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 ... | 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 rela... | 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... | 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 rela... | 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# Ap... | 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... | 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... | 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... | 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 ... | 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... | 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)$$ --... | 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... | 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... | 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... | 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... | 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(... | 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... | 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 bi... | 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... | 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 ro... | 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... | 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... | 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... | 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 _... | 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 ... |
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 Solu... | 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 _... | 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 ... |
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;... | 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 _... | 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 ... |
[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)*... | 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 _... | 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 ... |
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 => -... | 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 _... | 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 ... |
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\... | 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 _... | 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 ... |
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`, i... | 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 _... | 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 ... |
[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 ... | 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 _... | 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 ... |
[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 resul... | 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 _... | 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 ... |
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 ad... | 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 _... | 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 ... |
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 wher... | 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 _... | 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 ... |
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)$... | 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 _... | 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 ... |
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- ... | 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 _... | 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 ... |
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:**
**In... | 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 fo... | 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:**
**In... | 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... | 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:**
**In... | 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:\... | 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:**
**In... | 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)$$ --... | 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:**
**In... | 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)$$ --... | 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:**
**In... | 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 findO... | 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:**
**In... | 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 **.*... | 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:**
**In... | 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... | 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... | 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... | 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 eac... | 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... | 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 occurrenc... | 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... | 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)$$ --... | 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... | 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... | 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 stric... | 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 n... | 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 ... |
⬆️🔥✅ 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\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O... | 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 n... | 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 ... |
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 complexi... | 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 n... | 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 ... |
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. I... | 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 n... | 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 ... |
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)$$ --... | 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 n... | 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 ... |
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 ... | 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 n... | 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 ... |
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[s... | 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 <=... | 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 mi... |
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 tak... | 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 <=... | 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 mi... |
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 ... | 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 <=... | 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 mi... |
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 mov... | 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 =... | 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 mov... | 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 ho... | 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 us... |
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... | 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 =... | 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... | 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 ho... | 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 us... |
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 +... | 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 =... | 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 +... | 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 ho... | 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 us... |
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... | 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 =... | 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... | 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 ho... | 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 us... |
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 """... | 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 =... | 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 """... | 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 ho... | 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 us... |
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 ... | 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 =... | 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 ... | 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 ho... | 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 us... |
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])... | 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 =... | 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])... | 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 ho... | 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 us... |
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... | 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 =... | 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... | 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 ho... | 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 us... |
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 a... | 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... | 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 ... |
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 a... | 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 ... | 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... | 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... | 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 ... |
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... | 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 ... | 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... | 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... | 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 ... |
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... | 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 ... | 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() ... | 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... | 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 ... |
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() ... | 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 ... | 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)$$ --... | 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... | 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 ... |
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)$$ --... | 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 ... | 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)$$ --... | 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... | 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 ... |
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)$$ --... | 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 ... | 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... | 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... | 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 ... |
✅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... | 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 ... | 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 #... | 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 visite... | 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... |
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 #... | 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.)... | 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 in... | 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 visite... | 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... |
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 in... | 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.)... | 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(deq... | 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 visite... | 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... |
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(deq... | 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.)... | 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 S... | 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 visite... | 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... |
[ 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 S... | 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.)... | 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 ... | 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 visite... | 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... |
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 ... | 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.)... | 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 gri... | 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 visite... | 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... |
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 gri... | 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.)... | 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-... | 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`... | 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-... | 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 s... | 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... | 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`... | 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... | 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 s... | 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 (l... | 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`... | 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 (l... | 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 s... | 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 ... | 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`... | 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 ... | 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 s... | 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(... | 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`... | 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(... | 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 s... | 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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.