title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Easy Python comment
lexicographically-smallest-equivalent-string
0
1
# Python\n```\nclass Solution:\n def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:\n val = string.ascii_lowercase\n d = {x: x for x in val}\n\n# Look up umtil we get d[x] == x, which is the lowest character lexi.\n def find(x):\n if d[x] == x: \n return x\n return find(d[x])\n\n for a,b in zip(s1,s2):\n l1, l2 = find(a),find(b)\n\n if l1 > l2: \n d[l1] = l2\n else: \n d[l2] = l1\n\n return "".join([find(d[i]) for i in baseStr])\n```
2
You are given two strings of the same length `s1` and `s2` and a string `baseStr`. We say `s1[i]` and `s2[i]` are equivalent characters. * For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`. Equivalent characters follow the usual rules of any equivalence relation: * **Reflexivity:** `'a' == 'a'`. * **Symmetry:** `'a' == 'b'` implies `'b' == 'a'`. * **Transitivity:** `'a' == 'b'` and `'b' == 'c'` implies `'a' == 'c'`. For example, given the equivalency information from `s1 = "abc "` and `s2 = "cde "`, `"acd "` and `"aab "` are equivalent strings of `baseStr = "eed "`, and `"aab "` is the lexicographically smallest equivalent string of `baseStr`. Return _the lexicographically smallest equivalent string of_ `baseStr` _by using the equivalency information from_ `s1` _and_ `s2`. **Example 1:** **Input:** s1 = "parker ", s2 = "morris ", baseStr = "parser " **Output:** "makkek " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[m,p\], \[a,o\], \[k,r,s\], \[e,i\]. The characters in each group are equivalent and sorted in lexicographical order. So the answer is "makkek ". **Example 2:** **Input:** s1 = "hello ", s2 = "world ", baseStr = "hold " **Output:** "hdld " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[h,w\], \[d,e,o\], \[l,r\]. So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld ". **Example 3:** **Input:** s1 = "leetcode ", s2 = "programs ", baseStr = "sourcecode " **Output:** "aauaaaaada " **Explanation:** We group the equivalent characters in s1 and s2 as \[a,o,e,r,s,c\], \[l,p\], \[g,t\] and \[d,m\], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada ". **Constraints:** * `1 <= s1.length, s2.length, baseStr <= 1000` * `s1.length == s2.length` * `s1`, `s2`, and `baseStr` consist of lowercase English letters.
Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position.
Simple | Python3 | Path Optimized Union Find | Commented
lexicographically-smallest-equivalent-string
0
1
# Approach\n\nSimple solution using Path Optimized Union Find structure.\n\n# Complexity\n\nn = len(s1) = len(s2)\nm = len(baseStr)\nk = len(alphabet)\n\n- Time complexity: O(k)[union find creation + groups loop + mapper loop] + O(n)[union loop] + O(m)[baseStr loop] = O(k + n + m)\n\n- Space complexity: O(k)[union find + groups + mapper] + O(m)[result] = O(k + m)\n\n# Code\n\n```\nfrom collections import defaultdict\n\n\nclass Solution:\n def smallestEquivalentString(\n self, s1: str, s2: str, baseStr: str\n ) -> str:\n # initialize Union Find\n union_find = UnionFind(26)\n # Go through `s1` and `s2` strings\n # for each symbol in s1, s2\n # - find symbol index by `ord` func\n # - union indices\n for i in range(len(s1)):\n c1 = ord(s1[i]) - ord("a")\n c2 = ord(s2[i]) - ord("a")\n union_find.union(c1, c2)\n # collect indices to groups by its parent\n groups = defaultdict(list)\n for i in range(26):\n groups[union_find.find(i)].append(i)\n # find minimum index for each group\n # add pair (index, minimum) to mapper\n mapper = {}\n for _, indices in groups.items():\n group_min = min(indices)\n for i in indices:\n mapper[i] = group_min\n # for each symbol in baseStr:\n # - find symbol index by `ord` func\n # - find new index by mapper\n # - restore index to symbol by `chr` func\n string = []\n for c in baseStr:\n i = mapper[ord(c) - ord("a")]\n string.append(chr(ord("a") + i))\n return "".join(string)\n\n\nclass UnionFind:\n """Path Optimized UnionFind."""\n def __init__(self, size: int) -> None:\n """time: O(size), space: O(size)"""\n self.root = [i for i in range(size)]\n self.rank = [1 for _ in range(size)]\n\n def find(self, node: int) -> int:\n """\n time: O(a(size)) ~ O(1), space: O(a(size)) ~ O(1)\n a(n) - Inverse-Ackermann function ~ O(1) in case of star-like graph, like here due to we create it from strach with this rule\n """\n if node == self.root[node]:\n return node\n self.root[node] = self.find(self.root[node])\n return self.root[node]\n\n def union(self, parent: int, node: int) -> None:\n """\n time: O(a(size)) ~ O(1), space: O(a(size)) ~ O(1)\n a(n) - Inverse-Ackermann function ~ O(1) in case of star-like graph, like here due to we create it from strach with this rule\n """\n root_parent = self.find(parent)\n root_node = self.find(node)\n if root_parent == root_node:\n return\n if self.rank[root_parent] > self.rank[root_node]:\n self.root[root_node] = root_parent\n elif self.rank[root_parent] < self.rank[root_node]:\n self.root[root_parent] = root_node\n else:\n self.root[root_node] = root_parent\n self.rank[root_parent] += 1\n\n```
1
You are given two strings of the same length `s1` and `s2` and a string `baseStr`. We say `s1[i]` and `s2[i]` are equivalent characters. * For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`. Equivalent characters follow the usual rules of any equivalence relation: * **Reflexivity:** `'a' == 'a'`. * **Symmetry:** `'a' == 'b'` implies `'b' == 'a'`. * **Transitivity:** `'a' == 'b'` and `'b' == 'c'` implies `'a' == 'c'`. For example, given the equivalency information from `s1 = "abc "` and `s2 = "cde "`, `"acd "` and `"aab "` are equivalent strings of `baseStr = "eed "`, and `"aab "` is the lexicographically smallest equivalent string of `baseStr`. Return _the lexicographically smallest equivalent string of_ `baseStr` _by using the equivalency information from_ `s1` _and_ `s2`. **Example 1:** **Input:** s1 = "parker ", s2 = "morris ", baseStr = "parser " **Output:** "makkek " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[m,p\], \[a,o\], \[k,r,s\], \[e,i\]. The characters in each group are equivalent and sorted in lexicographical order. So the answer is "makkek ". **Example 2:** **Input:** s1 = "hello ", s2 = "world ", baseStr = "hold " **Output:** "hdld " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[h,w\], \[d,e,o\], \[l,r\]. So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld ". **Example 3:** **Input:** s1 = "leetcode ", s2 = "programs ", baseStr = "sourcecode " **Output:** "aauaaaaada " **Explanation:** We group the equivalent characters in s1 and s2 as \[a,o,e,r,s,c\], \[l,p\], \[g,t\] and \[d,m\], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada ". **Constraints:** * `1 <= s1.length, s2.length, baseStr <= 1000` * `s1.length == s2.length` * `s1`, `s2`, and `baseStr` consist of lowercase English letters.
Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position.
🚀Super Easy Solution🚀||🔥Fully Explained🔥|| C++ || Python3 || Java
greatest-common-divisor-of-strings
1
1
# Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n First we check if str1 + str2 == str2 + str1\n If it is equal than if find the longest common substring.\n Otherwise we return "".\n# Approach\n<!-- Describe your approach to solving the problem. -->\n Suppose str1 = "ABCABC" and str2 = "ABC"\n str1 + str2 = ABCABCABC\n str2 + str1 = ABCABCABC\n str1 + str2 == str2 + str1\n return str.substr(0, gcd(size(str1), gcd(size(str2))))\n where gcd(3, 6) = 3\n So, answer is "ABC"\n\n Also str1 = "LEET", str2 = "CODE"\n str1 + str2 = "LEETCODE"\n str2 + str1 = "CODELEET"\n So, return ""\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n string gcdOfStrings(string str1, string str2) {\n // Check if concatenated strings are equal or not, if not return ""\n if(str1 + str2 != str2 + str1)\n return "";\n // If strings are equal than return the substring from 0 to gcd of size(str1), size(str2)\n return str1.substr(0, gcd(str1.size(), str2.size()));\n }\n};\n```\n```python []\nclass Solution:\n def gcdOfStrings(self, str1: str, str2: str) -> str:\n # Check if concatenated strings are equal or not, if not return ""\n if str1 + str2 != str2 + str1:\n return ""\n # If strings are equal than return the substring from 0 to gcd of size(str1), size(str2)\n from math import gcd\n return str1[:gcd(len(str1), len(str2))]\n\n```\n```Java []\nclass Solution {\n public String gcdOfStrings(String str1, String str2) {\n // Check if concatenated strings are equal or not, if not return ""\n if (!(str1 + str2).equals(str2 + str1))\n return "";\n // If strings are equal than return the substring from 0 to gcd of size(str1), size(str2)\n int gcd = gcd(str1.length(), str2.length());\n return str1.substring(0, gcd);\n }\n\n private int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n}\n\n```\n```\n Give a \uD83D\uDC4D. It motivates me alot\n```\nLet\'s Connect On [Linkedin](https://www.linkedin.com/in/naman-agarwal-0551aa1aa/)
502
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Python straightforward solution – 30 ms beats 97%
greatest-common-divisor-of-strings
0
1
# Intuition\n\n1) check if str2 * k = str1\n2) check if str2[: ...] * k2 = str2 and str1[: ...] * k1 = str1\n3) check if str2[:?] = str1[:?]\n3) check if strings consist of the same one letter\n\n# Code\n```\nclass Solution:\n def gcdOfStrings(self, str1: str, str2: str) -> str:\n\n s1 = max(str1, str2, key = lambda x: len(x))\n if s1 == str1:\n s2 = str2\n else:\n s2 = str1\n a1, a2 = len(s1), len(s2)\n\n if s2 * (a1//a2) == s1:\n return s2\n \n for i in range(2, a2//2 + 1):\n if (a2 / i) % 1 == 0:\n if s2[:a2//i]*i == s2:\n if s1[:a2//i]*int(i*a1/a2) == s1:\n if s2[:a2//i] == s1[:a2//i]:\n return s2[:a2//i] \n\n if s1.count(s1[0]) == a1:\n if s2.count(s2[0]) == a2:\n if s1[0] == s2[0]:\n return s1[0]\n\n return \'\'\n```
3
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Python Solution Using Recursion || Easy to Understand
greatest-common-divisor-of-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can use a **recursive** approach to find the **greatest common divisor of two strings**. \n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis is the idea behind the solution in simple points :\n\n- If concatenating **str1** and **str2** is **not equal** to concatenating **str2** and **str1**, then there\'s no common divisor possible. So, we return an empty string **""**.\n\n- If the lengths of **str1** and **str2** are **equal**, and the concatenated strings are **equal**, then **str1** (or **str2**) itself is the greatest common divisor, and we return **str1** (or **str2**).\n\n- If the length of **str1** is greater than the length of **str2**, it means that **str1** contains **str2** as a prefix. In this case, we **recurse** with the substring of **str1** after removing (slicing) the prefix that matches **str2**.\n\n- If the length of **str2** is greater than the length of **str1**, it means that **str2** contains **str1** as a prefix. In this case, we **recurse** with the substring of **str2** after removing (slicing) the prefix that matches **str1**.\n\n---\n\n![Screenshot 2023-08-29 231552.png](https://assets.leetcode.com/users/images/9523e72d-3779-4afb-b8fa-68232c33761a_1693331865.71453.png)\n\n![Screenshot 2023-08-29 231620.png](https://assets.leetcode.com/users/images/fa7498db-0ee7-46df-9c36-5ebaf7b80e83_1693331887.4960327.png)\n\n\n\n---\n\n\n# Complexity\n- Time complexity: **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n\n# Code\n```\nclass Solution(object):\n def gcdOfStrings(self, str1, str2):\n if str1 + str2 != str2 + str1:\n return ""\n if len(str1) == len(str2):\n return str1\n if len(str1) > len(str2):\n return self.gcdOfStrings(str1[len(str2):], str2)\n return self.gcdOfStrings(str1, str2[len(str1):])\n\n```
33
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Easy to understand Python3 solution
flip-columns-for-maximum-number-of-equal-rows
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n d = {}\n ans = 0\n\n for i in range(len(matrix)):\n if matrix[i][0] == 0:\n for j in range(len(matrix[i])):\n if matrix[i][j] == 0:\n matrix[i][j] = 1\n elif matrix[i][j] == 1:\n matrix[i][j] = 0\n \n if tuple(matrix[i]) in d:\n d[tuple(matrix[i])] += 1\n else:\n d[tuple(matrix[i])] = 1\n \n print(d)\n\n return max(d.values())\n```
0
You are given an `m x n` binary matrix `matrix`. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa). Return _the maximum number of rows that have all values equal after some number of flips_. **Example 1:** **Input:** matrix = \[\[0,1\],\[1,1\]\] **Output:** 1 **Explanation:** After flipping no values, 1 row has all values equal. **Example 2:** **Input:** matrix = \[\[0,1\],\[1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first column, both rows have equal values. **Example 3:** **Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first two columns, the last two rows have equal values. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is either `0` or `1`.
We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j .
Python 1 line Solution!!!
flip-columns-for-maximum-number-of-equal-rows
0
1
\n# Code\n```\nclass Solution:\n def maxEqualRowsAfterFlips(self, A):\n return max(collections.Counter(tuple(x ^ r[0] for x in r) for r in A).values())\n```
0
You are given an `m x n` binary matrix `matrix`. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa). Return _the maximum number of rows that have all values equal after some number of flips_. **Example 1:** **Input:** matrix = \[\[0,1\],\[1,1\]\] **Output:** 1 **Explanation:** After flipping no values, 1 row has all values equal. **Example 2:** **Input:** matrix = \[\[0,1\],\[1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first column, both rows have equal values. **Example 3:** **Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first two columns, the last two rows have equal values. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is either `0` or `1`.
We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j .
bitmask python 94%
flip-columns-for-maximum-number-of-equal-rows
0
1
\n# Code\n```\nclass Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n hm = defaultdict(int)\n for r in matrix:\n if r[0] == 1:\n r = [not b for b in r]\n r = bytes(r)\n hm[r]+=1\n \n return max(hm.values())\n\n\n\n```
0
You are given an `m x n` binary matrix `matrix`. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa). Return _the maximum number of rows that have all values equal after some number of flips_. **Example 1:** **Input:** matrix = \[\[0,1\],\[1,1\]\] **Output:** 1 **Explanation:** After flipping no values, 1 row has all values equal. **Example 2:** **Input:** matrix = \[\[0,1\],\[1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first column, both rows have equal values. **Example 3:** **Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first two columns, the last two rows have equal values. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is either `0` or `1`.
We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j .
Simple Python 100% beat solution
flip-columns-for-maximum-number-of-equal-rows
0
1
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(mn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(m)\n\n# Code\n```\nclass Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n d = collections.defaultdict(int)\n n = len(matrix[0])\n for row in matrix:\n x = 0\n for i in reversed(row):\n x <<= 1\n x += i\n d[x] += 1\n d[x ^ ((1 << n) - 1)] += 1\n return max(d.values())\n \n```
0
You are given an `m x n` binary matrix `matrix`. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa). Return _the maximum number of rows that have all values equal after some number of flips_. **Example 1:** **Input:** matrix = \[\[0,1\],\[1,1\]\] **Output:** 1 **Explanation:** After flipping no values, 1 row has all values equal. **Example 2:** **Input:** matrix = \[\[0,1\],\[1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first column, both rows have equal values. **Example 3:** **Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first two columns, the last two rows have equal values. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is either `0` or `1`.
We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j .
Solution
flip-columns-for-maximum-number-of-equal-rows
1
1
```C++ []\nclass Solution {\npublic:\n int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int m=matrix.size(), n=matrix[0].size(), ans=0;\n unordered_map<bitset<300>, int> sts;\n for(int i=0, j; i<m; ++i) {\n bitset<300> conf;\n for(j=1; j<n; ++j) {\n conf[j]=matrix[i][j]!=matrix[i][0];\n }\n ans=max(ans, ++sts[conf]);\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n return collections.Counter(tuple(row if row[0] == 0 else map(operator.not_, row)) for row in matrix).most_common(1)[0][1]\n```\n\n```Java []\nclass Solution {\n class Trie {\n Trie left, right;\n int cnt;\n }\n public int maxEqualRowsAfterFlips(int[][] matrix) {\n Trie root = new Trie();\n int m = matrix.length, n = matrix[0].length;\n int ans = 0;\n for (int i = 0; i < m; i++) {\n Trie trie = root;\n for (int j = 0; j < n; j++) {\n if (matrix[i][j] == matrix[i][0]) {\n if (trie.left == null) {\n trie.left = new Trie();\n }\n trie = trie.left;\n } else {\n if (trie.right == null) {\n trie.right = new Trie();\n }\n trie = trie.right;\n }\n }\n trie.cnt++;\n ans = Math.max(ans, trie.cnt);\n }\n return ans;\n }\n}\n```
0
You are given an `m x n` binary matrix `matrix`. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa). Return _the maximum number of rows that have all values equal after some number of flips_. **Example 1:** **Input:** matrix = \[\[0,1\],\[1,1\]\] **Output:** 1 **Explanation:** After flipping no values, 1 row has all values equal. **Example 2:** **Input:** matrix = \[\[0,1\],\[1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first column, both rows have equal values. **Example 3:** **Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first two columns, the last two rows have equal values. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is either `0` or `1`.
We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j .
Memo with O(R*C) Time and Space | Commented and Explained
flip-columns-for-maximum-number-of-equal-rows
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt first look, this is a really hard seeming question. However, it can be made simpler if we look at it in the eyes of a backtracking question. If we were to take a row at its current form, we would add to the number of times that this row would be accepted. Similarly, if we were to flip the values of this row, we would add to the valuations of this rows flipped form. This is a situation though where we don\'t need to backtrack, merely consider the path in both directions at once. \n\nThis can be achieved with a memo and iterating over the rows of the matrix as we go along. To do this we need to store the results of the rows valuations. We can use the string form of the row and their transition form as the keys to our memo then, and then at end simply return maximum valuation (we were not asked which string was most, just what was the most! Tricky wording indeed!)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSet up a memo as a default dict of integers so it starts with 0 initialized and we never need to specify if a key is in the dictionary or not. \n\nLoop over the rows of the matrix \n- the row transition is a list of 1-val for val in the current row \n- increment our memo by 1 at the string cast of the row \n- increment our memo by 1 at the string cast of the row transition\n\nAt end, return the maximum value from the values of the memo! \n\n# Complexity\n- Time complexity: O(R*C) \n - We need to iterate over R rows \n - At each row, we need to stringify the row, taking time C\n - We do this inside of R, so R*C\n\n- Space complexity: O(R*C)\n - We store R rows \n - Of size C for the keys \n - So O(R*C) \n\n# Code\n```\nclass Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n # memoize results as we go \n memo = collections.defaultdict(int)\n # collect each row of the matrix \n for row in matrix : \n # as you collect it, get the row transitions\n row_transitions = [1-val for val in row]\n # memoize the results \n # either you\'ve seen this and increment or now see it and increment\n # same for the transition version where you flip values \n memo[str(row)] += 1 \n memo[str(row_transitions)] += 1\n # at end, return max memo values \n return max(memo.values())\n```
0
You are given an `m x n` binary matrix `matrix`. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa). Return _the maximum number of rows that have all values equal after some number of flips_. **Example 1:** **Input:** matrix = \[\[0,1\],\[1,1\]\] **Output:** 1 **Explanation:** After flipping no values, 1 row has all values equal. **Example 2:** **Input:** matrix = \[\[0,1\],\[1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first column, both rows have equal values. **Example 3:** **Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first two columns, the last two rows have equal values. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is either `0` or `1`.
We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j .
Clean Python | 1 Line | High Speed | O(n) time, O(1) space
flip-columns-for-maximum-number-of-equal-rows
0
1
# Code\n```\nclass Solution:\n def maxEqualRowsAfterFlips(self, A):\n return max(collections.Counter(tuple(x ^ r[0] for x in r) for r in A).values())\n```
0
You are given an `m x n` binary matrix `matrix`. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa). Return _the maximum number of rows that have all values equal after some number of flips_. **Example 1:** **Input:** matrix = \[\[0,1\],\[1,1\]\] **Output:** 1 **Explanation:** After flipping no values, 1 row has all values equal. **Example 2:** **Input:** matrix = \[\[0,1\],\[1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first column, both rows have equal values. **Example 3:** **Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\] **Output:** 2 **Explanation:** After flipping values in the first two columns, the last two rows have equal values. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is either `0` or `1`.
We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j .
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9%
adding-two-negabinary-numbers
0
1
# Code\n```\nclass Solution:\n def addBinary(self, A, B):\n res = []\n carry = 0\n while A or B or carry:\n carry += (A or [0]).pop() + (B or [0]).pop()\n res.append(carry & 1)\n carry = carry >> 1\n return res[::-1]\n\n def addNegabinary(self, A, B):\n res = []\n carry = 0\n while A or B or carry:\n carry += (A or [0]).pop() + (B or [0]).pop()\n res.append(carry & 1)\n carry = -(carry >> 1)\n while len(res) > 1 and res[-1] == 0:\n res.pop()\n return res[::-1]\n```
1
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
Rule based
adding-two-negabinary-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRule based solution\n\n\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n l = max(len(arr1), len(arr2)) + 2\n arr1 = [0] * (l - len(arr1)) + arr1\n arr2 = [0] * (l - len(arr2)) + arr2\n\n res = [0] * l\n for i in range(l-1, -1, -1):\n if arr1[i] + arr2[i] + res[i] == 3:\n res[i] = 1\n res[i-1] -= 1\n elif arr1[i] + arr2[i] + res[i] == 2:\n res[i] = 0\n res[i-1] -= 1\n elif arr1[i] + arr2[i] + res[i] == 1:\n res[i] = 1\n elif arr1[i] + arr2[i] + res[i] == 0:\n res[i] = 0\n elif arr1[i] + arr2[i] + res[i] == -1:\n res[i] = 1\n res[i-1] = 1\n \n for i in range(l):\n if res[i] != 0:\n return(res[i:])\n return([0])\n\n\n\n\n\n\n\n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
Solution
adding-two-negabinary-numbers
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> addNegabinary(vector<int> &arr1, vector<int> &arr2)\n {\n reverse(arr1.begin(), arr1.end());\n reverse(arr2.begin(), arr2.end());\n if (arr1.size() < arr2.size())\n swap(arr1, arr2);\n int carry = 0;\n for (int i = 0; i < arr1.size(); i++)\n {\n int cur = arr1[i];\n if (i < arr2.size())\n cur += arr2[i];\n if (cur == 0 && carry == -1)\n {\n arr1[i] = 1;\n carry = 1;\n }\n else\n {\n arr1[i] = (cur + carry) % 2;\n carry = -(cur + carry >= 2);\n }\n }\n if (carry != 0)\n arr1.push_back(1);\n if (carry == -1)\n arr1.push_back(1);\n while (arr1.size() > 1 && arr1.back() == 0)\n arr1.pop_back();\n reverse(arr1.begin(), arr1.end());\n return arr1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def addBinary(self, A, B):\n res = []\n carry = 0\n while A or B or carry:\n carry += (A or [0]).pop() + (B or [0]).pop()\n res.append(carry & 1)\n carry = carry >> 1\n return res[::-1]\n\n def addNegabinary(self, A, B):\n res = []\n carry = 0\n while A or B or carry:\n carry += (A or [0]).pop() + (B or [0]).pop()\n res.append(carry & 1)\n carry = -(carry >> 1)\n while len(res) > 1 and res[-1] == 0:\n res.pop()\n return res[::-1]\n```\n\n```Java []\nclass Solution {\n public int[] addNegabinary(int[] arr1, int[] arr2) {\n \n List<Integer> result = new ArrayList();\n int pointer_1 = arr1.length-1;\n int pointer_2 = arr2.length-1;\n\n int carry = 0;\n int current = 0;\n int sum = 0;\n \n while(pointer_1 >= 0 || pointer_2 >= 0){\n \n int a = (pointer_1 >=0)? arr1[pointer_1]: 0;\n int b = (pointer_2 >=0)? arr2[pointer_2]: 0;\n \n sum = a+b+carry;\n if(sum == 3){\n current = 1; carry = -1;\n }\n else if(sum == 2){\n current = 0; carry = -1;\n }\n else if(sum == 1){\n current = 1; carry = 0;\n }\n else if(sum == 0){\n current = 0; carry = 0;\n }\n else if(sum == -1)\n {\n current = 1; carry = 1;\n }\n result.add(current);\n pointer_1--;\n pointer_2--;\n }\n if(carry != 0)\n result.add(1);\n if(carry == -1)\n result.add(1);\n \n int idx = result.size()-1;\n while(idx > 0 && result.get(idx) == 0)\n idx--;\n \n int len = idx+1;\n int[] negaBinary = new int[len];\n for(int i=0; i<len; i++){\n negaBinary[i] = result.get(idx);\n idx--;\n }\n return negaBinary;\n }\n}\n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
[LC-1073-M | Python3] A Plain Solution
adding-two-negabinary-numbers
0
1
It can be treated as a direct follow-up of [LC-1017](https://leetcode.cn/problems/convert-to-base-2/).\n\n```Python3 []\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n v1 = v2 = 0\n i1 = i2 = 0\n for num1 in arr1[::-1]:\n v1 += num1 * (-2)**i1\n i1 += 1\n for num2 in arr2[::-1]:\n v2 += num2 * (-2)**i2\n i2 += 1\n v = v1 + v2\n\n res = [] if v else [0]\n while v:\n res.append(rem := v & 1)\n v = (v - rem) // -2\n \n return res[::-1]\n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
python basic math
adding-two-negabinary-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAssumption from basic math\n\n9 = a * (-2) ** x + b * (-2) ** (x-1) + c * (-2) ** (x-2) + ... + 1 \n=> do mod 2 to find last digit => will get 1\n=> new total will be 9 // 2 = 4\n4 = a ** (-2) ** (x-1) + b ** (-2) ** (x-2) + ... + -k => -1 time 2 sides\nfind k by mod2 both side\n-4 = .... + k\n=> repeat the process until total == 0\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n n1 = 0\n power = 0\n for i in range(len(arr1)-1, -1, -1):\n n1 += arr1[i] * (-2) ** power\n power += 1\n\n n2 = 0\n power = 0\n for i in range(len(arr2)-1, -1, -1):\n n2 += arr2[i] * (-2) ** power\n power += 1\n\n total = n1 + n2\n ans = []\n while total != 0:\n rem = abs(total % 2)\n total = total // 2\n ans.append(rem)\n total *= -1\n\n if not ans:\n return [0]\n\n return ans[::-1]\n\n"""\nAssumption from basic math\n\n9 = a * (-2) ** x + b * (-2) ** (x-1) + c * (-2) ** (x-2) + ... + 1 \n=> do mod 2 to find last digit => will get 1\n=> new total will be 9 // 2 = 4\n4 = a ** (-2) ** (x-1) + b ** (-2) ** (x-2) + ... + -k => -1 time 2 sides\nfind k by mod2 both side\n-4 = .... + k\n=> repeat the process until total == 0\n"""\n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
2s complement | Commented and Explained | Convert from -2 base then convert back
adding-two-negabinary-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to first know what values we have \nThen, we want to know what we sum up to \nThen, we want to convert from where we are to where we want to go \nWe can do this with two functions and a few calls as detailed below. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst we build our convert from negative form function \nThis function takes in an array to convert that is assumed to be in base -2. We have no way to check that in the current problem, so we take it on faith. Then, the following occurs \n- Our place value starts in the 1s place for any base (as anything to the power of 0, even a negative base, is 0) \n- Our return valuation starts at 0, and we will adjust from there \n- Then, we reverse our array (could also chose to read from the back, but good to call it when it occurs for readability) \n- Then, for bit in array to convert \n - return valuation is incremented by the product of the bit with the place value \n - place value is incremented as the product of itself with -2 \nWhen done, return return valuation \n\nNow that we have that, we get the array valuations \nDo this for array 1 and array 2 and make sure they match by hand. I have removed the print statements, but you could print these out after and then check. Once this is working correctly, we sum these valuations up as sum of arrays. \n\nNow we build our convert to negative form function which is given a value to convert and returns an array in base -2. To do so, we do the following\n- if value to convert is 0, return [0]\n- otherwise, set a negative form array as a deque\n- while your value to convert is not zero (meaning we are out of material)\n - update value to convert and get the remainder from the update as the result of a call to divmod, passing in value to convert and -2 as arguments\n - if our remainder is less than 0, it must be -1. \n - if our remainder is negative 1 \n - our value to convert is 1 greater than before (carry operation)\n - remainder then is set to 1 \n - append the remainder to the front of the negative form array \n- when done, we have our array, return it \n\n# Complexity\n- Time complexity: O(N) \n - each array is converted \n - the summation is converted back \n - both take linear time \n\n\n- Space complexity: O(N) \n - we end up creating an array to store the solution of size O(N) \n\n# Code\n```\n"""\n array valuation example walkthrough \n for the first problem, we are given \n [1, 1, 1, 1, 1]\n and \n [1, 0, 1]\n\n If we evaluate the converted form of these, the first is 11 and the second is 5 \n This gives a form of 16 in base of -2 \n in base of -2, 16 is -2^4 \n Remembering that we start at power 0, this as an array is then \n [1, 0, 0, 0, 0]\n\n Where we can notice that even powers of -2 will be the same as the regular powers of positive 2 \n This should come as no surprise if you have studied 2\'s complement which the problem is based on\n Learn more here : https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html \n\n"""\n\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n # converts from negative binary form array to a valuation\n def convert_from_negative_form(array_to_convert) : \n place_value = 1\n return_valuation = 0\n array_to_convert.reverse()\n for bit in array_to_convert : \n return_valuation += bit * place_value \n place_value *= -2\n return return_valuation\n\n # get array valuations \n array_1_valuation = convert_from_negative_form(arr1)\n array_2_valuation = convert_from_negative_form(arr2)\n # sum them \n sum_of_arrays = array_1_valuation + array_2_valuation\n \n # converts from value to convert to array form in 2s complement form \n def convert_to_negative_form(value_to_convert) : \n # base case \n if value_to_convert == 0 : \n return [0]\n # set up for return \n negative_form_array = collections.deque()\n # build negative_form_array while not 0 \n while value_to_convert != 0 : \n # update value to convert \n value_to_convert, remainder = divmod(value_to_convert, -2)\n # remainder is either -1 or 0 \n # if it is 0 we\'re good, \n # but if not we need to account for overflow \n if remainder < 0 : \n # shift value to convert forward on remainder -1 \n value_to_convert += 1 \n # cannot place -1 in binary array, but can place 1\n remainder = 1\n # append remainder as this is the 2s complement left over \n negative_form_array.appendleft(remainder)\n # return when done \n return negative_form_array \n\n # get valuation \n negative_array = convert_to_negative_form(sum_of_arrays)\n # return negative array \n return negative_array \n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
Concise code with detailed comments - Python3
adding-two-negabinary-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse `0b11` instead of `0b01` as the carry number.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOne-pass iteration, need care for processing the carry number. If need to carry bit, use `0b11` instead of `0b01`, if the carry number already have `0b01`, then the value cancels, see proof and explaination in comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```python\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n \'\'\'\n since base is -2, so carry is 0b11 instead of typical 0b1\n \'\'\'\n rev, carry = [], 0\n for a, b in zip_longest(reversed(arr1), reversed(arr2)):\n a, b = a if a else 0, b if b else 0 # eliminate None\n val, carry = a + b + (carry & 1), carry >> 1\n rev.append(val & 1)\n if val > 1:\n \'\'\'\n for higher bit of carry is 1, lower bit of carry is 2 and want to increase\n it will cancel to 0. e.g. 0b01 + 0b11, it means (1) + (-2 + 1) = 0.\n fix lower bit to 1, all comb are:\n 0b01 + 0b01 = 0b11(0)\n 0b11 + 0b01 = 0b00 -> cancel value\n 0b01 + 0b11 -> same as above but rev order\n 0b11 + 0b11 -> not possible since carry is right-shifted\n \'\'\'\n carry = (carry + 0b11) % 4\n # process remaining carry\n while carry:\n rev.append(carry & 1)\n carry //= 2\n \n # remove leading zeros\n while len(rev) > 1 and rev[-1] == 0:\n rev.pop()\n \n return list(reversed(rev))\n\n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
[python] Adding-converting Base-2
adding-two-negabinary-numbers
0
1
For Elaborate Explanation: [SIMILAR QUESTION]\n[1017 Convert to Base -2](https://leetcode.com/problems/convert-to-base-2/solutions/3133597/baseneg2-python/?orderBy=hot)\n\n# Code\n```\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n\n n = 0 \n res = []\n while arr1 or arr2 or n:\n if not arr1: arr1 = [0] # if empty \n if not arr2: arr2 = [0]\n\n total = arr1.pop() + arr2.pop() + n\n res.append(total%2)\n n = -(total//2)\n\n while( len(res)>1 and res[-1]==0): #before reverse : removing leading 0\'s\n res.pop()\n res.reverse()\n return res\n\n## BY MANUALLY CALCULATING ARR1 AND ARR2 WE CAN USE TOTAL VALUE HERE TO CALCULATE @baseNeg2\n def baseNeg2(self, n):\n if n == 0: return "0"\n res = []\n while n:\n # option - 1\n res.append(str(n & 1)) \n n = -(n >> 1) \n \'\'\' only return 1 or 0\n - Minus 1 form n, if last digit is 1.\n - Divide N by 2.\n \'\'\'\n\n # option - 2\n # if(abs(n%2) == 1):\n # res.append(str(1))\n # n = (n-1)/-2\n # else:\n # res.append(str(0))\n # n = n/-2\n return "".join(res[::-1])\nL\n\n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
[Python] Using math
adding-two-negabinary-numbers
0
1
The way I use is essentially [0, 0, 2] = [1, 1, 0]. With multiplications also work, such as [1, 0, 6] = [4, 3, 0] = [1, 5, 1, 0] = [2, 3, 1, 1, 0] = ...\n\n```\nfrom itertools import zip_longest\n\n\nclass Solution:\n def addNegabinary(self, arr1, arr2):\n arr1.reverse()\n arr2.reverse()\n result = [i + j for i, j in zip_longest(arr1, arr2, fillvalue=0)]\n result += [0 for i in range(len(result))] + [0, 0]\n for index, num in enumerate(result):\n if num == 1 or num == 0:\n continue\n if num == result[index + 1] * 2:\n result[index] = 0\n result[index + 1] = 0\n continue\n divide, remain = divmod(num, 2)\n result[index + 1] += divide\n result[index + 2] += divide\n result[index] = remain\n while len(result) > 1 and result[-1] == 0:\n result.pop()\n result.reverse()\n return result\n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
The way we learned in elementary school.
adding-two-negabinary-numbers
0
1
# Intuition\nIt works the same way we learned to add two numbers in elementary school, starting with the least significant digits and carrying over a remainder as we go. In fact, if you replaced `2` and `-2` with `10` on lines 9 and 12 below, what you\'d end up with is probably what you\'d write if you were asked to add two lists representing base 10 numbers (assuming no conversion to int and back allowed).\n\nThe only consideration when using a negative base is that negative numbers can be represented without a minus sign, so it\'s possible we could find ourselves adding a negative number and a positive number, in which case we could end up with leading zeros with this procedure. This would happen in the same way that we might get $$901 + (-900) = 001$$ when adding this way in regular old base 10. We have to take care of this by popping the extra zeros off in a short loop at the end.\n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1) additional space.\n\n# Code\n```\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n # build up digits of result as an initially reversed list.\n result, carryover = [], 0\n while arr1 or arr2 or carryover:\n d1 = arr1.pop() if arr1 else 0\n d2 = arr2.pop() if arr2 else 0\n val = d1 + d2 + carryover\n digit = val % 2\n result.append(digit)\n remainder = val - digit\n carryover = remainder // -2\n\n # remove leading zeros.\n while len(result) > 1 and result[-1] == 0:\n result.pop()\n \n return list(reversed(result))\n \n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
Fast Python with explanation || Beats 90% of python submissions in runtime and memory.
adding-two-negabinary-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is important to think of this as an addition of exponentials with a base of -2. The exponentials with base 2 can be written as.\n$[0:1, 1:-2, 2:4, 3:-8, 4:16, 5:-32]$\n\nWhen we add two negative binary numbers we can get instances where the sum has two of the same negative binaries.\nEx:\n$[1,1] + [1] = [1,2]$\nThis is an issue as we would need to remove the two so that the number can be written as an array of 0s and 1s.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can notice that each duplicated negative binary number can be written as:\nEx:\n$2(-2^i) = (-2^(i+1)) + (-2^(i+2) $\n\nThus, the above example can be written as:\n$[1,2,0]$\n\nHowever, there is still a two there and we need to get rid of that two. We notice also that if a duplicated negative binary number also has another negative binary number that has an exponent of $i+1$ in the array, then we can simplify. Notice that $i$ is the place value and not the index of the array. You can also imagine that the array is reverse when $i$ is mentioned.\n\n$2(-2^i) = -1*(-2^(i+1))$\n\nThis would mean that if a duplicated negative binary number has another negative binary number that has an exponent of $i+1$ in the array, then we can eliminate both. Thus,\n$[1,2,0]$\nbecomes \n$[0,0,0]$\nSince, there should be no leading zeroes, we would get rid of them. The answer is now $[0]$.\n\nWe would prefer the second way of removing duplicate binary numbers since it always removes numbers. The first way adds one to the $i+1$th and $i+2$th exponents. This may result in an infinite loop of [1,2] being moved up in the array of negative binary numbers. This is seen in the example above where [1,2] became [1,2,0]. Using the first method would not simplify. We would only use the first method if the second method would result in a negative for the $i+1$th place when getting rid of duplicate negative binaries. In that case the $i+1$th place would have a zero and adding one would result in one being in the $i+1$th place. This does not violate the requirement of the array being 1s and 0s. Adding one to the $i+2$th place would be acceptable since the value is not being rewritten by shifting the numbers as in the above example. if the $i+2$th place will be greater than 1, we can reduce the value at that position with the aforementioned methods.\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\nWe scan and modify values as we go through one sweap of an array.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\nWe would be adding to the larger array. If there is no larger array, then any array will do. If there is no larger array then any array will do. We may add to the array, but that is negligible.,\n# Code\n```\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n arr1.reverse()\n arr2.reverse()\n leng1 = len(arr1)\n leng2 = len(arr2)\n n = max(leng1,leng2)\n lower = min(leng1,leng2)\n\n if lower == leng1:\n arr3 = arr2\n for i in range(lower):\n arr3[i] += arr1[i]\n else:\n arr3 = arr1\n for i in range(lower):\n arr3[i] += arr2[i]\n\n\n count = 0\n\n while True:\n leng = len(arr3)\n if count == (leng - 1) and arr3[count] <= 1:\n arr3.reverse()\n while len(arr3) > 1 and arr3[0] == 0:\n arr3 = arr3[1:]\n\n return arr3\n\n while arr3[count] > 1:\n leng = len(arr3)\n if count > leng-3:\n diff = leng - count\n lp = 3- diff\n for i in range(lp):\n arr3.append(0)\n\n if arr3[count] > 1 and arr3[count+1]>0:\n arr3[count]-=2\n arr3[count+1]-=1\n continue\n\n arr3[count+1] += 1\n arr3[count +2] += 1\n arr3[count] -= 2\n count +=1\n\n \n\n\n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
Python solution with Math proof
adding-two-negabinary-numbers
0
1
# Intuition\nThis need 2 carries and some math, need to handle 2 cases: \n- 1 + 1 = 110\n- 1 + 11 = 0\n# Approach\nHandle all scenario by gating the second carry, see the comment lines of the solution below.\n\n# Complexity\n- Time complexity:$$O(n)$$ where $$n = max(len(arr1), len(arr2))$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n """\n this negabinary base need two carries, why? Because\n 1 + 1 = 110\n in math formula: (-2)^n + (-2)^n = (1-2) * (-2) * (-2)^n = (1 - 2)* (-2)^(n+1)\n = (-2)^(n+1) + (-2)^(n+2) \n one special thing is: 1 + 11 = 0\n that can also be proven by math in general form\n so at each digit addition from right to left we have formula below: \n (x, y are digit from arr1 and arr2 respectively)\n x \n +\n y\n + \n c2 c1\n\n where c1, and c2 are two caries\n and we have the following cases:\n if c2 = 0:\n if x + y + c1 <= 1:\n val = x + y + c1 \n next_c1 = c2 = 0, next_c2 = 0 (there is nothing to carry)\n if x + y + c1 = 2:\n val = 0\n next_c1 = c2 = 1, next_c2 = 1 (case 1+1 = 110)\n if x + y + c1 = 3:\n val = 1\n next_c1 = c2 = 1, next_c2 = 1 (also case 1+1 = 110, then plus 1 which is 111)\n if c2 = 1:\n if x + y + c1 <= 1:\n val = x + y + c1 \n next_c1 = c2 = 1\n next_c2 = 0\n if x + y + c1 = 2:\n val = 0\n next_c1 = c2 = 0, next_c2 = 0 (case 1 + 11 = 0)\n if x + y + c1 = 3:\n val = 1\n next_c1 = c2 = 0, next_c2 = 0 (also case 1 + 11 + 1 = 0 + 1 = 1)\n\n """\n c1, c2 = 0, 0\n res = []\n while arr1 or arr2 or c1 or c2:\n x = (arr1 or [0]).pop()\n y = (arr2 or [0]).pop()\n res.append((x + y + c1)%2)\n if c2 == 0: \n if x + y + c1 <= 1:\n c1, c2 = 0, 0 \n if x + y + c1 >= 2:\n c1, c2 = 1, 1\n elif c2 == 1: \n if x + y + c1 <= 1: \n c1, c2 = c2, 0\n if x + y + c1 >= 2: \n c1, c2 = 0, 0\n \n # remove leading zero\n while len(res) > 1 and res[-1] == 0:\n res.pop()\n \n return res[::-1]\n```
0
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
Python 3 | Math, Two Pointers | Explanation
adding-two-negabinary-numbers
0
1
### Explanation\n- Math fact for -2 based numbers\n\t- `1 + 1 = 0, carry -1`\n\t- `-1 + 0 = 1, carry 1` \n\t- `1 + 0 = 1, carry 0`\n\t- `0 + 0 = 0, carry 0`\n\t- `0 + 1 = 1, carry 0`\n\t- `-1 + 1 = 0, carry 0`\n\t- `-1 + -1 is not possible`\n- Based on above fact, we can do a two pointer addition from right to left\n- Remember to count the `carry` and remove the leading `0` before return the answer\n### Implementation\n```\nclass Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n ans = list()\n m, n = len(arr1), len(arr2)\n i, j = m-1, n-1\n def add(a, b): # A helper function to add -2 based numbers\n if a == 1 and b == 1:\n cur, carry = 0, -1\n elif (a == -1 and b == 0) or (a == 0 and b == -1): \n cur = carry = 1\n else: \n cur, carry = a+b, 0\n return cur, carry # Return current value and carry\n carry = 0\n while i >= 0 or j >= 0: # Two pointers from right side\n cur, carry_1, carry_2 = carry, 0, 0\n if i >= 0:\n cur, carry_1 = add(cur, arr1[i])\n if j >= 0: \n cur, carry_2 = add(cur, arr2[j])\n carry = carry_1 + carry_2\n ans.append(cur)\n i, j = i-1, j-1\n ans = [1,1] + ans[::-1] if carry == -1 else ans[::-1] # Add [1, 1] if there is a carry -1 leftover\n for i, v in enumerate(ans): # Remove leading zero and return\n if v == 1:\n return ans[i:]\n else:\n return [0]\n```
2
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
occurrences-after-bigram
occurrences-after-bigram
0
1
\n# Code\n```\nclass Solution:\n def findOcurrences(self, s: str, first: str, second: str) -> List[str]:\n a = s.split()\n l = []\n for i in range(len(a)-2):\n if a[i]==first and a[i+1]==second:\n l.append(a[i+2])\n return l\n\n\n```
1
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`. Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`. **Example 1:** **Input:** text = "alice is a good girl she is a good student", first = "a", second = "good" **Output:** \["girl","student"\] **Example 2:** **Input:** text = "we will we will rock you", first = "we", second = "will" **Output:** \["we","rock"\] **Constraints:** * `1 <= text.length <= 1000` * `text` consists of lowercase English letters and spaces. * All the words in `text` a separated by **a single space**. * `1 <= first.length, second.length <= 10` * `first` and `second` consist of lowercase English letters.
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
Python 3
occurrences-after-bigram
0
1
```\nclass Solution(object):\n def findOcurrences(self, text, first, second):\n """\n :type text: str\n :type first: str\n :type second: str\n :rtype: List[str]\n """\n if not text:\n return \n results = []\n text = text.split(" ")\n for i in range(len(text)-2):\n if text[i] == first and text[i+1] == second:\n results.append(text[i+2])\n return results\n \n```
20
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`. Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`. **Example 1:** **Input:** text = "alice is a good girl she is a good student", first = "a", second = "good" **Output:** \["girl","student"\] **Example 2:** **Input:** text = "we will we will rock you", first = "we", second = "will" **Output:** \["we","rock"\] **Constraints:** * `1 <= text.length <= 1000` * `text` consists of lowercase English letters and spaces. * All the words in `text` a separated by **a single space**. * `1 <= first.length, second.length <= 10` * `first` and `second` consist of lowercase English letters.
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
Beats 98.6% in runtime and 80% in memory!!! 7 Lines of code!!! Super Easy!!!
occurrences-after-bigram
0
1
# Approach\nif the first and second match, add the third to final list!\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def findOcurrences(self, text: str, first: str, second: str) -> List[str]:\n text = text.split(" ")\n f = []\n for i in range(1, len(text)-1):\n if text[i] == second and text[i-1] == first:\n f.append(text[i+1])\n i+=1\n return f\n```
0
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`. Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`. **Example 1:** **Input:** text = "alice is a good girl she is a good student", first = "a", second = "good" **Output:** \["girl","student"\] **Example 2:** **Input:** text = "we will we will rock you", first = "we", second = "will" **Output:** \["we","rock"\] **Constraints:** * `1 <= text.length <= 1000` * `text` consists of lowercase English letters and spaces. * All the words in `text` a separated by **a single space**. * `1 <= first.length, second.length <= 10` * `first` and `second` consist of lowercase English letters.
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
Beats 93% of python solutions, Very Simple
occurrences-after-bigram
0
1
# Approach\nMake a list of the string and split it into each word. Loop through each word and check if index equals target 1 and index + 1 equals target two.\n\nIf they do add index + 2 to the result list. When we have looped through the list, to len(str) - 2, return the result list\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def findOcurrences(self, text: str, first: str, second: str) -> List[str]:\n lst = text.split(" ")\n result = []\n\n for ind, char in enumerate(lst):\n if ind < len(lst) + 2:\n if ind + 2 > len(lst) - 1:\n break\n if lst[ind] == first and lst[ind + 1] == second:\n result.append(lst[ind + 2])\n \n return result\n```
0
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`. Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`. **Example 1:** **Input:** text = "alice is a good girl she is a good student", first = "a", second = "good" **Output:** \["girl","student"\] **Example 2:** **Input:** text = "we will we will rock you", first = "we", second = "will" **Output:** \["we","rock"\] **Constraints:** * `1 <= text.length <= 1000` * `text` consists of lowercase English letters and spaces. * All the words in `text` a separated by **a single space**. * `1 <= first.length, second.length <= 10` * `first` and `second` consist of lowercase English letters.
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
easy python code beats 91.8%
occurrences-after-bigram
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findOcurrences(self, text: str, first: str, second: str) -> List[str]:\n s=[]\n l=text.split(" ")\n l=list(l)\n for i in range(2,len(l)):\n print(l[i-2],l[i-1])\n if l[i-2]==first and l[i-1]==second:\n s.append(l[i])\n return s\n\n \n```
0
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`. Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`. **Example 1:** **Input:** text = "alice is a good girl she is a good student", first = "a", second = "good" **Output:** \["girl","student"\] **Example 2:** **Input:** text = "we will we will rock you", first = "we", second = "will" **Output:** \["we","rock"\] **Constraints:** * `1 <= text.length <= 1000` * `text` consists of lowercase English letters and spaces. * All the words in `text` a separated by **a single space**. * `1 <= first.length, second.length <= 10` * `first` and `second` consist of lowercase English letters.
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
Short regex solution
occurrences-after-bigram
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findOcurrences(self, text: str, first: str, second: str) -> List[str]:\n\n ptr = re.compile(rf\'(?<=\\b{first} {second} )\\w+\')\n\n return ptr.findall(text)\n \n```
0
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`. Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`. **Example 1:** **Input:** text = "alice is a good girl she is a good student", first = "a", second = "good" **Output:** \["girl","student"\] **Example 2:** **Input:** text = "we will we will rock you", first = "we", second = "will" **Output:** \["we","rock"\] **Constraints:** * `1 <= text.length <= 1000` * `text` consists of lowercase English letters and spaces. * All the words in `text` a separated by **a single space**. * `1 <= first.length, second.length <= 10` * `first` and `second` consist of lowercase English letters.
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
Python easy solution
occurrences-after-bigram
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUse for loop upto len(a)-2. Then condition check. If condition match just append a[i+2] in result array.\n\n# Complexity\n- Time complexity:\n$O(n)\n\n- Space complexity:\n$O(n)\n\n# Code\n```\nclass Solution:\n def findOcurrences(self, text: str, first: str, second: str) -> List[str]:\n a = list(text.split())\n res = []\n for i in range(len(a)-2):\n if a[i] == first and a[i+1] == second:\n res.append(a[i+2])\n return res\n```
0
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`. Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`. **Example 1:** **Input:** text = "alice is a good girl she is a good student", first = "a", second = "good" **Output:** \["girl","student"\] **Example 2:** **Input:** text = "we will we will rock you", first = "we", second = "will" **Output:** \["we","rock"\] **Constraints:** * `1 <= text.length <= 1000` * `text` consists of lowercase English letters and spaces. * All the words in `text` a separated by **a single space**. * `1 <= first.length, second.length <= 10` * `first` and `second` consist of lowercase English letters.
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
Python3 simple solution, with Full Explaination.
occurrences-after-bigram
0
1
# Intuition\nThe goal is to find the third word in the text that follows the given pair of words (first and second).\n\n# Approach\n---\n1. Initialize an empty list \'thirds\' to store the third words.\n---\n2. Split the input \'text\' into words.\n---\n3. iterate Through the list of words. For each word:\n **.** check if we are not at the last two words.\n **.** if the current word is equal to the \'first\' and the following word is equal to \'second\', we store the following in thirds.\n---\n4. Return the \'thirds\' list containing the third words.\n---\n# Complexity\n- Time complexity:\n O(n)\n\n- Space complexity:\n O(n)\n\n# Code\n```\nclass Solution:\n def findOcurrences(self, text: str, first: str, second: str) -> List[str]:\n thirds = []\n words = text.split()\n for index,word in enumerate(words):\n if index < len(words)-2:\n if word == first and words[index+1] == second:\n thirds.append(words[index+2])\n return thirds\n\n```
0
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`. Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`. **Example 1:** **Input:** text = "alice is a good girl she is a good student", first = "a", second = "good" **Output:** \["girl","student"\] **Example 2:** **Input:** text = "we will we will rock you", first = "we", second = "will" **Output:** \["we","rock"\] **Constraints:** * `1 <= text.length <= 1000` * `text` consists of lowercase English letters and spaces. * All the words in `text` a separated by **a single space**. * `1 <= first.length, second.length <= 10` * `first` and `second` consist of lowercase English letters.
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
EASY SOLUTION USING PERMUTATION !!
letter-tile-possibilities
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nNot sure about the space complexity ,I think it should be O(N^2)\n# Code\n```\nfrom itertools import permutations \nclass Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n a=[]\n for i in range(len(tiles)):\n a.append(list(permutations(tiles,i+1)))\n s=[]\n for i in a:\n if i not in s:\n s.append(set(i))\n c=0\n for i in s:\n c+=len(i)\n return c\n```
2
You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles = "AAB " **Output:** 8 **Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ". **Example 2:** **Input:** tiles = "AAABBC " **Output:** 188 **Example 3:** **Input:** tiles = "V " **Output:** 1 **Constraints:** * `1 <= tiles.length <= 7` * `tiles` consists of uppercase English letters.
Find each path, then transform that path to an integer in base 10.
SIMPLE || 4 LINES|| BEGINNER FRIENDLY SOLUTION
letter-tile-possibilities
0
1
```\nclass Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n n= len(tiles)\n tiles=list(tiles)\n s1=set()\n for i in range(1,n+1):\n s1.update(permutations(tiles,i))\n return len(s1)
3
You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles = "AAB " **Output:** 8 **Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ". **Example 2:** **Input:** tiles = "AAABBC " **Output:** 188 **Example 3:** **Input:** tiles = "V " **Output:** 1 **Constraints:** * `1 <= tiles.length <= 7` * `tiles` consists of uppercase English letters.
Find each path, then transform that path to an integer in base 10.
Python 3 Backtracking (no set, no itertools, simple DFS count) with explanation
letter-tile-possibilities
0
1
### Intro\nI see lots of solution are actually generating the strings, but the question is only asking for the total count. Why doing so? \n\n### Intuition\n- First, we count the letter frequency, since same char at same position should only count as 1 same string\n- Second, use backtracking to count permutation in each `record` situation. Remember to revert it back, before goes to next letter\n\n\n### Implementation\n```\nclass Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n record = [0] * 26\n for tile in tiles: record[ord(tile)-ord(\'A\')] += 1\n def dfs(record):\n s = 0\n for i in range(26):\n if not record[i]: continue\n record[i] -= 1\n s += dfs(record) + 1 \n record[i] += 1\n return s \n return dfs(record)\n```
28
You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles = "AAB " **Output:** 8 **Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ". **Example 2:** **Input:** tiles = "AAABBC " **Output:** 188 **Example 3:** **Input:** tiles = "V " **Output:** 1 **Constraints:** * `1 <= tiles.length <= 7` * `tiles` consists of uppercase English letters.
Find each path, then transform that path to an integer in base 10.
Backtracking using frequencies python3 Solution || Beats 70% 🔥
letter-tile-possibilities
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to count all the possible unique permutations of the given string. We can see in the example that there can be multiple occurrences of the same character so, we make a frquency map of characters that stores the number of occurrences of each character in a string. We then form each permutation using a recursive function search and perform backtracking.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is simple frequency based backtracking. Each time that we pick a character to be the part of a valid permutation, we decrease that character\'s frequency by one and continue thw recursive calls and on returning each time, we again increase the frequency (i.e, not picking that character for the permutation)\n\n\n# Code\n```\nclass Solution:\n count = 0\n def numTilePossibilities(self, tiles: str) -> int:\n freqmap = defaultdict(int)\n for c in tiles: freqmap[c]+=1\n Solution.count = 0\n self.search(freqmap)\n return Solution.count - 1\n\n def search(self, freqmap):\n Solution.count += 1\n for k in freqmap:\n if freqmap[k] > 0:\n freqmap[k] -= 1\n self.search(freqmap)\n freqmap[k] += 1\n```
4
You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles = "AAB " **Output:** 8 **Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ". **Example 2:** **Input:** tiles = "AAABBC " **Output:** 188 **Example 3:** **Input:** tiles = "V " **Output:** 1 **Constraints:** * `1 <= tiles.length <= 7` * `tiles` consists of uppercase English letters.
Find each path, then transform that path to an integer in base 10.
itertools.permutations() beats 92% python
letter-tile-possibilities
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n ans = 0\n for i in range(1,len(tiles)+1):\n ans+=len((set(itertools.permutations(tiles,i))))\n\n return ans\n```
4
You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles = "AAB " **Output:** 8 **Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ". **Example 2:** **Input:** tiles = "AAABBC " **Output:** 188 **Example 3:** **Input:** tiles = "V " **Output:** 1 **Constraints:** * `1 <= tiles.length <= 7` * `tiles` consists of uppercase English letters.
Find each path, then transform that path to an integer in base 10.
75 % TC and 90% SC easy python solution
letter-tile-possibilities
0
1
```\ndef numTilePossibilities(self, tiles: str) -> int:\n\td = Counter(tiles)\n\tlru_cache(None)\n\tdef solve(d):\n\t\ttemp = 0\n\t\tfor c in d:\n\t\t\tif(d[c] > 0):\n\t\t\t\td[c] -= 1\n\t\t\t\ttemp += 1\n\t\t\t\ttemp += solve(d)\n\t\t\t\td[c] += 1\n\t\treturn temp\n\treturn solve(d)\n```
1
You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles = "AAB " **Output:** 8 **Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ". **Example 2:** **Input:** tiles = "AAABBC " **Output:** 188 **Example 3:** **Input:** tiles = "V " **Output:** 1 **Constraints:** * `1 <= tiles.length <= 7` * `tiles` consists of uppercase English letters.
Find each path, then transform that path to an integer in base 10.
Python DFS Postorder, beats 99%
insufficient-nodes-in-root-to-leaf-paths
0
1
**Idea:** Use DFS to compute the path_sum from the root to each leaf node. Once we reach a leaf node, we check if the path_sum is strictly less than the limit. If so, we pass-up the result False to the upper node indicating that this node has to be removed since it\'s insufficient (path_sum including this node is strictly less than the limit). Otherwise, we pass-up True.\n\nOnce the node has received results from both of its children, we can see if this node is included in the path that has sum strictly less than the limit or not.\n\nIf any of the children has returned True, it means that it was involved in a path that has sum NOT strictly less than the limit\nIf both of them are False, it means that all path_sum obtainable with this node involved are strictly less than the limit\nIf a child of the node has returned False, it means it can be removed. So, we just set it as False.\n\n# Code\n```\nclass Solution:\n def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:\n def dfs(node, path_sum):\n if not node:\n return False\n path_sum += node.val\n if not node.left and not node.right:\n return path_sum >= limit\n left = dfs(node.left, path_sum)\n right = dfs(node.right, path_sum)\n if not left:\n node.left = None\n if not right:\n node.right = None\n return left or right\n result = dfs(root, 0)\n return root if result else None\n```
2
Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_. A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1 **Output:** \[1,2,3,4,null,null,7,8,9,null,14\] **Example 2:** **Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22 **Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\] **Example 3:** **Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1 **Output:** \[1,null,-3,4\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `-105 <= Node.val <= 105` * `-109 <= limit <= 109`
Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2) The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively.
⬆️🔥✅ 100 % | 0MS | EASY | RECURSION | proof
insufficient-nodes-in-root-to-leaf-paths
1
1
# UPVOTE PLS\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n![image.png](https://assets.leetcode.com/users/images/05450dbf-5ddf-4f50-b836-bc3bdd4f53e9_1672730492.6868703.png)\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode sufficientSubset(TreeNode root, int limit) {\n if(root==null) return null;\n if(root.left==null && root.right==null) return root.val<limit? null: root;\n root.left = sufficientSubset(root.left,limit-root.val);\n root.right = sufficientSubset(root.right,limit-root.val);\n return root.left==root.right? null: root;\n }\n}\n```
2
Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_. A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1 **Output:** \[1,2,3,4,null,null,7,8,9,null,14\] **Example 2:** **Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22 **Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\] **Example 3:** **Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1 **Output:** \[1,null,-3,4\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `-105 <= Node.val <= 105` * `-109 <= limit <= 109`
Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2) The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively.
Easy-understanding and efficient solution
insufficient-nodes-in-root-to-leaf-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind all pths that >= limit and store these treenodes, delete other treenodes.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe same as intuition.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:\n left_nodes = set()\n \n def dfs(root, path, curr_sum):\n if not root.left and not root.right and curr_sum >= limit:\n for node in path:\n left_nodes.add(node)\n if root.left:\n new_path = path + [root.left]\n new_path.append(root.left)\n dfs(root.left, new_path, root.left.val + curr_sum)\n if root.right:\n new_path = path + [root.right]\n new_path.append(root.right)\n dfs(root.right, new_path, root.right.val + curr_sum)\n \n dfs(root, [root], root.val)\n\n if not left_nodes:\n return None\n \n def delete(root):\n if root.left and root.left not in left_nodes:\n root.left = None\n elif root.left:\n delete(root.left)\n if root.right and root.right not in left_nodes:\n root.right = None\n elif root.right:\n delete(root.right)\n \n delete(root)\n return root\n \n \n \n```
0
Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_. A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1 **Output:** \[1,2,3,4,null,null,7,8,9,null,14\] **Example 2:** **Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22 **Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\] **Example 3:** **Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1 **Output:** \[1,null,-3,4\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `-105 <= Node.val <= 105` * `-109 <= limit <= 109`
Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2) The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively.
Python Easy Solution
insufficient-nodes-in-root-to-leaf-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimilar to root to leaf sum path but with restructuring of tree.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSimilar to root to leaf path sum compute sum of each path.\nCalculate sum of left and right subtrees. If max of both is less than given limit then that node is not useful. So remove it from tree.\nEdge case: There are testcases where even we need to remove the root node. So check that condition in main block.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:\n import math\n def dfs(root,psum):\n if root.left==None and root.right==None:\n return (psum+root.val,root)\n\n elif root.left!=None and root.right!=None:\n left,leftnode=dfs(root.left,psum+root.val)\n right,rightnode=dfs(root.right,psum+root.val)\n\n elif root.left!=None and root.right==None:\n left,leftnode=dfs(root.left,psum+root.val)\n right,rightnode=(-math.inf,None)\n\n elif root.right!=None and root.left==None:\n right,rightnode=dfs(root.right,psum+root.val)\n left,leftnode=(-math.inf,None)\n\n \n #print(left,right)\n if left<limit:\n root.left=None\n else:\n root.left=leftnode\n if right<limit:\n root.right=None\n else:\n root.right=rightnode\n return (max(left,right),root)\n \n val,root=dfs(root,0)\n if val<limit:\n return None\n return root\n```
0
Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_. A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1 **Output:** \[1,2,3,4,null,null,7,8,9,null,14\] **Example 2:** **Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22 **Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\] **Example 3:** **Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1 **Output:** \[1,null,-3,4\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `-105 <= Node.val <= 105` * `-109 <= limit <= 109`
Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2) The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively.
Python recursion solution beats 70.87%
insufficient-nodes-in-root-to-leaf-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:\n def cut(n:int,node: Optional[TreeNode])->bool:\n n=n+node.val\n if not node.left and not node.right:\n return n<limit\n else:\n res=True\n if node.left:\n if cut(n,node.left):\n node.left=None\n else:\n res=False\n if node.right:\n if cut(n,node.right):\n node.right=None\n else:\n res=False\n return res\n return None if cut(0,root) else root\n```
0
Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_. A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1 **Output:** \[1,2,3,4,null,null,7,8,9,null,14\] **Example 2:** **Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22 **Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\] **Example 3:** **Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1 **Output:** \[1,null,-3,4\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `-105 <= Node.val <= 105` * `-109 <= limit <= 109`
Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2) The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively.
Simple DFS solution
insufficient-nodes-in-root-to-leaf-paths
0
1
```\nclass Solution:\n def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:\n dummy = TreeNode(left= root)\n self.sufficientSubset_dfs(dummy, 0, limit)\n return dummy.left\n\n def sufficientSubset_dfs(self, root, sum_val, limit):\n if not root:\n return True\n sum_val += root.val\n if not root.left and not root.right:\n return sum_val < limit\n less_limit_left = self.sufficientSubset_dfs(root.left, sum_val, limit)\n less_limit_right = self.sufficientSubset_dfs(root.right, sum_val, limit)\n if less_limit_left:\n root.left = None\n if less_limit_right:\n root.right = None\n return less_limit_left and less_limit_right\n```
0
Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_. A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1 **Output:** \[1,2,3,4,null,null,7,8,9,null,14\] **Example 2:** **Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22 **Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\] **Example 3:** **Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1 **Output:** \[1,null,-3,4\] **Constraints:** * The number of nodes in the tree is in the range `[1, 5000]`. * `-105 <= Node.val <= 105` * `-109 <= limit <= 109`
Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2) The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively.
Python stack
smallest-subsequence-of-distinct-characters
0
1
```\n# C \u2B55 D E \u262F\nclass Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n d = Counter(s)\n visited = set()\n stack = []\n for i in range(len(s)):\n d[s[i]] -= 1\n if s[i] not in visited:\n while stack and stack[-1] > s[i] and d[stack[-1]]:\n # stack.pop()\n visited.remove(stack[-1])\n stack.pop()\n visited.add(s[i])\n stack.append(s[i])\n \n return "".join(stack)\n \n \n```
10
Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of lowercase English letters. **Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/)
What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section.
PYTHON SOL | EXPLAINED | VERY EASY | FAST | SIMPLE | BINARY SEARCH + ITERATION |
smallest-subsequence-of-distinct-characters
0
1
\n# EXPLAINED\n```\nThe idea is we try to find the best character for each index\n\nFirst we get a list of unique characters in sorted order : unique\nAlso we make a dictionary having\n key : characters\n\tvalue : list [ indexes of the occurence of character]\n\nThe current left boundary left = 0\n( means we can take any character which occur at or after 0 )\n\nNow we iterate for size of list:unique \n We iterate unique which is in sorted order so we make smallest lexicographical subseq\n\t If any character is already used we neglect\n\t Else\n\t Check if the character have any occurence after the current left boundary left\n\t\tIf yes find the nearst index say new_left\n\t\tNow we again iterate unique:\n\t\t Neglect the used and curent character itself\n\t\t\t If the rest of character have any occurence after new_left we say we can fill the\n\t\t\t place with current character\n```\n\n\n# CODE\n```\nclass Solution:\n def smallestSubsequence(self, s: str) -> str:\n d = defaultdict(list)\n for index,character in enumerate(s):\n d[character].append(index)\n unique = sorted([ x for x in d])\n \n # what should be the character at index = 1\n size = len(unique)\n ans = ""\n used = {}\n left = 0\n for i in range(size):\n for character in unique:\n if character in used:continue\n if d[character][-1] < left: continue\n # find the new left\n idx = bisect.bisect_left(d[character],left)\n new_left = d[character][idx]\n # check if current character can be used\n flag = True\n for character2 in unique:\n if character2 in used or character2 == character: continue\n if d[character2][-1] < new_left:\n flag = False\n break\n if flag == True:\n left = new_left\n ans += character\n used[character] = True\n break\n return ans\n```
1
Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of lowercase English letters. **Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/)
What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section.
Python: Easy! Simple Solution using Stack || Time O(n)
smallest-subsequence-of-distinct-characters
0
1
```\nclass Solution:\n def smallestSubsequence(self, text: str) -> str:\n countMap = collections.defaultdict(int)\n stack = []\n selected = set()\n\n for c in text:\n countMap[c] += 1\n\n for c in text:\n countMap[c] -= 1\n if c not in selected:\n while stack and countMap[stack[-1]] > 0 and stack[-1] > c:\n selected.remove(stack.pop())\n \n stack.append(c)\n selected.add(c)\n \n return "".join(stack)\n```
6
Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of lowercase English letters. **Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/)
What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section.
Twin Zeroes ( 0---0 )......
duplicate-zeros
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code doubles every 0 in the array. When it encounters a 0, it adds another 0 right after it and removes the last element in the array. It then skips the next element by incrementing i by 2. If the current element is not 0, it just moves to the next element.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- **Loop:**\n\nThe code initializes a variable i to 0 and enters into a while loop that iterates until i is less than the length of the array minus 1.\n\nInside the loop, there is an if condition checking if the element at the current index i in the array is equal to 0.\n\n- **Insertion and Deletion:**\nIf the element at the current index i is 0, it inserts another 0 immediately after it, then removes the last element of the array. After these operations, it increments i by 2.\n\n - arr.insert(i + 1, 0): Inserts 0 at the position next to the current index i.\n - arr.pop(): Removes the last element of the array.\n - i += 2: Increments i by 2 to skip the recently added 0 and move to the next element.\n\n- **Else:**\nIf the element at the current index i is not 0, it simply increments i by 1, moving to the next element.\n# Complexity\n- Time complexity:Let\'s analyze the time complexity of the given code:\n\nIn each iteration of the while loop, either `i` is incremented by 1 or by 2. This depends on whether `arr[i]` is equal to 0 or not. If `arr[i]` is 0, then an element is inserted, and the loop increments `i` by 2; otherwise, `i` is incremented by 1.\n\nLet `n` be the length of the input array `arr`. In the worst case, the loop will run approximately `n/2` times because, in each iteration, either `i` is incremented by 1 or by 2. Therefore, the time complexity of the while loop is O(n).\n\nThe operations inside the loop include inserting an element and popping an element from the list. Both of these operations take O(n) time in the worst case because elements may need to be shifted. Therefore, the overall time complexity of the given code is O(n^2) in the worst case.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:The input list arr is the main data structure used in the code.\n\nThe loop variable i is an integer, and it doesn\'t depend on the size of the input.\n\nThe other variables used are constants (e.g., the integer 0).\n\nThe primary factor contributing to space complexity in this code is the input list arr. The space complexity is O(n), where n is the length of the input list. This is because, in the worst case, the size of the input list can grow by a factor of 1 for each zero encountered in the original list due to the insert operation inside the loop.\n\nThe space complexity does not depend on the size of the array or the number of elements in the array but rather on the number of zeros present in the array. If there are no zeros in the array, the space complexity is O(1).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n # Initialize a counter variable i to 0\n i = 0\n\n # Iterate through the elements of the array\n while i < len(arr) - 1:\n if arr[i] == 0: # Check if the current element is 0\n> # If the current element is 0, insert another 0 after it\n arr.insert(i + 1, 0)\n \n # Remove the last element in the list\n arr.pop()\n \n # Move the counter by 2 to skip the next element (the one we just inserted)\n i += 2\n else:\n # If the current element is not 0, move the counter by 1\n i += 1\n\n# The modified list is now stored in the \'arr\' variable\n```\n# > Do upvote if you like the explanation, tell me in comment section if there is any better way.
4
Given a fixed-length integer array `arr`, duplicate each occurrence of zero, shifting the remaining elements to the right. **Note** that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. **Example 1:** **Input:** arr = \[1,0,2,3,0,4,5,0\] **Output:** \[1,0,0,2,3,0,0,4\] **Explanation:** After calling your function, the input array is modified to: \[1,0,0,2,3,0,0,4\] **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[1,2,3\] **Explanation:** After calling your function, the input array is modified to: \[1,2,3\] **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 9`
How to erase vowels in a string? Loop over the string and check every character, if it is a vowel ignore it otherwise add it to the answer.
Twin Zeroes ( 0---0 )......
duplicate-zeros
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code doubles every 0 in the array. When it encounters a 0, it adds another 0 right after it and removes the last element in the array. It then skips the next element by incrementing i by 2. If the current element is not 0, it just moves to the next element.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- **Loop:**\n\nThe code initializes a variable i to 0 and enters into a while loop that iterates until i is less than the length of the array minus 1.\n\nInside the loop, there is an if condition checking if the element at the current index i in the array is equal to 0.\n\n- **Insertion and Deletion:**\nIf the element at the current index i is 0, it inserts another 0 immediately after it, then removes the last element of the array. After these operations, it increments i by 2.\n\n - arr.insert(i + 1, 0): Inserts 0 at the position next to the current index i.\n - arr.pop(): Removes the last element of the array.\n - i += 2: Increments i by 2 to skip the recently added 0 and move to the next element.\n\n- **Else:**\nIf the element at the current index i is not 0, it simply increments i by 1, moving to the next element.\n# Complexity\n- Time complexity:Let\'s analyze the time complexity of the given code:\n\nIn each iteration of the while loop, either `i` is incremented by 1 or by 2. This depends on whether `arr[i]` is equal to 0 or not. If `arr[i]` is 0, then an element is inserted, and the loop increments `i` by 2; otherwise, `i` is incremented by 1.\n\nLet `n` be the length of the input array `arr`. In the worst case, the loop will run approximately `n/2` times because, in each iteration, either `i` is incremented by 1 or by 2. Therefore, the time complexity of the while loop is O(n).\n\nThe operations inside the loop include inserting an element and popping an element from the list. Both of these operations take O(n) time in the worst case because elements may need to be shifted. Therefore, the overall time complexity of the given code is O(n^2) in the worst case.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:The input list arr is the main data structure used in the code.\n\nThe loop variable i is an integer, and it doesn\'t depend on the size of the input.\n\nThe other variables used are constants (e.g., the integer 0).\n\nThe primary factor contributing to space complexity in this code is the input list arr. The space complexity is O(n), where n is the length of the input list. This is because, in the worst case, the size of the input list can grow by a factor of 1 for each zero encountered in the original list due to the insert operation inside the loop.\n\nThe space complexity does not depend on the size of the array or the number of elements in the array but rather on the number of zeros present in the array. If there are no zeros in the array, the space complexity is O(1).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n # Initialize a counter variable i to 0\n i = 0\n\n # Iterate through the elements of the array\n while i < len(arr) - 1:\n if arr[i] == 0: # Check if the current element is 0\n> # If the current element is 0, insert another 0 after it\n arr.insert(i + 1, 0)\n \n # Remove the last element in the list\n arr.pop()\n \n # Move the counter by 2 to skip the next element (the one we just inserted)\n i += 2\n else:\n # If the current element is not 0, move the counter by 1\n i += 1\n\n# The modified list is now stored in the \'arr\' variable\n```\n# > Do upvote if you like the explanation, tell me in comment section if there is any better way.
4
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Python | Brute force
duplicate-zeros
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMust modify in-place so two-pointers initially came to mind. After thinking for a while, couldn\'t decipher how it would be possible to use pointers to solve the problem.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nBrute force loop through the array, if find a zero -> starting from the last element and decrementing, assign i = i-1 until we get to the index after the found 0. Stop looping and assign the index after the found 0 to 0 also.\n\nRe-begin looping through array from the index after the inserted additional 0 until either j or i reaches the final element.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWe loop through the array for as many times as we encounter a 0.\n\nO(n*number of zeros)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nNo additional data structures are used as we are modifying in-place.\nO(1)\n\n# Code\n```\n\nclass Solution:\n def duplicateZeros(self, arr: list[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n\n def shift(arr, idx):\n n = len(arr) - 1\n\n for i in range(n, idx+1, -1):\n arr[i] = arr[i-1]\n arr[idx+1] = 0\n\n j = 0\n flag = True\n while j < len(arr) - 1 and flag:\n flag = False\n for i in range(j, len(arr)):\n if i == len(arr) - 1:\n break\n if arr[i] == 0:\n flag = True\n shift(arr, i)\n j = i + 2\n break\n\n```
1
Given a fixed-length integer array `arr`, duplicate each occurrence of zero, shifting the remaining elements to the right. **Note** that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. **Example 1:** **Input:** arr = \[1,0,2,3,0,4,5,0\] **Output:** \[1,0,0,2,3,0,0,4\] **Explanation:** After calling your function, the input array is modified to: \[1,0,0,2,3,0,0,4\] **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[1,2,3\] **Explanation:** After calling your function, the input array is modified to: \[1,2,3\] **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 9`
How to erase vowels in a string? Loop over the string and check every character, if it is a vowel ignore it otherwise add it to the answer.
Python | Brute force
duplicate-zeros
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMust modify in-place so two-pointers initially came to mind. After thinking for a while, couldn\'t decipher how it would be possible to use pointers to solve the problem.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nBrute force loop through the array, if find a zero -> starting from the last element and decrementing, assign i = i-1 until we get to the index after the found 0. Stop looping and assign the index after the found 0 to 0 also.\n\nRe-begin looping through array from the index after the inserted additional 0 until either j or i reaches the final element.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWe loop through the array for as many times as we encounter a 0.\n\nO(n*number of zeros)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nNo additional data structures are used as we are modifying in-place.\nO(1)\n\n# Code\n```\n\nclass Solution:\n def duplicateZeros(self, arr: list[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n\n def shift(arr, idx):\n n = len(arr) - 1\n\n for i in range(n, idx+1, -1):\n arr[i] = arr[i-1]\n arr[idx+1] = 0\n\n j = 0\n flag = True\n while j < len(arr) - 1 and flag:\n flag = False\n for i in range(j, len(arr)):\n if i == len(arr) - 1:\n break\n if arr[i] == 0:\n flag = True\n shift(arr, i)\n j = i + 2\n break\n\n```
1
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Python 3 real in-place solution
duplicate-zeros
0
1
Start from the back and adjust items to correct locations. If item is zero then duplicate it.\n\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n zeroes = arr.count(0)\n n = len(arr)\n for i in range(n-1, -1, -1):\n if i + zeroes < n:\n arr[i + zeroes] = arr[i]\n if arr[i] == 0: \n zeroes -= 1\n if i + zeroes < n:\n arr[i + zeroes] = 0\n```
337
Given a fixed-length integer array `arr`, duplicate each occurrence of zero, shifting the remaining elements to the right. **Note** that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. **Example 1:** **Input:** arr = \[1,0,2,3,0,4,5,0\] **Output:** \[1,0,0,2,3,0,0,4\] **Explanation:** After calling your function, the input array is modified to: \[1,0,0,2,3,0,0,4\] **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[1,2,3\] **Explanation:** After calling your function, the input array is modified to: \[1,2,3\] **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 9`
How to erase vowels in a string? Loop over the string and check every character, if it is a vowel ignore it otherwise add it to the answer.
Python 3 real in-place solution
duplicate-zeros
0
1
Start from the back and adjust items to correct locations. If item is zero then duplicate it.\n\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n zeroes = arr.count(0)\n n = len(arr)\n for i in range(n-1, -1, -1):\n if i + zeroes < n:\n arr[i + zeroes] = arr[i]\n if arr[i] == 0: \n zeroes -= 1\n if i + zeroes < n:\n arr[i + zeroes] = 0\n```
337
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Easy | Python Solution | While
duplicate-zeros
0
1
# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n l = len(arr)\n i = 0\n while i < l:\n if arr[i] == 0:\n arr.insert(i+1, 0)\n arr.pop()\n i += 1\n i += 1 \n```\nDo upvote if you like the solution :)
11
Given a fixed-length integer array `arr`, duplicate each occurrence of zero, shifting the remaining elements to the right. **Note** that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. **Example 1:** **Input:** arr = \[1,0,2,3,0,4,5,0\] **Output:** \[1,0,0,2,3,0,0,4\] **Explanation:** After calling your function, the input array is modified to: \[1,0,0,2,3,0,0,4\] **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[1,2,3\] **Explanation:** After calling your function, the input array is modified to: \[1,2,3\] **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 9`
How to erase vowels in a string? Loop over the string and check every character, if it is a vowel ignore it otherwise add it to the answer.
Easy | Python Solution | While
duplicate-zeros
0
1
# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n l = len(arr)\n i = 0\n while i < l:\n if arr[i] == 0:\n arr.insert(i+1, 0)\n arr.pop()\n i += 1\n i += 1 \n```\nDo upvote if you like the solution :)
11
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Easy python solution. Beats 91%
duplicate-zeros
0
1
# Intuition\nEasy solution \n\n# Approach\nusing insert in python\n\n# Complexity\n- Time complexity:\n O(m) where m = length of final array\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n n = len(arr)\n a= []\n for i in range(len(arr)):\n if arr[i]==0:\n a.append(i)\n k =0\n for i in range(len(a)):\n arr.insert(a[i]+k,0)\n k+=1\n m = len(arr)\n for i in range(m-n):\n arr.pop()\n return arr\n \n```
2
Given a fixed-length integer array `arr`, duplicate each occurrence of zero, shifting the remaining elements to the right. **Note** that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. **Example 1:** **Input:** arr = \[1,0,2,3,0,4,5,0\] **Output:** \[1,0,0,2,3,0,0,4\] **Explanation:** After calling your function, the input array is modified to: \[1,0,0,2,3,0,0,4\] **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[1,2,3\] **Explanation:** After calling your function, the input array is modified to: \[1,2,3\] **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 9`
How to erase vowels in a string? Loop over the string and check every character, if it is a vowel ignore it otherwise add it to the answer.
Easy python solution. Beats 91%
duplicate-zeros
0
1
# Intuition\nEasy solution \n\n# Approach\nusing insert in python\n\n# Complexity\n- Time complexity:\n O(m) where m = length of final array\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n n = len(arr)\n a= []\n for i in range(len(arr)):\n if arr[i]==0:\n a.append(i)\n k =0\n for i in range(len(a)):\n arr.insert(a[i]+k,0)\n k+=1\n m = len(arr)\n for i in range(m-n):\n arr.pop()\n return arr\n \n```
2
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Python Easy solution with comment
duplicate-zeros
0
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n```\narr = [1,0,2,3,0,4,5,0]\n ^\n (i=1) & i+2\n (insert)\n \narr = [1,0,0,2,3,0,4,5,0]\n ^ ^ \n (i=3) (pop) \n\narr = [1,0,0,2,3,0,4,5]\n\n```\n\n\n# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n \n <!-- use while loop to contorl "i" -->\n i=0\n while(i<len(arr)):\n if(arr[i]==0):\n arr.insert(i,0)\n\n <!-- i+2 for skip the insert index -->\n i=i+2\n arr.pop()\n else:\n i=i+1\n \n```
8
Given a fixed-length integer array `arr`, duplicate each occurrence of zero, shifting the remaining elements to the right. **Note** that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. **Example 1:** **Input:** arr = \[1,0,2,3,0,4,5,0\] **Output:** \[1,0,0,2,3,0,0,4\] **Explanation:** After calling your function, the input array is modified to: \[1,0,0,2,3,0,0,4\] **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[1,2,3\] **Explanation:** After calling your function, the input array is modified to: \[1,2,3\] **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 9`
How to erase vowels in a string? Loop over the string and check every character, if it is a vowel ignore it otherwise add it to the answer.
Python Easy solution with comment
duplicate-zeros
0
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n```\narr = [1,0,2,3,0,4,5,0]\n ^\n (i=1) & i+2\n (insert)\n \narr = [1,0,0,2,3,0,4,5,0]\n ^ ^ \n (i=3) (pop) \n\narr = [1,0,0,2,3,0,4,5]\n\n```\n\n\n# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n \n <!-- use while loop to contorl "i" -->\n i=0\n while(i<len(arr)):\n if(arr[i]==0):\n arr.insert(i,0)\n\n <!-- i+2 for skip the insert index -->\n i=i+2\n arr.pop()\n else:\n i=i+1\n \n```
8
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Simple Python solution -
duplicate-zeros
0
1
What the code does\n1. Iterates through the array.\n2. If the current element is 0, removes the last element from the array and Insert 0 at the current index.\n4. Increment the index by 2.\n5. If the current element is not 0, increment the index by 1\n\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n i = 0\n while i < len(arr):\n if arr[i] == 0: \n arr.pop()\n arr.insert(i, 0)\n i += 2\n else:\n i += 1\n```\n\nTime complexity is O(n) as it will iterate over the entire array and space complexity is O(1) as we are only inserting and deleting elements from the array.
6
Given a fixed-length integer array `arr`, duplicate each occurrence of zero, shifting the remaining elements to the right. **Note** that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. **Example 1:** **Input:** arr = \[1,0,2,3,0,4,5,0\] **Output:** \[1,0,0,2,3,0,0,4\] **Explanation:** After calling your function, the input array is modified to: \[1,0,0,2,3,0,0,4\] **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[1,2,3\] **Explanation:** After calling your function, the input array is modified to: \[1,2,3\] **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 9`
How to erase vowels in a string? Loop over the string and check every character, if it is a vowel ignore it otherwise add it to the answer.
Simple Python solution -
duplicate-zeros
0
1
What the code does\n1. Iterates through the array.\n2. If the current element is 0, removes the last element from the array and Insert 0 at the current index.\n4. Increment the index by 2.\n5. If the current element is not 0, increment the index by 1\n\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n i = 0\n while i < len(arr):\n if arr[i] == 0: \n arr.pop()\n arr.insert(i, 0)\n i += 2\n else:\n i += 1\n```\n\nTime complexity is O(n) as it will iterate over the entire array and space complexity is O(1) as we are only inserting and deleting elements from the array.
6
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Python one pass with O(n) space, easy understanding!
duplicate-zeros
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse a new pointer to record index with duplicated zero.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a pointer `j=0`. When we encounter a `0`, add j twice.\nOne thing to note is that in case of out of bound error, break is necessary in the for loop.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n j = 0\n for n in arr[:]:\n if n == 0:\n arr[j] = 0\n j += 1\n if j == len(arr):\n break\n arr[j] = 0\n else:\n arr[j] = n\n j += 1\n if j == len(arr):\n break\n \n \n \n```
3
Given a fixed-length integer array `arr`, duplicate each occurrence of zero, shifting the remaining elements to the right. **Note** that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. **Example 1:** **Input:** arr = \[1,0,2,3,0,4,5,0\] **Output:** \[1,0,0,2,3,0,0,4\] **Explanation:** After calling your function, the input array is modified to: \[1,0,0,2,3,0,0,4\] **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[1,2,3\] **Explanation:** After calling your function, the input array is modified to: \[1,2,3\] **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 9`
How to erase vowels in a string? Loop over the string and check every character, if it is a vowel ignore it otherwise add it to the answer.
Python one pass with O(n) space, easy understanding!
duplicate-zeros
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse a new pointer to record index with duplicated zero.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a pointer `j=0`. When we encounter a `0`, add j twice.\nOne thing to note is that in case of out of bound error, break is necessary in the for loop.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n """\n Do not return anything, modify arr in-place instead.\n """\n j = 0\n for n in arr[:]:\n if n == 0:\n arr[j] = 0\n j += 1\n if j == len(arr):\n break\n arr[j] = 0\n else:\n arr[j] = n\n j += 1\n if j == len(arr):\n break\n \n \n \n```
3
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Clean Python | 8 Lines | High Speed | O(n) time, O(1) space | Beats 98.9%
largest-values-from-labels
0
1
# Code\n```\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:\n ans = 0\n freq = {}\n for value, label in sorted(zip(values, labels), reverse=True):\n if freq.get(label, 0) < use_limit: \n ans += value\n num_wanted -= 1\n if not num_wanted: break \n freq[label] = 1 + freq.get(label, 0)\n return ans \n```
1
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
Clean Python | 8 Lines | High Speed | O(n) time, O(1) space | Beats 98.9%
largest-values-from-labels
0
1
# Code\n```\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:\n ans = 0\n freq = {}\n for value, label in sorted(zip(values, labels), reverse=True):\n if freq.get(label, 0) < use_limit: \n ans += value\n num_wanted -= 1\n if not num_wanted: break \n freq[label] = 1 + freq.get(label, 0)\n return ans \n```
1
A transaction is possibly invalid if: * the amount exceeds `$1000`, or; * if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. **Example 1:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. **Example 2:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\] **Output:** \[ "alice,50,1200,mtv "\] **Example 3:** **Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\] **Output:** \[ "bob,50,1200,mtv "\] **Constraints:** * `transactions.length <= 1000` * Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "` * Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. * Each `{time}` consist of digits, and represent an integer between `0` and `1000`. * Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
Python Elegant & Short | Greedy | Hash Table
largest-values-from-labels
0
1
# Complexity\n- Time complexity: $$O(n*\\log_2{n})$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:\n used_count = defaultdict(int)\n total_value = 0\n\n for val, label in sorted(zip(values, labels), reverse=True):\n if not num_wanted:\n break\n\n if used_count[label] >= use_limit:\n continue\n\n used_count[label] += 1\n num_wanted -= 1\n total_value += val\n\n return total_value\n```
2
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
Python Elegant & Short | Greedy | Hash Table
largest-values-from-labels
0
1
# Complexity\n- Time complexity: $$O(n*\\log_2{n})$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:\n used_count = defaultdict(int)\n total_value = 0\n\n for val, label in sorted(zip(values, labels), reverse=True):\n if not num_wanted:\n break\n\n if used_count[label] >= use_limit:\n continue\n\n used_count[label] += 1\n num_wanted -= 1\n total_value += val\n\n return total_value\n```
2
A transaction is possibly invalid if: * the amount exceeds `$1000`, or; * if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. **Example 1:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. **Example 2:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\] **Output:** \[ "alice,50,1200,mtv "\] **Example 3:** **Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\] **Output:** \[ "bob,50,1200,mtv "\] **Constraints:** * `transactions.length <= 1000` * Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "` * Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. * Each `{time}` consist of digits, and represent an integer between `0` and `1000`. * Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
71% TC and 68% SC easy python solution
largest-values-from-labels
0
1
```\ndef largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n\td = defaultdict(int)\n\tans = 0\n\tl = numWanted\n\tfor i, j in sorted(list(zip(values, labels)), reverse = True):\n\t\tif(d[j] < useLimit and l):\n\t\t\tl -= 1\n\t\t\td[j] += 1\n\t\t\tans += i\n\treturn ans\n```
1
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
71% TC and 68% SC easy python solution
largest-values-from-labels
0
1
```\ndef largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n\td = defaultdict(int)\n\tans = 0\n\tl = numWanted\n\tfor i, j in sorted(list(zip(values, labels)), reverse = True):\n\t\tif(d[j] < useLimit and l):\n\t\t\tl -= 1\n\t\t\td[j] += 1\n\t\t\tans += i\n\treturn ans\n```
1
A transaction is possibly invalid if: * the amount exceeds `$1000`, or; * if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. **Example 1:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. **Example 2:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\] **Output:** \[ "alice,50,1200,mtv "\] **Example 3:** **Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\] **Output:** \[ "bob,50,1200,mtv "\] **Constraints:** * `transactions.length <= 1000` * Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "` * Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. * Each `{time}` consist of digits, and represent an integer between `0` and `1000`. * Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
Simple and Readable Python code
largest-values-from-labels
0
1
\n\n# Code\n```\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n d = defaultdict(list)\n for i in range(len(values)):\n d[labels[i]].append(values[i])\n \n all_vals = [[k, x] for k, v in d.items() for x in v]\n all_vals = sorted(all_vals, key = lambda arr:arr[1], reverse = True)\n \n usage = [0] * (max(labels)+1) # 1 - indexing careful\n \n ans = 0\n\n for k, v in all_vals:\n if usage[k] < useLimit and numWanted: \n ans += v\n usage[k] += 1\n numWanted -= 1\n \n return ans\n \n \n```
0
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
Simple and Readable Python code
largest-values-from-labels
0
1
\n\n# Code\n```\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n d = defaultdict(list)\n for i in range(len(values)):\n d[labels[i]].append(values[i])\n \n all_vals = [[k, x] for k, v in d.items() for x in v]\n all_vals = sorted(all_vals, key = lambda arr:arr[1], reverse = True)\n \n usage = [0] * (max(labels)+1) # 1 - indexing careful\n \n ans = 0\n\n for k, v in all_vals:\n if usage[k] < useLimit and numWanted: \n ans += v\n usage[k] += 1\n numWanted -= 1\n \n return ans\n \n \n```
0
A transaction is possibly invalid if: * the amount exceeds `$1000`, or; * if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. **Example 1:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. **Example 2:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\] **Output:** \[ "alice,50,1200,mtv "\] **Example 3:** **Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\] **Output:** \[ "bob,50,1200,mtv "\] **Constraints:** * `transactions.length <= 1000` * Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "` * Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. * Each `{time}` consist of digits, and represent an integer between `0` and `1000`. * Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
beats 98% of python users in runtime and 97% in memory
largest-values-from-labels
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import defaultdict as dd\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n hsh_mp = dd(list)\n ans = []\n for idx,val in enumerate(labels):\n hsh_mp[val].append(values[idx])\n for keys,vals in hsh_mp.items():\n vals = sorted(vals,reverse=True)\n val = vals[:useLimit:]\n for v in val:\n ans.append(v)\n ans = sorted(ans,reverse=True)\n return sum(ans[:numWanted:])\n \n \n \n \n \n \n \n \n \n \n \n```
0
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
beats 98% of python users in runtime and 97% in memory
largest-values-from-labels
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import defaultdict as dd\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n hsh_mp = dd(list)\n ans = []\n for idx,val in enumerate(labels):\n hsh_mp[val].append(values[idx])\n for keys,vals in hsh_mp.items():\n vals = sorted(vals,reverse=True)\n val = vals[:useLimit:]\n for v in val:\n ans.append(v)\n ans = sorted(ans,reverse=True)\n return sum(ans[:numWanted:])\n \n \n \n \n \n \n \n \n \n \n \n```
0
A transaction is possibly invalid if: * the amount exceeds `$1000`, or; * if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. **Example 1:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. **Example 2:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\] **Output:** \[ "alice,50,1200,mtv "\] **Example 3:** **Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\] **Output:** \[ "bob,50,1200,mtv "\] **Constraints:** * `transactions.length <= 1000` * Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "` * Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. * Each `{time}` consist of digits, and represent an integer between `0` and `1000`. * Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
python heap+greedy
largest-values-from-labels
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n \n arr = [(-v, l) for v, l in zip(values, labels)]\n heapify(arr)\n C = Counter()\n res = 0\n \n while numWanted and arr:\n l = arr[0][1]\n if C[l] < useLimit: \n res += -heappop(arr)[0]\n C[l] += 1\n numWanted -= 1\n else: heappop(arr)\n return res\n```
0
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
python heap+greedy
largest-values-from-labels
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n \n arr = [(-v, l) for v, l in zip(values, labels)]\n heapify(arr)\n C = Counter()\n res = 0\n \n while numWanted and arr:\n l = arr[0][1]\n if C[l] < useLimit: \n res += -heappop(arr)[0]\n C[l] += 1\n numWanted -= 1\n else: heappop(arr)\n return res\n```
0
A transaction is possibly invalid if: * the amount exceeds `$1000`, or; * if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. **Example 1:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. **Example 2:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\] **Output:** \[ "alice,50,1200,mtv "\] **Example 3:** **Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\] **Output:** \[ "bob,50,1200,mtv "\] **Constraints:** * `transactions.length <= 1000` * Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "` * Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. * Each `{time}` consist of digits, and represent an integer between `0` and `1000`. * Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
✅CLEAN AND COINCISE SOLUTIONS WITH EXPLENATIONS. BEATS 100% OF RUNTIME✅
largest-values-from-labels
0
1
# We can solve this question using 2 approaches :\n- **Sorting** the values array zipped with the labels array, in reverse order\n- Using a **Priority Queue**\n\nIn this post i wil explain the **first** approach\n\n# Sorting Approach\nThe key to solve this problem is to take always the **biggest** elements of the array values, but we have a limitation on the count of each labels indicated from **useLimit**\n\n- Create a third array where each cell indicates the value and the labels of a certain element, and sort that in **decreasing** order\n- loop over the array and sum only the **biggest** elements, but take track of the **count** of every labels so we will not exceed the useLimit\n- Once we reach the **numWanted** we can break the loop\n\n# Complexity\n- Time complexity -> **O(nLog(n))**\n\n- Space complexity -> **O(n)**\n\n# Code\n```\nclass Solution(object):\n def largestValsFromLabels(self, values, labels, numWanted, useLimit):\n\n items = [(values[i], labels[i]) for i in range(len(values))]\n labels_count = defaultdict(int)\n items.sort(reverse=True)\n numCount = ans = 0\n\n for value, label in items:\n \n if labels_count.get(label, 0) < useLimit:\n labels_count[label] += 1\n numCount += 1\n ans += value\n\n if numCount == numWanted:\n break\n\n return ans\n```
0
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
✅CLEAN AND COINCISE SOLUTIONS WITH EXPLENATIONS. BEATS 100% OF RUNTIME✅
largest-values-from-labels
0
1
# We can solve this question using 2 approaches :\n- **Sorting** the values array zipped with the labels array, in reverse order\n- Using a **Priority Queue**\n\nIn this post i wil explain the **first** approach\n\n# Sorting Approach\nThe key to solve this problem is to take always the **biggest** elements of the array values, but we have a limitation on the count of each labels indicated from **useLimit**\n\n- Create a third array where each cell indicates the value and the labels of a certain element, and sort that in **decreasing** order\n- loop over the array and sum only the **biggest** elements, but take track of the **count** of every labels so we will not exceed the useLimit\n- Once we reach the **numWanted** we can break the loop\n\n# Complexity\n- Time complexity -> **O(nLog(n))**\n\n- Space complexity -> **O(n)**\n\n# Code\n```\nclass Solution(object):\n def largestValsFromLabels(self, values, labels, numWanted, useLimit):\n\n items = [(values[i], labels[i]) for i in range(len(values))]\n labels_count = defaultdict(int)\n items.sort(reverse=True)\n numCount = ans = 0\n\n for value, label in items:\n \n if labels_count.get(label, 0) < useLimit:\n labels_count[label] += 1\n numCount += 1\n ans += value\n\n if numCount == numWanted:\n break\n\n return ans\n```
0
A transaction is possibly invalid if: * the amount exceeds `$1000`, or; * if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. **Example 1:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. **Example 2:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\] **Output:** \[ "alice,50,1200,mtv "\] **Example 3:** **Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\] **Output:** \[ "bob,50,1200,mtv "\] **Constraints:** * `transactions.length <= 1000` * Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "` * Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. * Each `{time}` consist of digits, and represent an integer between `0` and `1000`. * Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
Python short and clean. BFS. Functional programming.
shortest-path-in-binary-matrix
0
1
# Complexity\n- Time complexity: $$O(n ^ 2)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\nwhere, `n * n is the dimensions of the grid.`\n\n# Code\n```python\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: list[list[int]]) -> int:\n n = len(grid)\n start, end = (0, 0), (n - 1, n - 1)\n\n # Helper functions\n in_bound = lambda cell: 0 <= cell[0] < n and 0 <= cell[1] < n\n grid_get = lambda cell: grid[cell[0]][cell[1]] if in_bound(cell) else 1\n all_nbrs = lambda cell: product(range(cell[0] - 1, cell[0] + 2), range(cell[1] - 1, cell[1] + 2))\n is_clear = lambda cell, skips: grid_get(cell) == 0 and cell not in skips\n\n if start == end: return -1 if grid_get(start) else 1\n queue = deque([] if grid_get(start) else [(start, 1)])\n seen = {start}\n valid_nbr = partial(is_clear, skips=seen)\n\n while queue:\n cell, length = queue.popleft()\n valid_nbrs = set(filter(valid_nbr, all_nbrs(cell)))\n\n if end in valid_nbrs: return length + 1\n queue.extend(zip(valid_nbrs, repeat(length + 1)))\n seen.update(valid_nbrs)\n \n return -1\n\n\n```
2
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
Python short and clean. BFS. Functional programming.
shortest-path-in-binary-matrix
0
1
# Complexity\n- Time complexity: $$O(n ^ 2)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\nwhere, `n * n is the dimensions of the grid.`\n\n# Code\n```python\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: list[list[int]]) -> int:\n n = len(grid)\n start, end = (0, 0), (n - 1, n - 1)\n\n # Helper functions\n in_bound = lambda cell: 0 <= cell[0] < n and 0 <= cell[1] < n\n grid_get = lambda cell: grid[cell[0]][cell[1]] if in_bound(cell) else 1\n all_nbrs = lambda cell: product(range(cell[0] - 1, cell[0] + 2), range(cell[1] - 1, cell[1] + 2))\n is_clear = lambda cell, skips: grid_get(cell) == 0 and cell not in skips\n\n if start == end: return -1 if grid_get(start) else 1\n queue = deque([] if grid_get(start) else [(start, 1)])\n seen = {start}\n valid_nbr = partial(is_clear, skips=seen)\n\n while queue:\n cell, length = queue.popleft()\n valid_nbrs = set(filter(valid_nbr, all_nbrs(cell)))\n\n if end in valid_nbrs: return length + 1\n queue.extend(zip(valid_nbrs, repeat(length + 1)))\n seen.update(valid_nbrs)\n \n return -1\n\n\n```
2
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Python — A* search using priority queue (faster than 99%)
shortest-path-in-binary-matrix
0
1
# Problem\nGiven a binary matrix representing an 8-connected grid, find the shortest path from the top-left cell to the bottom-right cell. The path can only traverse through cells containing $0$, and diagonal movement is allowed.\n\n# Intuition\nWe conceptualize the matrix as an implicit graph, where the neighboring indices are connected. Then we apply A* search using a simple heuristic:\n\n$$h(x,y) = \\max(n{-}x, n{-}y)$$\n\nThis is simply the shortest distance from $(x,y)$ to $(n{-}1,n{-}1)$ for any 8-connected grid.\n\nRemember:\n- $f(x,y) = g(x,y) + h(x,y)$ \u2014 Total cost from start to goal, for a path that goes through the current node.\n - Total cost = Cost from start to current node + Heuristic estimate to goal.\n\n \n\n- $g(x,y)$ \u2014 Cost from start to current node.\n- $h(x,y)$ \u2014 Heuristic estimate of cost from current node to goal.\n\n \n\n# Approach\nWe maintain two data structures:\n\n- `heap` \u2014 A priority queue (or min-heap) to store tuples in the form `(f(x, y), x, y)`, enabling us to retrieve the tuple with the smallest $f$ score using `heappop`.\n\n- `length` \u2014 A grid of size $n{\\times}n$ that stores the cost from the start cell to each cell, which represents the $g$ score. Initially, all cells are assigned a value of `sys.maxsize` to indicate they are unexplored.\n\n# Complexity\n- Time complexity: $$O(8^d)$$\n - The branching factor is 8 because every node has 8 neighbors.\n - The depth factor $d$ depends on the similarity of our heuristic $h(x,y)$ to the optimal heuristic $h^*(x,y)$;\n - Depending on which, the time complexity might be anywhere between constant to exponential.\n\n \n\n- Space complexity: $$O(n^2)$$\n\n - Like most graph search algorithms, we have to store state for every node (i.e. `length`).\n\n \n\n# Code\n```\nfrom sys import maxsize\nfrom heapq import heappush, heappop\n\n# A* search using priority queue\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n n = len(grid)\n heap = []\n length = [[maxsize for _ in range(n)] for _ in range(n)]\n offset = [(1,1),(1,0),(0,1),(-1,1),(1,-1),(-1,0),(0,-1),(-1,-1)]\n\n if grid[0][0] == 0 and grid[n-1][n-1] == 0:\n heap.append((n,0,0))\n length[0][0] = 1\n\n while heap:\n _, i, j = heappop(heap)\n L = length[i][j] + 1\n\n if (i,j) == (n-1,n-1):\n return L-1\n\n for di, dj in offset:\n x, y = i+di, j+dj\n if 0 <= x < n and 0 <= y n:\n if grid[x][y] == 0 and length[x][y] > L:\n length[x][y] = L\n heappush(heap, (L+max(n-x, n-y), x, y))\n \n return -1\n```\n\n# Explanation\nWe initialize the heap and length as follows:\n\n```python\nn = len(grid)\nheap = []\nlength = [[maxsize for _ in range(n)] for _ in range(n)]\n```\n\nWe consider diagonal and adjacent cells as neighbors in the 8-connected grid. Hence, we define the offset list as:\n\n```python\noffset = [\n (1, 1),\n (1, 0),\n (0, 1),\n (-1, 1),\n (1, -1),\n (-1, 0),\n (0, -1),\n (-1, -1)\n]\n```\n\nEach tuple in offset represents the offset needed to reach one of the eight neighbors.\n\nWe initiate the search by checking the accessibility of the top-left cell $(0, 0)$ and the goal node $(n{-}1, n{-}1)$. If both cells are reachable (i.e., contain $0$), we add the top-left cell to the heap and assign its length as $1$:\n\n```python\nif grid[0][0] == 0 and grid[n-1][n-1] == 0:\n heap.append((n, 0, 0))\n length[0][0] = 1\n```\n\nWhile there are cells in the heap, we extract the cell with the smallest $f$ score and explore its neighbors. For each neighbor cell $(x, y)$, if it is within the grid bounds and contains $0$, and if the new cost $L$ from start to the neighbor cell is smaller than the current cost, we update the cost and add the neighbor to the heap:\n\n```python\nwhile heap:\n _, i, j = heappop(heap)\n L = length[i][j] + 1\n\n if (i, j) == (n - 1, n - 1):\n return L - 1\n\n for di, dj in offset:\n x, y = i + di, j + dj\n if 0 <= x < n and 0 <= y < n:\n if grid[x][y] == 0 and length[x][y] > L:\n length[x][y] = L\n heappush(heap, (L + max(n - x, n - y), x, y))\n```\n\nIf the bottom-right cell cannot be reached, the function returns -1.
1
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
Python — A* search using priority queue (faster than 99%)
shortest-path-in-binary-matrix
0
1
# Problem\nGiven a binary matrix representing an 8-connected grid, find the shortest path from the top-left cell to the bottom-right cell. The path can only traverse through cells containing $0$, and diagonal movement is allowed.\n\n# Intuition\nWe conceptualize the matrix as an implicit graph, where the neighboring indices are connected. Then we apply A* search using a simple heuristic:\n\n$$h(x,y) = \\max(n{-}x, n{-}y)$$\n\nThis is simply the shortest distance from $(x,y)$ to $(n{-}1,n{-}1)$ for any 8-connected grid.\n\nRemember:\n- $f(x,y) = g(x,y) + h(x,y)$ \u2014 Total cost from start to goal, for a path that goes through the current node.\n - Total cost = Cost from start to current node + Heuristic estimate to goal.\n\n \n\n- $g(x,y)$ \u2014 Cost from start to current node.\n- $h(x,y)$ \u2014 Heuristic estimate of cost from current node to goal.\n\n \n\n# Approach\nWe maintain two data structures:\n\n- `heap` \u2014 A priority queue (or min-heap) to store tuples in the form `(f(x, y), x, y)`, enabling us to retrieve the tuple with the smallest $f$ score using `heappop`.\n\n- `length` \u2014 A grid of size $n{\\times}n$ that stores the cost from the start cell to each cell, which represents the $g$ score. Initially, all cells are assigned a value of `sys.maxsize` to indicate they are unexplored.\n\n# Complexity\n- Time complexity: $$O(8^d)$$\n - The branching factor is 8 because every node has 8 neighbors.\n - The depth factor $d$ depends on the similarity of our heuristic $h(x,y)$ to the optimal heuristic $h^*(x,y)$;\n - Depending on which, the time complexity might be anywhere between constant to exponential.\n\n \n\n- Space complexity: $$O(n^2)$$\n\n - Like most graph search algorithms, we have to store state for every node (i.e. `length`).\n\n \n\n# Code\n```\nfrom sys import maxsize\nfrom heapq import heappush, heappop\n\n# A* search using priority queue\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n n = len(grid)\n heap = []\n length = [[maxsize for _ in range(n)] for _ in range(n)]\n offset = [(1,1),(1,0),(0,1),(-1,1),(1,-1),(-1,0),(0,-1),(-1,-1)]\n\n if grid[0][0] == 0 and grid[n-1][n-1] == 0:\n heap.append((n,0,0))\n length[0][0] = 1\n\n while heap:\n _, i, j = heappop(heap)\n L = length[i][j] + 1\n\n if (i,j) == (n-1,n-1):\n return L-1\n\n for di, dj in offset:\n x, y = i+di, j+dj\n if 0 <= x < n and 0 <= y n:\n if grid[x][y] == 0 and length[x][y] > L:\n length[x][y] = L\n heappush(heap, (L+max(n-x, n-y), x, y))\n \n return -1\n```\n\n# Explanation\nWe initialize the heap and length as follows:\n\n```python\nn = len(grid)\nheap = []\nlength = [[maxsize for _ in range(n)] for _ in range(n)]\n```\n\nWe consider diagonal and adjacent cells as neighbors in the 8-connected grid. Hence, we define the offset list as:\n\n```python\noffset = [\n (1, 1),\n (1, 0),\n (0, 1),\n (-1, 1),\n (1, -1),\n (-1, 0),\n (0, -1),\n (-1, -1)\n]\n```\n\nEach tuple in offset represents the offset needed to reach one of the eight neighbors.\n\nWe initiate the search by checking the accessibility of the top-left cell $(0, 0)$ and the goal node $(n{-}1, n{-}1)$. If both cells are reachable (i.e., contain $0$), we add the top-left cell to the heap and assign its length as $1$:\n\n```python\nif grid[0][0] == 0 and grid[n-1][n-1] == 0:\n heap.append((n, 0, 0))\n length[0][0] = 1\n```\n\nWhile there are cells in the heap, we extract the cell with the smallest $f$ score and explore its neighbors. For each neighbor cell $(x, y)$, if it is within the grid bounds and contains $0$, and if the new cost $L$ from start to the neighbor cell is smaller than the current cost, we update the cost and add the neighbor to the heap:\n\n```python\nwhile heap:\n _, i, j = heappop(heap)\n L = length[i][j] + 1\n\n if (i, j) == (n - 1, n - 1):\n return L - 1\n\n for di, dj in offset:\n x, y = i + di, j + dj\n if 0 <= x < n and 0 <= y < n:\n if grid[x][y] == 0 and length[x][y] > L:\n length[x][y] = L\n heappush(heap, (L + max(n - x, n - y), x, y))\n```\n\nIf the bottom-right cell cannot be reached, the function returns -1.
1
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
BFS
shortest-path-in-binary-matrix
0
1
\n```CPP []\nstruct cell{\n int row, col;\n};\n\nclass Solution {\npublic:\n int shortestPathBinaryMatrix(vector<vector<int>>& grid) \n {\n int n = grid.size()-1, pr, pc, r, c;\n if(grid[0][0] == 1 || grid[n][n] == 1) return -1;\n if(grid.size() == 1) return 1;\n\n queue<cell> q(deque<cell> {{0,0}});\n vector<vector<int>> diff = {{0,-1}, {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}};\n\n for(int level=2, size=1; !q.empty(); level++, size=q.size())\n {\n while(size--)\n {\n pr = q.front().row, pc = q.front().col; q.pop();\n for(auto &d: diff)\n {\n r = pr+d[0], c = pc+d[1];\n if(r<0 || r>n || c<0 || c>n || grid[r][c]!=0)\n continue;\n if(r==n && c==n) return level;\n grid[r][c] = 2;\n q.push({r,c});\n }\n }\n }\n\n return -1;\n }\n};\n```\n```Python []\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n n = len(grid) - 1\n if grid[0][0] == 1 or grid[n][n] == 1: return -1\n if len(grid) == 1: return 1\n\n q, level = deque([(0,0)]), 2\n while q:\n for _ in range(len(q)):\n pr, pc = q.popleft()\n for (x,y) in ((0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1)):\n r, c = pr + x, pc + y\n if r<0 or r>n or c<0 or c>n or grid[r][c] != 0:\n continue\n if r == n and c == n: return level\n grid[r][c] = 2\n q.append((r, c))\n level += 1\n\n return -1\n```\n```\nTime complexity : O(n*n)\nSpace complexity : O(n*n)\n```
1
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
BFS
shortest-path-in-binary-matrix
0
1
\n```CPP []\nstruct cell{\n int row, col;\n};\n\nclass Solution {\npublic:\n int shortestPathBinaryMatrix(vector<vector<int>>& grid) \n {\n int n = grid.size()-1, pr, pc, r, c;\n if(grid[0][0] == 1 || grid[n][n] == 1) return -1;\n if(grid.size() == 1) return 1;\n\n queue<cell> q(deque<cell> {{0,0}});\n vector<vector<int>> diff = {{0,-1}, {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}};\n\n for(int level=2, size=1; !q.empty(); level++, size=q.size())\n {\n while(size--)\n {\n pr = q.front().row, pc = q.front().col; q.pop();\n for(auto &d: diff)\n {\n r = pr+d[0], c = pc+d[1];\n if(r<0 || r>n || c<0 || c>n || grid[r][c]!=0)\n continue;\n if(r==n && c==n) return level;\n grid[r][c] = 2;\n q.push({r,c});\n }\n }\n }\n\n return -1;\n }\n};\n```\n```Python []\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n n = len(grid) - 1\n if grid[0][0] == 1 or grid[n][n] == 1: return -1\n if len(grid) == 1: return 1\n\n q, level = deque([(0,0)]), 2\n while q:\n for _ in range(len(q)):\n pr, pc = q.popleft()\n for (x,y) in ((0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1)):\n r, c = pr + x, pc + y\n if r<0 or r>n or c<0 or c>n or grid[r][c] != 0:\n continue\n if r == n and c == n: return level\n grid[r][c] = 2\n q.append((r, c))\n level += 1\n\n return -1\n```\n```\nTime complexity : O(n*n)\nSpace complexity : O(n*n)\n```
1
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
[ Python ] ✅✅ Simple Python Solution Using Queue and BFS🥳✌👍
shortest-path-in-binary-matrix
0
1
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 785 ms, faster than 21.72% of Python3 online submissions for Shortest Path in Binary Matrix.\n# Memory Usage: 18 MB, less than 12.33% of Python3 online submissions for Shortest Path in Binary Matrix.\n\n\tclass Solution:\n\t\tdef shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n\n\t\t\tlength = len(grid)\n\n\t\t\tif grid[0][0] == 1 or grid[length - 1][length - 1] == 1:\n\t\t\t\treturn -1\n\n\t\t\tvisited = set((0,0))\n\n\t\t\tdirections = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, 1], [1, -1]]\n\n\t\t\tqueue = collections.deque([(1,0,0)])\n\n\t\t\twhile queue:\n\n\t\t\t\tcurrent_distance, current_position_x , current_position_y = queue.popleft()\n\n\t\t\t\tif current_position_x == length - 1 and current_position_y == length - 1:\n\t\t\t\t\treturn current_distance\n\n\t\t\t\tfor direction in directions:\n\n\t\t\t\t\tx , y = direction\n\n\t\t\t\t\tnext_position_x , next_position_y = current_position_x + x , current_position_y + y\n\n\t\t\t\t\tif 0 <= current_position_x < length and 0 <= current_position_y < length and grid[current_position_x][current_position_y] == 0 and (next_position_x , next_position_y) not in visited: \n\n\t\t\t\t\t\tqueue.append((current_distance + 1 , next_position_x , next_position_y))\n\t\t\t\t\t\tvisited.add((next_position_x , next_position_y))\n\n\t\t\treturn -1\n\t\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D
4
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
[ Python ] ✅✅ Simple Python Solution Using Queue and BFS🥳✌👍
shortest-path-in-binary-matrix
0
1
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 785 ms, faster than 21.72% of Python3 online submissions for Shortest Path in Binary Matrix.\n# Memory Usage: 18 MB, less than 12.33% of Python3 online submissions for Shortest Path in Binary Matrix.\n\n\tclass Solution:\n\t\tdef shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n\n\t\t\tlength = len(grid)\n\n\t\t\tif grid[0][0] == 1 or grid[length - 1][length - 1] == 1:\n\t\t\t\treturn -1\n\n\t\t\tvisited = set((0,0))\n\n\t\t\tdirections = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, 1], [1, -1]]\n\n\t\t\tqueue = collections.deque([(1,0,0)])\n\n\t\t\twhile queue:\n\n\t\t\t\tcurrent_distance, current_position_x , current_position_y = queue.popleft()\n\n\t\t\t\tif current_position_x == length - 1 and current_position_y == length - 1:\n\t\t\t\t\treturn current_distance\n\n\t\t\t\tfor direction in directions:\n\n\t\t\t\t\tx , y = direction\n\n\t\t\t\t\tnext_position_x , next_position_y = current_position_x + x , current_position_y + y\n\n\t\t\t\t\tif 0 <= current_position_x < length and 0 <= current_position_y < length and grid[current_position_x][current_position_y] == 0 and (next_position_x , next_position_y) not in visited: \n\n\t\t\t\t\t\tqueue.append((current_distance + 1 , next_position_x , next_position_y))\n\t\t\t\t\t\tvisited.add((next_position_x , next_position_y))\n\n\t\t\treturn -1\n\t\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D
4
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
EASY PYTHON SOLUTION USING BFS TRAVERSAL
shortest-path-in-binary-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n m,n=len(grid),len(grid[0])\n vis=[[0]*n for _ in range(m)]\n if grid[0][0]==1:\n return -1\n queue=[(0,0,1)]\n vis[0][0]=1\n while queue:\n x,y,d=queue.pop(0)\n if x==m-1 and y==n-1:\n return d\n # print(x,y,d)\n for i in range(-1,2):\n for j in range(-1,2):\n if 0<=x+i<m and 0<=y+j<n:\n if vis[x+i][y+j]==0 and grid[x+i][y+j]==0:\n queue.append((x+i,y+j,d+1))\n vis[x+i][y+j]=1\n return -1\n\n \n```
3
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
EASY PYTHON SOLUTION USING BFS TRAVERSAL
shortest-path-in-binary-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n m,n=len(grid),len(grid[0])\n vis=[[0]*n for _ in range(m)]\n if grid[0][0]==1:\n return -1\n queue=[(0,0,1)]\n vis[0][0]=1\n while queue:\n x,y,d=queue.pop(0)\n if x==m-1 and y==n-1:\n return d\n # print(x,y,d)\n for i in range(-1,2):\n for j in range(-1,2):\n if 0<=x+i<m and 0<=y+j<n:\n if vis[x+i][y+j]==0 and grid[x+i][y+j]==0:\n queue.append((x+i,y+j,d+1))\n vis[x+i][y+j]=1\n return -1\n\n \n```
3
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Elegant BFS solution beats 90%
shortest-path-in-binary-matrix
0
1
# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Code\n```\nfrom collections import deque\n\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n n = len(grid)\n visited = [[False] * n for _ in range(n)]\n queue = deque()\n if grid[0][0] == 0:\n queue.append((0, 0, 1))\n visited[0][0] = True\n\n while queue:\n i, j, level = queue.popleft()\n path.append((i, j))\n if i == n - 1 and j == n - 1:\n return level\n for x, y in [\n (i+1, j+1), (i+1, j), (i, j+1), (i+1, j-1), (i, j-1), (i-1, j+1), (i-1, j), (i-1, j-1),\n ]:\n if 0 <= x < n and 0 <= y < n and not visited[x][y]:\n if grid[x][y] == 0:\n queue.append((x, y, level+1))\n visited[x][y] = True\n return -1\n \n```
0
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
Elegant BFS solution beats 90%
shortest-path-in-binary-matrix
0
1
# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Code\n```\nfrom collections import deque\n\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n n = len(grid)\n visited = [[False] * n for _ in range(n)]\n queue = deque()\n if grid[0][0] == 0:\n queue.append((0, 0, 1))\n visited[0][0] = True\n\n while queue:\n i, j, level = queue.popleft()\n path.append((i, j))\n if i == n - 1 and j == n - 1:\n return level\n for x, y in [\n (i+1, j+1), (i+1, j), (i, j+1), (i+1, j-1), (i, j-1), (i-1, j+1), (i-1, j), (i-1, j-1),\n ]:\n if 0 <= x < n and 0 <= y < n and not visited[x][y]:\n if grid[x][y] == 0:\n queue.append((x, y, level+1))\n visited[x][y] = True\n return -1\n \n```
0
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Python || DP || Easy || LCS
shortest-common-supersequence
0
1
```\nclass Solution:\n def shortestCommonSupersequence(self, s1: str, s2: str) -> str:\n n,m=len(s1),len(s2)\n dp=[[0 for j in range(m+1)] for i in range(n+1)]\n for i in range(1,n+1):\n for j in range(1,m+1):\n if s1[i-1]==s2[j-1]:\n dp[i][j]=1+dp[i-1][j-1]\n else:\n dp[i][j]=max(dp[i-1][j],dp[i][j-1])\n s=\'\'\n i,j=n,m\n while i > 0 and j > 0:\n if s1[i - 1] == s2[j - 1]:\n s+= s1[i - 1]\n i -= 1\n j -= 1\n elif dp[i - 1][j] > dp[i][j - 1]:\n s+=s1[i-1]\n i -= 1\n else:\n s+=s2[j-1]\n j -= 1\n while i>0:\n s+=s1[i-1]\n i-=1\n while j>0:\n s+=s2[j-1]\n j-=1 \n return s[-1::-1]\n```\n**An upvote will be encouraging**
2
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them. A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`. **Example 1:** **Input:** str1 = "abac ", str2 = "cab " **Output:** "cabac " **Explanation:** str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ". str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ". The answer provided is the shortest such string that satisfies these properties. **Example 2:** **Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa " **Output:** "aaaaaaaa " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of lowercase English letters.
For each subtree, find the minimum value and maximum value of its descendants.
Python || DP || Easy || LCS
shortest-common-supersequence
0
1
```\nclass Solution:\n def shortestCommonSupersequence(self, s1: str, s2: str) -> str:\n n,m=len(s1),len(s2)\n dp=[[0 for j in range(m+1)] for i in range(n+1)]\n for i in range(1,n+1):\n for j in range(1,m+1):\n if s1[i-1]==s2[j-1]:\n dp[i][j]=1+dp[i-1][j-1]\n else:\n dp[i][j]=max(dp[i-1][j],dp[i][j-1])\n s=\'\'\n i,j=n,m\n while i > 0 and j > 0:\n if s1[i - 1] == s2[j - 1]:\n s+= s1[i - 1]\n i -= 1\n j -= 1\n elif dp[i - 1][j] > dp[i][j - 1]:\n s+=s1[i-1]\n i -= 1\n else:\n s+=s2[j-1]\n j -= 1\n while i>0:\n s+=s1[i-1]\n i-=1\n while j>0:\n s+=s2[j-1]\n j-=1 \n return s[-1::-1]\n```\n**An upvote will be encouraging**
2
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2. You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`. Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\] **Output:** \[1\] **Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz "). **Example 2:** **Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** \[1,2\] **Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc "). **Constraints:** * `1 <= queries.length <= 2000` * `1 <= words.length <= 2000` * `1 <= queries[i].length, words[i].length <= 10` * `queries[i][j]`, `words[i][j]` consist of lowercase English letters.
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.
✔💯 DAY 403 | EASY LCS | 0MS-100% | | [PYTHON/JAVA/C++] | EXPLAINED Approach 🆙🆙🆙
shortest-common-supersequence
1
1
\n\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n# Intuition & Approach\n\n##### \u2022\tThe shortestCommonSupersequence method takes two strings s1 and s2 as input and returns their shortest common supersequence\n##### \u2022\tThe first finds the longest common subsequence (LCS) of s1 and s2 using the lcs helper method\n##### \u2022\tThe lcs method takes two strings s1 and s2 as input and returns their LCS\n##### \u2022\tIt uses dynamic programming to fill a 2D array dp where dp[i][j] represents the length of the LCS of the first i characters of s1 and the first j characters of s2\n##### \u2022 Then backtracks from the bottom right corner of the dp array to find the LCS\n##### \u2022\tThe shortestCommonSupersequence method then merges s1 and s2 with the LCS to create the shortest common supersequence\n##### \u2022\tIt uses a StringBuilder to build the merged string\n##### \u2022\tThe method iterates over the characters of the LCS and adds characters from s1 and s2 until the LCS character is found\n##### \u2022\tIt then adds the LCS character to the merged string\n##### \u2022\tAfter all the LCS characters have been added, the method adds any remaining characters from s1 and s2 to the merged string\n##### \u2022\tThe method returns the merged string as the shortest common supersequence\n##### \u2022\tThe approach is to find the LCS of the two input strings and then merge the strings with the LCS to create the shortest common supersequence\n##### \u2022\tThe use of dynamic programming to find the LCS allows for an efficient solution\n\n# Code\n```java []\npublic String shortestCommonSupersequence(String s1, String s2) {\n // find the LCS of s1 and s2\n char lcs[] = lcs(s1,s2).toCharArray();\n int i=0,j=0;\n StringBuilder sb = new StringBuilder();\n // merge s1 and s2 with the LCS\n for(char c:lcs){\n // add characters from s1 until the LCS character is found\n while(s1.charAt(i)!=c) sb.append(s1.charAt(i++));\n // add characters from s2 until the LCS character is found\n while(s2.charAt(j)!=c) sb.append(s2.charAt(j++));\n // add the LCS character\n sb.append(c);\n i++;\n j++;\n }\n // add any remaining characters from s1 and s2\n sb.append(s1.substring(i)).append(s2.substring(j));\n // return the merged string\n return sb.toString();\n}\n\n// helper method to find the LCS of two strings\nString lcs(String s1,String s2){\n int m = s1.length(),n=s2.length();\n int dp[][] = new int[m+1][n+1];\n // fill the dp array using dynamic programming\n for(int i=1;i<=m;i++){\n for(int j=1;j<=n;j++){\n if(s1.charAt(i-1)==s2.charAt(j-1)){\n dp[i][j]=1+dp[i-1][j-1];\n }else dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);\n }\n }\n // backtrack from the bottom right corner of the dp array to find the LCS\n StringBuilder sb = new StringBuilder();\n int i=m,j=n;\n while(i>0 && j>0){\n if(s1.charAt(i-1)==s2.charAt(j-1)){\n sb.append(s1.charAt(i-1));\n i--;\n j--;\n }else if(dp[i-1][j]>dp[i][j-1]) i--;\n else j--;\n }\n // reverse the LCS string and return it\n return sb.reverse().toString();\n}\n```\n```c++ []\nclass Solution {\npublic:\n string shortestCommonSupersequence(string s1, string s2) {\n // find the LCS of s1 and s2\n string lcs = getLCS(s1, s2);\n int i = 0, j = 0;\n string result = "";\n // merge s1 and s2 with the LCS\n for (char c : lcs) {\n // add characters from s1 until the LCS character is found\n while (s1[i] != c) {\n result += s1[i];\n i++;\n }\n // add characters from s2 until the LCS character is found\n while (s2[j] != c) {\n result += s2[j];\n j++;\n }\n // add the LCS character\n result += c;\n i++;\n j++;\n }\n // add any remaining characters from s1 and s2\n result += s1.substr(i) + s2.substr(j);\n // return the merged string\n return result;\n }\n\n // helper method to find the LCS of two strings\n string getLCS(string s1, string s2) {\n int m = s1.length(), n = s2.length();\n vector<vector<int>> dp(m+1, vector<int>(n+1));\n // fill the dp array using dynamic programming\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (s1[i-1] == s2[j-1]) {\n dp[i][j] = 1 + dp[i-1][j-1];\n } else {\n dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n }\n }\n }\n // backtrack from the bottom right corner of the dp array to find the LCS\n string lcs = "";\n int i = m, j = n;\n while (i > 0 && j > 0) {\n if (s1[i-1] == s2[j-1]) {\n lcs = s1[i-1] + lcs;\n i--;\n j--;\n } else if (dp[i-1][j] > dp[i][j-1]) {\n i--;\n } else {\n j--;\n }\n }\n return lcs;\n }\n};\n```\n```python []\nclass Solution:\n def shortestCommonSupersequence(self, s1: str, s2: str) -> str:\n # find the LCS of s1 and s2\n lcs = self.getLCS(s1, s2)\n i, j = 0, 0\n result = ""\n # merge s1 and s2 with the LCS\n for c in lcs:\n # add characters from s1 until the LCS character is found\n while s1[i] != c:\n result += s1[i]\n i += 1\n # add characters from s2 until the LCS character is found\n while s2[j] != c:\n result += s2[j]\n j += 1\n # add the LCS character\n result += c\n i += 1\n j += 1\n # add any remaining characters from s1 and s2\n result += s1[i:] + s2[j:]\n # return the merged string\n return result\n\n # helper method to find the LCS of two strings\n def getLCS(self, s1: str, s2: str) -> str:\n m, n = len(s1), len(s2)\n dp = [[0] * (n+1) for _ in range(m+1)]\n # fill the dp array using dynamic programming\n for i in range(1, m+1):\n for j in range(1, n+1):\n if s1[i-1] == s2[j-1]:\n dp[i][j] = 1 + dp[i-1][j-1]\n else:\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n # backtrack from the bottom right corner of the dp array to find the LCS\n lcs = ""\n i, j = m, n\n while i > 0 and j > 0:\n if s1[i-1] == s2[j-1]:\n lcs = s1[i-1] + lcs\n i -= 1\n j -= 1\n elif dp[i-1][j] > dp[i][j-1]:\n i -= 1\n else:\n j -= 1\n return lcs\n```\n\n# Complexity\n- Time complexity:o(n2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# optimal \n```java []\n public String shortestCommonSupersequence(String s1, String s2) {\n // find the LCS of s1 and s2\n int m = s1.length(),n=s2.length();\n int dp[][] = new int[m+1][n+1];\n // fill the dp array using dynamic programming\n for(int i=1;i<=m;i++){\n for(int j=1;j<=n;j++){\n if(s1.charAt(i-1)==s2.charAt(j-1)){\n dp[i][j]=1+dp[i-1][j-1];\n }else dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);\n }\n }\n // backtrack from the bottom right corner of the dp array to find the LCS\n StringBuilder sb = new StringBuilder();\n int i=m,j=n;\n while(i>0 && j>0){\n if(s1.charAt(i-1)==s2.charAt(j-1)){\n sb.append(s1.charAt(i-1));\n i--;\n j--;\n }else if(dp[i-1][j]>dp[i][j-1]){//shrink s1\n sb.append(s1.charAt(i-1));\n i--;\n }else{\n sb.append(s2.charAt(j-1));\n j--;\n }\n }\n while(i>0){//remaing 1 element in s1\n sb.append(s1.charAt(i-1));\n i--;\n }\n while(j>0){\n sb.append(s2.charAt(j-1));\n j--;\n }\n // reverse the LCS string and return it\n return sb.reverse().toString();\n}\n```\n\n\n![BREUSELEE.webp](https://assets.leetcode.com/users/images/062630f0-ef80-4e74-abdb-302827b99235_1680054012.5054147.webp)\n![image.png](https://assets.leetcode.com/users/images/303fa18d-281d-49f0-87ef-1a018fc9a488_1681355186.0923774.png)\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A
24
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them. A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`. **Example 1:** **Input:** str1 = "abac ", str2 = "cab " **Output:** "cabac " **Explanation:** str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ". str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ". The answer provided is the shortest such string that satisfies these properties. **Example 2:** **Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa " **Output:** "aaaaaaaa " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of lowercase English letters.
For each subtree, find the minimum value and maximum value of its descendants.
✔💯 DAY 403 | EASY LCS | 0MS-100% | | [PYTHON/JAVA/C++] | EXPLAINED Approach 🆙🆙🆙
shortest-common-supersequence
1
1
\n\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n# Intuition & Approach\n\n##### \u2022\tThe shortestCommonSupersequence method takes two strings s1 and s2 as input and returns their shortest common supersequence\n##### \u2022\tThe first finds the longest common subsequence (LCS) of s1 and s2 using the lcs helper method\n##### \u2022\tThe lcs method takes two strings s1 and s2 as input and returns their LCS\n##### \u2022\tIt uses dynamic programming to fill a 2D array dp where dp[i][j] represents the length of the LCS of the first i characters of s1 and the first j characters of s2\n##### \u2022 Then backtracks from the bottom right corner of the dp array to find the LCS\n##### \u2022\tThe shortestCommonSupersequence method then merges s1 and s2 with the LCS to create the shortest common supersequence\n##### \u2022\tIt uses a StringBuilder to build the merged string\n##### \u2022\tThe method iterates over the characters of the LCS and adds characters from s1 and s2 until the LCS character is found\n##### \u2022\tIt then adds the LCS character to the merged string\n##### \u2022\tAfter all the LCS characters have been added, the method adds any remaining characters from s1 and s2 to the merged string\n##### \u2022\tThe method returns the merged string as the shortest common supersequence\n##### \u2022\tThe approach is to find the LCS of the two input strings and then merge the strings with the LCS to create the shortest common supersequence\n##### \u2022\tThe use of dynamic programming to find the LCS allows for an efficient solution\n\n# Code\n```java []\npublic String shortestCommonSupersequence(String s1, String s2) {\n // find the LCS of s1 and s2\n char lcs[] = lcs(s1,s2).toCharArray();\n int i=0,j=0;\n StringBuilder sb = new StringBuilder();\n // merge s1 and s2 with the LCS\n for(char c:lcs){\n // add characters from s1 until the LCS character is found\n while(s1.charAt(i)!=c) sb.append(s1.charAt(i++));\n // add characters from s2 until the LCS character is found\n while(s2.charAt(j)!=c) sb.append(s2.charAt(j++));\n // add the LCS character\n sb.append(c);\n i++;\n j++;\n }\n // add any remaining characters from s1 and s2\n sb.append(s1.substring(i)).append(s2.substring(j));\n // return the merged string\n return sb.toString();\n}\n\n// helper method to find the LCS of two strings\nString lcs(String s1,String s2){\n int m = s1.length(),n=s2.length();\n int dp[][] = new int[m+1][n+1];\n // fill the dp array using dynamic programming\n for(int i=1;i<=m;i++){\n for(int j=1;j<=n;j++){\n if(s1.charAt(i-1)==s2.charAt(j-1)){\n dp[i][j]=1+dp[i-1][j-1];\n }else dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);\n }\n }\n // backtrack from the bottom right corner of the dp array to find the LCS\n StringBuilder sb = new StringBuilder();\n int i=m,j=n;\n while(i>0 && j>0){\n if(s1.charAt(i-1)==s2.charAt(j-1)){\n sb.append(s1.charAt(i-1));\n i--;\n j--;\n }else if(dp[i-1][j]>dp[i][j-1]) i--;\n else j--;\n }\n // reverse the LCS string and return it\n return sb.reverse().toString();\n}\n```\n```c++ []\nclass Solution {\npublic:\n string shortestCommonSupersequence(string s1, string s2) {\n // find the LCS of s1 and s2\n string lcs = getLCS(s1, s2);\n int i = 0, j = 0;\n string result = "";\n // merge s1 and s2 with the LCS\n for (char c : lcs) {\n // add characters from s1 until the LCS character is found\n while (s1[i] != c) {\n result += s1[i];\n i++;\n }\n // add characters from s2 until the LCS character is found\n while (s2[j] != c) {\n result += s2[j];\n j++;\n }\n // add the LCS character\n result += c;\n i++;\n j++;\n }\n // add any remaining characters from s1 and s2\n result += s1.substr(i) + s2.substr(j);\n // return the merged string\n return result;\n }\n\n // helper method to find the LCS of two strings\n string getLCS(string s1, string s2) {\n int m = s1.length(), n = s2.length();\n vector<vector<int>> dp(m+1, vector<int>(n+1));\n // fill the dp array using dynamic programming\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (s1[i-1] == s2[j-1]) {\n dp[i][j] = 1 + dp[i-1][j-1];\n } else {\n dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n }\n }\n }\n // backtrack from the bottom right corner of the dp array to find the LCS\n string lcs = "";\n int i = m, j = n;\n while (i > 0 && j > 0) {\n if (s1[i-1] == s2[j-1]) {\n lcs = s1[i-1] + lcs;\n i--;\n j--;\n } else if (dp[i-1][j] > dp[i][j-1]) {\n i--;\n } else {\n j--;\n }\n }\n return lcs;\n }\n};\n```\n```python []\nclass Solution:\n def shortestCommonSupersequence(self, s1: str, s2: str) -> str:\n # find the LCS of s1 and s2\n lcs = self.getLCS(s1, s2)\n i, j = 0, 0\n result = ""\n # merge s1 and s2 with the LCS\n for c in lcs:\n # add characters from s1 until the LCS character is found\n while s1[i] != c:\n result += s1[i]\n i += 1\n # add characters from s2 until the LCS character is found\n while s2[j] != c:\n result += s2[j]\n j += 1\n # add the LCS character\n result += c\n i += 1\n j += 1\n # add any remaining characters from s1 and s2\n result += s1[i:] + s2[j:]\n # return the merged string\n return result\n\n # helper method to find the LCS of two strings\n def getLCS(self, s1: str, s2: str) -> str:\n m, n = len(s1), len(s2)\n dp = [[0] * (n+1) for _ in range(m+1)]\n # fill the dp array using dynamic programming\n for i in range(1, m+1):\n for j in range(1, n+1):\n if s1[i-1] == s2[j-1]:\n dp[i][j] = 1 + dp[i-1][j-1]\n else:\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n # backtrack from the bottom right corner of the dp array to find the LCS\n lcs = ""\n i, j = m, n\n while i > 0 and j > 0:\n if s1[i-1] == s2[j-1]:\n lcs = s1[i-1] + lcs\n i -= 1\n j -= 1\n elif dp[i-1][j] > dp[i][j-1]:\n i -= 1\n else:\n j -= 1\n return lcs\n```\n\n# Complexity\n- Time complexity:o(n2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# optimal \n```java []\n public String shortestCommonSupersequence(String s1, String s2) {\n // find the LCS of s1 and s2\n int m = s1.length(),n=s2.length();\n int dp[][] = new int[m+1][n+1];\n // fill the dp array using dynamic programming\n for(int i=1;i<=m;i++){\n for(int j=1;j<=n;j++){\n if(s1.charAt(i-1)==s2.charAt(j-1)){\n dp[i][j]=1+dp[i-1][j-1];\n }else dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);\n }\n }\n // backtrack from the bottom right corner of the dp array to find the LCS\n StringBuilder sb = new StringBuilder();\n int i=m,j=n;\n while(i>0 && j>0){\n if(s1.charAt(i-1)==s2.charAt(j-1)){\n sb.append(s1.charAt(i-1));\n i--;\n j--;\n }else if(dp[i-1][j]>dp[i][j-1]){//shrink s1\n sb.append(s1.charAt(i-1));\n i--;\n }else{\n sb.append(s2.charAt(j-1));\n j--;\n }\n }\n while(i>0){//remaing 1 element in s1\n sb.append(s1.charAt(i-1));\n i--;\n }\n while(j>0){\n sb.append(s2.charAt(j-1));\n j--;\n }\n // reverse the LCS string and return it\n return sb.reverse().toString();\n}\n```\n\n\n![BREUSELEE.webp](https://assets.leetcode.com/users/images/062630f0-ef80-4e74-abdb-302827b99235_1680054012.5054147.webp)\n![image.png](https://assets.leetcode.com/users/images/303fa18d-281d-49f0-87ef-1a018fc9a488_1681355186.0923774.png)\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A
24
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2. You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`. Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\] **Output:** \[1\] **Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz "). **Example 2:** **Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** \[1,2\] **Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc "). **Constraints:** * `1 <= queries.length <= 2000` * `1 <= words.length <= 2000` * `1 <= queries[i].length, words[i].length <= 10` * `queries[i][j]`, `words[i][j]` consist of lowercase English letters.
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.
Python || Using LCS || Tabulation
shortest-common-supersequence
0
1
> **First Solve Leetcode Ques No. ->> 1143 - Longest Common Subsequence** \n\n[Navigate to Leetcode problem 1143. ](https://leetcode.com/problems/longest-common-subsequence/solutions/4122297/python-96-beats-tabulation-dp-memorization-optimize-way-2d-matrix-way/)\n\n# Approach\nFirst We Create 2-d matrix and fill it (like LCS)\nthen travel in matix from end to start and store the char from string\n\n# Complexity\n> - Time complexity:\nO(N^2)\n\n> - Space complexity:\nO(N^2)\n\n# Code\n```\nclass Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n\n # LCS Part\n n1 = len(str1)\n n2 = len(str2)\n\n dp = [[0 for j in range(n2+1)] for i in range(n1+1)]\n\n for i in range(1,n1+1):\n for j in range(1,n2+1):\n if str1[i-1] == str2[j-1]:\n dp[i][j] = 1+ dp[i-1][j-1]\n else:\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n\n ans = \'\'\n i = n1\n j = n2\n\n # Get String from 2-d matrix\n while i >0 and j > 0:\n if str1[i-1] == str2[j-1]:\n ans += str1[i-1]\n i -= 1\n j -= 1\n elif dp[i-1][j] > dp[i][j-1]:\n print(i,j)\n ans += str1[i-1]\n i -= 1\n else:\n ans += str2[j-1]\n j -= 1\n \n while i > 0:\n ans += str1[i-1]\n i -= 1\n \n while j > 0:\n ans += str2[j-1]\n j -= 1\n\n return ans[::-1]\n\n```\n# Your upvote is my motivation!\n\n.
2
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them. A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`. **Example 1:** **Input:** str1 = "abac ", str2 = "cab " **Output:** "cabac " **Explanation:** str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ". str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ". The answer provided is the shortest such string that satisfies these properties. **Example 2:** **Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa " **Output:** "aaaaaaaa " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of lowercase English letters.
For each subtree, find the minimum value and maximum value of its descendants.
Python || Using LCS || Tabulation
shortest-common-supersequence
0
1
> **First Solve Leetcode Ques No. ->> 1143 - Longest Common Subsequence** \n\n[Navigate to Leetcode problem 1143. ](https://leetcode.com/problems/longest-common-subsequence/solutions/4122297/python-96-beats-tabulation-dp-memorization-optimize-way-2d-matrix-way/)\n\n# Approach\nFirst We Create 2-d matrix and fill it (like LCS)\nthen travel in matix from end to start and store the char from string\n\n# Complexity\n> - Time complexity:\nO(N^2)\n\n> - Space complexity:\nO(N^2)\n\n# Code\n```\nclass Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n\n # LCS Part\n n1 = len(str1)\n n2 = len(str2)\n\n dp = [[0 for j in range(n2+1)] for i in range(n1+1)]\n\n for i in range(1,n1+1):\n for j in range(1,n2+1):\n if str1[i-1] == str2[j-1]:\n dp[i][j] = 1+ dp[i-1][j-1]\n else:\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n\n ans = \'\'\n i = n1\n j = n2\n\n # Get String from 2-d matrix\n while i >0 and j > 0:\n if str1[i-1] == str2[j-1]:\n ans += str1[i-1]\n i -= 1\n j -= 1\n elif dp[i-1][j] > dp[i][j-1]:\n print(i,j)\n ans += str1[i-1]\n i -= 1\n else:\n ans += str2[j-1]\n j -= 1\n \n while i > 0:\n ans += str1[i-1]\n i -= 1\n \n while j > 0:\n ans += str2[j-1]\n j -= 1\n\n return ans[::-1]\n\n```\n# Your upvote is my motivation!\n\n.
2
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2. You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`. Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\] **Output:** \[1\] **Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz "). **Example 2:** **Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** \[1,2\] **Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc "). **Constraints:** * `1 <= queries.length <= 2000` * `1 <= words.length <= 2000` * `1 <= queries[i].length, words[i].length <= 10` * `queries[i][j]`, `words[i][j]` consist of lowercase English letters.
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.
Easiest Python code- Clean and simple (Striver)
shortest-common-supersequence
0
1
\n\n# Code\n```\nclass Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n n=len(str1)\n m=len(str2)\n ans=""\n i=n\n j=m\n dp=[[0]*(m+1) for _ in range(n+1)]\n for j in range(m+1):\n dp[0][j]=0\n for i in range(n+1):\n dp[i][0]=0\n for i in range(1,n+1):\n for j in range(1,m+1):\n if str1[i-1]==str2[j-1]:\n dp[i][j]=1+dp[i-1][j-1]\n else:\n dp[i][j]=max(dp[i][j-1],dp[i-1][j])\n \n while(i>0 and j>0):\n if str1[i-1]==str2[j-1]:\n ans+=str1[i-1]\n i=i-1\n j=j-1\n elif dp[i-1][j]>dp[i][j-1]:\n ans+=str1[i-1]\n i=i-1\n else:\n ans+=str2[j-1]\n j=j-1\n while i>0:\n ans+=str1[i-1]\n i-=1\n while j>0:\n ans+=str2[j-1]\n j-=1\n return ans[::-1]\n \n```
1
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them. A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`. **Example 1:** **Input:** str1 = "abac ", str2 = "cab " **Output:** "cabac " **Explanation:** str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ". str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ". The answer provided is the shortest such string that satisfies these properties. **Example 2:** **Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa " **Output:** "aaaaaaaa " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of lowercase English letters.
For each subtree, find the minimum value and maximum value of its descendants.
Easiest Python code- Clean and simple (Striver)
shortest-common-supersequence
0
1
\n\n# Code\n```\nclass Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n n=len(str1)\n m=len(str2)\n ans=""\n i=n\n j=m\n dp=[[0]*(m+1) for _ in range(n+1)]\n for j in range(m+1):\n dp[0][j]=0\n for i in range(n+1):\n dp[i][0]=0\n for i in range(1,n+1):\n for j in range(1,m+1):\n if str1[i-1]==str2[j-1]:\n dp[i][j]=1+dp[i-1][j-1]\n else:\n dp[i][j]=max(dp[i][j-1],dp[i-1][j])\n \n while(i>0 and j>0):\n if str1[i-1]==str2[j-1]:\n ans+=str1[i-1]\n i=i-1\n j=j-1\n elif dp[i-1][j]>dp[i][j-1]:\n ans+=str1[i-1]\n i=i-1\n else:\n ans+=str2[j-1]\n j=j-1\n while i>0:\n ans+=str1[i-1]\n i-=1\n while j>0:\n ans+=str2[j-1]\n j-=1\n return ans[::-1]\n \n```
1
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2. You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`. Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\] **Output:** \[1\] **Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz "). **Example 2:** **Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** \[1,2\] **Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc "). **Constraints:** * `1 <= queries.length <= 2000` * `1 <= words.length <= 2000` * `1 <= queries[i].length, words[i].length <= 10` * `queries[i][j]`, `words[i][j]` consist of lowercase English letters.
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.
Python 3 || dp, w/ example || T/M: 98% / 94%
shortest-common-supersequence
0
1
```\nclass Solution:\n def shortestCommonSupersequence(self, s1: str, s2: str) -> str:\n\n n1, n2 = len(s1)+1, len(s2)+1 # Example: str1 = "abac" str2 = "cab"\n i1, i2, ans = n1-1, n2-1, \'\' # s1 = " abac" s2 = " cab"\n s1,s2 = s1.rjust(n1),s2.rjust(n2)\n dp = [[0] * n2 for _ in range(n1)]\n\n for i1 in range(1, n1):\n for i2 in range(1, n2):\n if s1[i1] == s2[i2]: dp[i1][i2] = dp[i1-1][i2-1] + 1\n else: dp[i1][i2] = max(dp[i1 - 1][i2], dp[i1][i2-1])\n\n while i1|i2: # \' \' c a b\n if not i1*i2: # \' \' [ 0 0 0 0 ]\n ans += s1[i1] if i1 else s2[i2] # a [ 0 0 1 1 ]\n i2 -= bool(i2) ; i1 -= bool(i1) # b [ 0 0 1 2 ]\n # a [ 0 0 1 2 ] \n elif s1[i1] == s2[i2]: # c [ 0 1 1 2 ]\n ans += s1[i1]\n i1 -= 1 ; i2 -= 1\n\n elif dp[i1][i2] == dp[i1-1][i2]: # i1 i2 s[i1] s[i2] ans\n ans += s1[i1] # \u2013\u2013\u2013 \u2013\u2013\u2013 \u2013\u2013\u2013 \u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \n i1 -= 1 # 4 3 c b \'\'\n # 3 3 a b c\n else: # dp[i1][i2] == dp[i1][i2-1] # 2 3 b b ca\n ans += s2[i2] # 1 2 \'\' c caba\n i2 -= 1 # 0 0 \'\' \'\' cabac\n\n return ans[::-1]\n```\n[https://leetcode.com/problems/shortest-common-supersequence/submissions/882059436/](http://)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*^2) and space complexity is *O*(*N*^2).
4
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them. A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`. **Example 1:** **Input:** str1 = "abac ", str2 = "cab " **Output:** "cabac " **Explanation:** str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ". str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ". The answer provided is the shortest such string that satisfies these properties. **Example 2:** **Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa " **Output:** "aaaaaaaa " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of lowercase English letters.
For each subtree, find the minimum value and maximum value of its descendants.
Python 3 || dp, w/ example || T/M: 98% / 94%
shortest-common-supersequence
0
1
```\nclass Solution:\n def shortestCommonSupersequence(self, s1: str, s2: str) -> str:\n\n n1, n2 = len(s1)+1, len(s2)+1 # Example: str1 = "abac" str2 = "cab"\n i1, i2, ans = n1-1, n2-1, \'\' # s1 = " abac" s2 = " cab"\n s1,s2 = s1.rjust(n1),s2.rjust(n2)\n dp = [[0] * n2 for _ in range(n1)]\n\n for i1 in range(1, n1):\n for i2 in range(1, n2):\n if s1[i1] == s2[i2]: dp[i1][i2] = dp[i1-1][i2-1] + 1\n else: dp[i1][i2] = max(dp[i1 - 1][i2], dp[i1][i2-1])\n\n while i1|i2: # \' \' c a b\n if not i1*i2: # \' \' [ 0 0 0 0 ]\n ans += s1[i1] if i1 else s2[i2] # a [ 0 0 1 1 ]\n i2 -= bool(i2) ; i1 -= bool(i1) # b [ 0 0 1 2 ]\n # a [ 0 0 1 2 ] \n elif s1[i1] == s2[i2]: # c [ 0 1 1 2 ]\n ans += s1[i1]\n i1 -= 1 ; i2 -= 1\n\n elif dp[i1][i2] == dp[i1-1][i2]: # i1 i2 s[i1] s[i2] ans\n ans += s1[i1] # \u2013\u2013\u2013 \u2013\u2013\u2013 \u2013\u2013\u2013 \u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \n i1 -= 1 # 4 3 c b \'\'\n # 3 3 a b c\n else: # dp[i1][i2] == dp[i1][i2-1] # 2 3 b b ca\n ans += s2[i2] # 1 2 \'\' c caba\n i2 -= 1 # 0 0 \'\' \'\' cabac\n\n return ans[::-1]\n```\n[https://leetcode.com/problems/shortest-common-supersequence/submissions/882059436/](http://)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*^2) and space complexity is *O*(*N*^2).
4
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2. You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`. Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\] **Output:** \[1\] **Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz "). **Example 2:** **Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** \[1,2\] **Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc "). **Constraints:** * `1 <= queries.length <= 2000` * `1 <= words.length <= 2000` * `1 <= queries[i].length, words[i].length <= 10` * `queries[i][j]`, `words[i][j]` consist of lowercase English letters.
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.