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 |
|---|---|---|---|---|---|---|---|
python solution | maximum-number-of-non-overlapping-substrings | 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)$$ -->\nnear about O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity her... | 0 | Given the `root` of a binary tree, return _the lowest common ancestor (LCA) of two given nodes,_ `p` _and_ `q`. If either node `p` or `q` **does not exist** in the tree, return `null`. All values of the nodes in the tree are **unique**.
According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/... | Notice that it's impossible for any two valid substrings to overlap unless one is inside another. We can start by finding the starting and ending index for each character. From these indices, we can form the substrings by expanding each character's range if necessary (if another character exists in the range with small... |
Python | Mono Stack of Candidate Substrings | Easy to Understand | Commented | maximum-number-of-non-overlapping-substrings | 0 | 1 | # Approach\nWe scan the string rom left to right while maintaining stack of nested candidate intervals for a valid minimal substring, backtracking as needed. Stack is cleared once a minimal valid substring found, since strings containing it cannot be minimal.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your ... | 0 | Given a string `s` of lowercase letters, you need to find the maximum number of **non-empty** substrings of `s` that meet the following conditions:
1. The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[x..y]`, either `j < x` or `i > y` is true.
2. A substring that contains a certain chara... | Read the string from right to left, if the string ends in '0' then the number is even otherwise it is odd. Simulate the steps described in the binary string. |
Python | Mono Stack of Candidate Substrings | Easy to Understand | Commented | maximum-number-of-non-overlapping-substrings | 0 | 1 | # Approach\nWe scan the string rom left to right while maintaining stack of nested candidate intervals for a valid minimal substring, backtracking as needed. Stack is cleared once a minimal valid substring found, since strings containing it cannot be minimal.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your ... | 0 | Given the `root` of a binary tree, return _the lowest common ancestor (LCA) of two given nodes,_ `p` _and_ `q`. If either node `p` or `q` **does not exist** in the tree, return `null`. All values of the nodes in the tree are **unique**.
According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/... | Notice that it's impossible for any two valid substrings to overlap unless one is inside another. We can start by finding the starting and ending index for each character. From these indices, we can form the substrings by expanding each character's range if necessary (if another character exists in the range with small... |
[Python3] greedy | maximum-number-of-non-overlapping-substrings | 0 | 1 | \n```\nclass Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n locs = {}\n for i, x in enumerate(s): \n locs.setdefault(x, []).append(i)\n \n def fn(lo, hi): \n """Return expanded range covering all chars in s[lo:hi+1]."""\n for xx in locs: ... | 1 | Given a string `s` of lowercase letters, you need to find the maximum number of **non-empty** substrings of `s` that meet the following conditions:
1. The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[x..y]`, either `j < x` or `i > y` is true.
2. A substring that contains a certain chara... | Read the string from right to left, if the string ends in '0' then the number is even otherwise it is odd. Simulate the steps described in the binary string. |
[Python3] greedy | maximum-number-of-non-overlapping-substrings | 0 | 1 | \n```\nclass Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n locs = {}\n for i, x in enumerate(s): \n locs.setdefault(x, []).append(i)\n \n def fn(lo, hi): \n """Return expanded range covering all chars in s[lo:hi+1]."""\n for xx in locs: ... | 1 | Given the `root` of a binary tree, return _the lowest common ancestor (LCA) of two given nodes,_ `p` _and_ `q`. If either node `p` or `q` **does not exist** in the tree, return `null`. All values of the nodes in the tree are **unique**.
According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/... | Notice that it's impossible for any two valid substrings to overlap unless one is inside another. We can start by finding the starting and ending index for each character. From these indices, we can form the substrings by expanding each character's range if necessary (if another character exists in the range with small... |
[Python3] bitwise and | find-a-value-of-a-mysterious-function-closest-to-target | 0 | 1 | Algo\n[Bitwise operations](https://en.wikipedia.org/wiki/Bitwise_operation) can be efficiently carried out in the bit space. Here, the focus is "bitwise and", and an important property of "bitwise and" is that its result cannot be larger than its operands since no unset bits could be set. Furthermore, given a series of... | 8 | Winston was given the above mysterious function `func`. He has an integer array `arr` and an integer `target` and he wants to find the values `l` and `r` that make the value `|func(arr, l, r) - target|` minimum possible.
Return _the minimum possible value_ of `|func(arr, l, r) - target|`.
Notice that `func` should be... | null |
python solution | find-a-value-of-a-mysterious-function-closest-to-target | 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 | Winston was given the above mysterious function `func`. He has an integer array `arr` and an integer `target` and he wants to find the values `l` and `r` that make the value `|func(arr, l, r) - target|` minimum possible.
Return _the minimum possible value_ of `|func(arr, l, r) - target|`.
Notice that `func` should be... | null |
Python3 solution | find-a-value-of-a-mysterious-function-closest-to-target | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this solution is to use a set to store the values of the array and the bitwise AND operations between all the elements\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach we are using to... | 0 | Winston was given the above mysterious function `func`. He has an integer array `arr` and an integer `target` and he wants to find the values `l` and `r` that make the value `|func(arr, l, r) - target|` minimum possible.
Return _the minimum possible value_ of `|func(arr, l, r) - target|`.
Notice that `func` should be... | null |
Python Linear Time Solution | Faster than 70% | find-a-value-of-a-mysterious-function-closest-to-target | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python []\nclass Solution:\n def closestToTarget(self, arr: List[int], target: int) -> int:\n sz, left, right, ... | 0 | Winston was given the above mysterious function `func`. He has an integer array `arr` and an integer `target` and he wants to find the values `l` and `r` that make the value `|func(arr, l, r) - target|` minimum possible.
Return _the minimum possible value_ of `|func(arr, l, r) - target|`.
Notice that `func` should be... | null |
Segment Tree + Sliding Window | O(nlogn) | find-a-value-of-a-mysterious-function-closest-to-target | 0 | 1 | ```\nclass SegmentTree:\n def __init__(self, values):\n self.data = [0 for _ in values] + values\n self.n = len(values)\n\n for idx in reversed(range(1, self.n)):\n self.data[idx] = self.data[2*idx] & self.data[2*idx+1]\n\n\n def query(self, left, right): ... | 5 | Winston was given the above mysterious function `func`. He has an integer array `arr` and an integer `target` and he wants to find the values `l` and `r` that make the value `|func(arr, l, r) - target|` minimum possible.
Return _the minimum possible value_ of `|func(arr, l, r) - target|`.
Notice that `func` should be... | null |
[Python] Num of SubArray & Num of SubSet, Explained | number-of-sub-arrays-with-odd-sum | 0 | 1 | The solution for ***SubArray*** is straight forward with prefix sum:\n* We count not only the prefix sum, but also the number of even & odd prefix sum\n* For a prefix sum is even, we can only get an odd subarray sum by substract an odd prefix sum\n* For a prefix sum is odd, we can only get an odd subarray sum by substr... | 1 | Given an array of integers `arr`, return _the number of subarrays with an **odd** sum_.
Since the answer can be very large, return it modulo `109 + 7`.
**Example 1:**
**Input:** arr = \[1,3,5\]
**Output:** 4
**Explanation:** All subarrays are \[\[1\],\[1,3\],\[1,3,5\],\[3\],\[3,5\],\[5\]\]
All sub-arrays sum are \[1... | Bruteforce to find if one string is substring of another or use KMP algorithm. |
[Python] Num of SubArray & Num of SubSet, Explained | number-of-sub-arrays-with-odd-sum | 0 | 1 | The solution for ***SubArray*** is straight forward with prefix sum:\n* We count not only the prefix sum, but also the number of even & odd prefix sum\n* For a prefix sum is even, we can only get an odd subarray sum by substract an odd prefix sum\n* For a prefix sum is odd, we can only get an odd subarray sum by substr... | 1 | You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**... | Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa. |
Python3 Recursive Solution | number-of-sub-arrays-with-odd-sum | 0 | 1 | ```\n\nclass Solution:\n def odd(self,arr,summ,i,flag):\n #recursion\n if flag==1 and i>0 and summ>0:\n return summ%2\n if i==len(arr):\n return (summ)%2\n if flag==1:\n summ=0\n return self.odd(arr,summ+arr[i],i+1,0)+self.odd(arr,summ,i+1,1)\n ... | 4 | Given an array of integers `arr`, return _the number of subarrays with an **odd** sum_.
Since the answer can be very large, return it modulo `109 + 7`.
**Example 1:**
**Input:** arr = \[1,3,5\]
**Output:** 4
**Explanation:** All subarrays are \[\[1\],\[1,3\],\[1,3,5\],\[3\],\[3,5\],\[5\]\]
All sub-arrays sum are \[1... | Bruteforce to find if one string is substring of another or use KMP algorithm. |
Python3 Recursive Solution | number-of-sub-arrays-with-odd-sum | 0 | 1 | ```\n\nclass Solution:\n def odd(self,arr,summ,i,flag):\n #recursion\n if flag==1 and i>0 and summ>0:\n return summ%2\n if i==len(arr):\n return (summ)%2\n if flag==1:\n summ=0\n return self.odd(arr,summ+arr[i],i+1,0)+self.odd(arr,summ,i+1,1)\n ... | 4 | You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**... | Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa. |
Python | O(n) time & O(1) space | prefix sum(detailed explanation) | number-of-sub-arrays-with-odd-sum | 0 | 1 | Keys:\n1) odd number - even numer = odd number(e.g., 9 - 4 = 5)\n2) even number - odd number = odd number(e.g., 8 - 3 = 5)\n3) prefix sum: to obtain the sum of subarray `arr[i + 1, j]`, we can use prefix sum by `sum[0, j] - sum[0, i]`.\n\nIdea:\n1) Keep two counters, `odd_sum` and `even_sum` for the number of odd sums ... | 19 | Given an array of integers `arr`, return _the number of subarrays with an **odd** sum_.
Since the answer can be very large, return it modulo `109 + 7`.
**Example 1:**
**Input:** arr = \[1,3,5\]
**Output:** 4
**Explanation:** All subarrays are \[\[1\],\[1,3\],\[1,3,5\],\[3\],\[3,5\],\[5\]\]
All sub-arrays sum are \[1... | Bruteforce to find if one string is substring of another or use KMP algorithm. |
Python | O(n) time & O(1) space | prefix sum(detailed explanation) | number-of-sub-arrays-with-odd-sum | 0 | 1 | Keys:\n1) odd number - even numer = odd number(e.g., 9 - 4 = 5)\n2) even number - odd number = odd number(e.g., 8 - 3 = 5)\n3) prefix sum: to obtain the sum of subarray `arr[i + 1, j]`, we can use prefix sum by `sum[0, j] - sum[0, i]`.\n\nIdea:\n1) Keep two counters, `odd_sum` and `even_sum` for the number of odd sums ... | 19 | You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**... | Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa. |
Python 3 | Easy to understand | Basic | number-of-sub-arrays-with-odd-sum | 0 | 1 | ```\nclass Solution:\n def numOfSubarrays(self, arr: List[int]) -> int:\n ans = 0\n even = 1 #(sum zero before array start)\n odd = 0\n rsum = 0\n for i in range(len(arr)):\n rsum += arr[i]\n if rsum % 2 == 1:\n ans += even\n odd ... | 4 | Given an array of integers `arr`, return _the number of subarrays with an **odd** sum_.
Since the answer can be very large, return it modulo `109 + 7`.
**Example 1:**
**Input:** arr = \[1,3,5\]
**Output:** 4
**Explanation:** All subarrays are \[\[1\],\[1,3\],\[1,3,5\],\[3\],\[3,5\],\[5\]\]
All sub-arrays sum are \[1... | Bruteforce to find if one string is substring of another or use KMP algorithm. |
Python 3 | Easy to understand | Basic | number-of-sub-arrays-with-odd-sum | 0 | 1 | ```\nclass Solution:\n def numOfSubarrays(self, arr: List[int]) -> int:\n ans = 0\n even = 1 #(sum zero before array start)\n odd = 0\n rsum = 0\n for i in range(len(arr)):\n rsum += arr[i]\n if rsum % 2 == 1:\n ans += even\n odd ... | 4 | You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**... | Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa. |
[Java/Python 3] Count odds and compute, w/ brief explanation and analysis. | number-of-sub-arrays-with-odd-sum | 1 | 1 | 1. Count the number of the odd prefix sum `oddCount`, then the number of the even prefix sum is `arr.length - oddCount`\n2. For each odd prefix sum, its difference between any even prefix sum is also odd subarray sum; \n\n e.g., `arr = [1,2,3,4,5,6,7]`, for a given odd prefix sum `arr[0] + arr[1] = 3`, the difference ... | 11 | Given an array of integers `arr`, return _the number of subarrays with an **odd** sum_.
Since the answer can be very large, return it modulo `109 + 7`.
**Example 1:**
**Input:** arr = \[1,3,5\]
**Output:** 4
**Explanation:** All subarrays are \[\[1\],\[1,3\],\[1,3,5\],\[3\],\[3,5\],\[5\]\]
All sub-arrays sum are \[1... | Bruteforce to find if one string is substring of another or use KMP algorithm. |
[Java/Python 3] Count odds and compute, w/ brief explanation and analysis. | number-of-sub-arrays-with-odd-sum | 1 | 1 | 1. Count the number of the odd prefix sum `oddCount`, then the number of the even prefix sum is `arr.length - oddCount`\n2. For each odd prefix sum, its difference between any even prefix sum is also odd subarray sum; \n\n e.g., `arr = [1,2,3,4,5,6,7]`, for a given odd prefix sum `arr[0] + arr[1] = 3`, the difference ... | 11 | You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**... | Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa. |
Python | DP | Elementary math | [even=i-odd]| Commented | number-of-sub-arrays-with-odd-sum | 0 | 1 | Simple math:\n* even + even = even\n* odd + odd = even\n* odd + even = **odd** (*the only way to get an odd number*)\n\n```dp[i]``` indicates the number of subarrays ending with ```arr[i]``` that summed to an odd number, therefore the number of subarrays ending with ```arr[i]``` that summed to an even number would be `... | 5 | Given an array of integers `arr`, return _the number of subarrays with an **odd** sum_.
Since the answer can be very large, return it modulo `109 + 7`.
**Example 1:**
**Input:** arr = \[1,3,5\]
**Output:** 4
**Explanation:** All subarrays are \[\[1\],\[1,3\],\[1,3,5\],\[3\],\[3,5\],\[5\]\]
All sub-arrays sum are \[1... | Bruteforce to find if one string is substring of another or use KMP algorithm. |
Python | DP | Elementary math | [even=i-odd]| Commented | number-of-sub-arrays-with-odd-sum | 0 | 1 | Simple math:\n* even + even = even\n* odd + odd = even\n* odd + even = **odd** (*the only way to get an odd number*)\n\n```dp[i]``` indicates the number of subarrays ending with ```arr[i]``` that summed to an odd number, therefore the number of subarrays ending with ```arr[i]``` that summed to an even number would be `... | 5 | You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**... | Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa. |
99.7% Python 3 solution with 17 lines, no search, explained | number-of-good-ways-to-split-a-string | 0 | 1 | The following solution yields a 99.64% runtime. For the explanation see below!\n\n```\nclass Solution:\n def numSplits(self, s: str) -> int:\n\t\t# this is not neccessary, but speeds things up\n length = len(s)\n if length == 1: # never splittable\n return 0\n elif length == 2: # al... | 80 | You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.
Return _the number of **good splits** you can make ... | Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning. |
99.7% Python 3 solution with 17 lines, no search, explained | number-of-good-ways-to-split-a-string | 0 | 1 | The following solution yields a 99.64% runtime. For the explanation see below!\n\n```\nclass Solution:\n def numSplits(self, s: str) -> int:\n\t\t# this is not neccessary, but speeds things up\n length = len(s)\n if length == 1: # never splittable\n return 0\n elif length == 2: # al... | 80 | Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.
The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:
* The rank is an integer starting from `1`.
*... | Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index. |
Python O(n) | number-of-good-ways-to-split-a-string | 0 | 1 | ```\n# TimeComplexity O(n)\n# MemoryComplexity O(n)\n\nclass Solution:\n def numSplits(self, s: str) -> int:\n if not s: return 0\n total = 0\n \n # prefix unique count\n prefix_count = [0]*len(s)\n unique = set()\n for i in range(len(s)):\n unique.add(s[i]... | 8 | You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.
Return _the number of **good splits** you can make ... | Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning. |
Python O(n) | number-of-good-ways-to-split-a-string | 0 | 1 | ```\n# TimeComplexity O(n)\n# MemoryComplexity O(n)\n\nclass Solution:\n def numSplits(self, s: str) -> int:\n if not s: return 0\n total = 0\n \n # prefix unique count\n prefix_count = [0]*len(s)\n unique = set()\n for i in range(len(s)):\n unique.add(s[i]... | 8 | Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.
The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:
* The rank is an integer starting from `1`.
*... | Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index. |
✔️ [Python] | Simple | Clean approach | beat 95% Easy T: O(N) | number-of-good-ways-to-split-a-string | 0 | 1 | ```\nfrom collections import defaultdict\n\nclass Solution:\n def numSplits(self, s: str) -> int:\n leftD, rightD = defaultdict(int), defaultdict(int)\n ans = 0\n for val in s: rightD[val]+=1\n leftUnique, rightUnique = 0, len(rightD.keys())\n for val in s:\n if leftD.g... | 1 | You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.
Return _the number of **good splits** you can make ... | Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning. |
✔️ [Python] | Simple | Clean approach | beat 95% Easy T: O(N) | number-of-good-ways-to-split-a-string | 0 | 1 | ```\nfrom collections import defaultdict\n\nclass Solution:\n def numSplits(self, s: str) -> int:\n leftD, rightD = defaultdict(int), defaultdict(int)\n ans = 0\n for val in s: rightD[val]+=1\n leftUnique, rightUnique = 0, len(rightD.keys())\n for val in s:\n if leftD.g... | 1 | Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.
The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:
* The rank is an integer starting from `1`.
*... | Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index. |
Very simple python 🐍 solution using counter Dict with comments | number-of-good-ways-to-split-a-string | 0 | 1 | ```\nimport collections\nclass Solution:\n def numSplits(self, s: str) -> int:\n myS1=collections.Counter() #s1 is now empty\n myS2=collections.Counter(s) #s2 is now has all string \n ways=0 #when len of myS1= len of myS2 --> ways+=1\n\n for letter in s: \n myS1[letter]+=1\n... | 20 | You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.
Return _the number of **good splits** you can make ... | Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning. |
Very simple python 🐍 solution using counter Dict with comments | number-of-good-ways-to-split-a-string | 0 | 1 | ```\nimport collections\nclass Solution:\n def numSplits(self, s: str) -> int:\n myS1=collections.Counter() #s1 is now empty\n myS2=collections.Counter(s) #s2 is now has all string \n ways=0 #when len of myS1= len of myS2 --> ways+=1\n\n for letter in s: \n myS1[letter]+=1\n... | 20 | Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.
The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:
* The rank is an integer starting from `1`.
*... | Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index. |
Two Hashset Approach | number-of-good-ways-to-split-a-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thought that appears is the usage of suffix and prefix arrays. We can use hashset to maintain unique characters and store the counts in left and right arrays.\n\n# Approach\n<!-- Describe your approach to solving the problem. --... | 1 | You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.
Return _the number of **good splits** you can make ... | Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning. |
Two Hashset Approach | number-of-good-ways-to-split-a-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thought that appears is the usage of suffix and prefix arrays. We can use hashset to maintain unique characters and store the counts in left and right arrays.\n\n# Approach\n<!-- Describe your approach to solving the problem. --... | 1 | Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.
The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:
* The rank is an integer starting from `1`.
*... | Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index. |
Python3 | Solved Using Hashmap and Set | O(N) Time and O(N) Space | number-of-good-ways-to-split-a-string | 0 | 1 | # Intuition\nBasically, I thought of performing linear scan first to obtain frequency map for the entire string. Then, I thought of utilizing a set instance to keep track of number of distinct chars of currently built up left substring and use another hashmap instance to keep track of the current right substring (s.t. ... | 1 | You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.
Return _the number of **good splits** you can make ... | Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning. |
Python3 | Solved Using Hashmap and Set | O(N) Time and O(N) Space | number-of-good-ways-to-split-a-string | 0 | 1 | # Intuition\nBasically, I thought of performing linear scan first to obtain frequency map for the entire string. Then, I thought of utilizing a set instance to keep track of number of distinct chars of currently built up left substring and use another hashmap instance to keep track of the current right substring (s.t. ... | 1 | Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.
The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:
* The rank is an integer starting from `1`.
*... | Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index. |
Simple solution/intuition in TypeScript / Python | minimum-number-of-increments-on-subarrays-to-form-a-target-array | 0 | 1 | # Intuition\nHere we have:\n- list of integers `target`\n- our goal is to recreate `target` from `initial` list of integers\n\nAn `initial` list consists with `0`-s. It has **the same** structure as in `target`.\n\nThe key to solve this problem is to think about **neighbours** and how they\'re related to each other.\n\... | 1 | You are given an integer array `target`. You have an integer array `initial` of the same size as `target` with all elements initially zeros.
In one operation you can choose **any** subarray from `initial` and increment each value by one.
Return _the minimum number of operations to form a_ `target` _array from_ `initi... | Search the string for all the occurrences of the character '&'. For every '&' check if it matches an HTML entity by checking the ';' character and if entity found replace it in the answer. |
Python 3 | Simplest one pass solution. | minimum-number-of-increments-on-subarrays-to-form-a-target-array | 0 | 1 | Check with previous number if it is higher then add the difference otherwise not\n\n```\nclass Solution:\n def minNumberOperations(self, target: List[int]) -> int:\n prev_num = 0\n steps = 0\n for val in target:\n steps += val-prev_num if val > prev_num else 0\n prev_num = ... | 7 | You are given an integer array `target`. You have an integer array `initial` of the same size as `target` with all elements initially zeros.
In one operation you can choose **any** subarray from `initial` and increment each value by one.
Return _the minimum number of operations to form a_ `target` _array from_ `initi... | Search the string for all the occurrences of the character '&'. For every '&' check if it matches an HTML entity by checking the ';' character and if entity found replace it in the answer. |
Pandas vs SQL | Elegant & Short | All 30 Days of Pandas solutions ✅ | patients-with-a-condition | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef find_patients(patients: pd.DataFrame) -> pd.DataFrame:\n return patients[\n patients[\'conditions\'].str.contains(r\'(^DIAB1)|( DIAB1)\')\n ]\n```\n```SQL []\nSELECT *\n FROM Patients\n WHERE conditions RE... | 9 | Design a queue that supports `push` and `pop` operations in the front, middle, and back.
Implement the `FrontMiddleBack` class:
* `FrontMiddleBack()` Initializes the queue.
* `void pushFront(int val)` Adds `val` to the **front** of the queue.
* `void pushMiddle(int val)` Adds `val` to the **middle** of the queu... | null |
😃 Easy Solution || Pandas 🔥🔥 | patients-with-a-condition | 0 | 1 | ```\nimport pandas as pd\n\ndef find_patients(patients: pd.DataFrame) -> pd.DataFrame:\n df = patients[patients[\'conditions\'].str.contains(r\'(^DIAB1)|( DIAB1)\')]\n return df\n \n``` | 1 | Design a queue that supports `push` and `pop` operations in the front, middle, and back.
Implement the `FrontMiddleBack` class:
* `FrontMiddleBack()` Initializes the queue.
* `void pushFront(int val)` Adds `val` to the **front** of the queue.
* `void pushMiddle(int val)` Adds `val` to the **middle** of the queu... | null |
Pandas - Simple solution | patients-with-a-condition | 0 | 1 | # Approach\n1. Retrieve the content of the `conditions` field.\n2. Create a function to split each `conditions` by a space `\' \'` and check whether it starts with `DIAB1` or not.\n\n# Code\n```\nimport pandas as pd\n\ndef find_patients(patients: pd.DataFrame) -> pd.DataFrame:\n return patients[patients[\'conditions... | 5 | Design a queue that supports `push` and `pop` operations in the front, middle, and back.
Implement the `FrontMiddleBack` class:
* `FrontMiddleBack()` Initializes the queue.
* `void pushFront(int val)` Adds `val` to the **front** of the queue.
* `void pushMiddle(int val)` Adds `val` to the **middle** of the queu... | null |
Simple Python3 Solution || beats 90% ||🤖💻🧑💻|| upvote please | shuffle-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def restoreString(self, s: str, indices: List[int]) -> str:\n outcome=""\n for i in range(len(s)):\n outcome=outcome+s[indices.index(i)]\n return outcome\n\n \n``` | 7 | You are given a string `s` and an integer array `indices` of the **same length**. The string `s` will be shuffled such that the character at the `ith` position moves to `indices[i]` in the shuffled string.
Return _the shuffled string_.
**Example 1:**
**Input:** s = "codeleet ", `indices` = \[4,5,6,7,0,2,1,3\]
**Out... | Use greedy approach. For each kid check if candies[i] + extraCandies ≥ maximum in Candies[i]. |
Solution of shuffle string problem | shuffle-string | 0 | 1 | # Approach\n- Solved using `zip()` function\n- Python\u2019s `zip()` function creates an iterator that will aggregate elements from two or more iterables\n\n# Complexity\n- Time complexity:\n$$O(n)$$ - as zip() function takes linear time\n\n- Space complexity:\n$$O(n)$$ - as we use extra space for answer\n\n# Code\n```... | 4 | You are given a string `s` and an integer array `indices` of the **same length**. The string `s` will be shuffled such that the character at the `ith` position moves to `indices[i]` in the shuffled string.
Return _the shuffled string_.
**Example 1:**
**Input:** s = "codeleet ", `indices` = \[4,5,6,7,0,2,1,3\]
**Out... | Use greedy approach. For each kid check if candies[i] + extraCandies ≥ maximum in Candies[i]. |
String Restoration from Indices | shuffle-string | 0 | 1 | This code defines a class Solution with a method restoreString that is used to restore the original string from a given string s and a list of indices indices. The indices list indicates the order in which characters of the original string should be rearranged.\n\nHere\'s a breakdown of the code:\n# Intuition\n<!-- Des... | 3 | You are given a string `s` and an integer array `indices` of the **same length**. The string `s` will be shuffled such that the character at the `ith` position moves to `indices[i]` in the shuffled string.
Return _the shuffled string_.
**Example 1:**
**Input:** s = "codeleet ", `indices` = \[4,5,6,7,0,2,1,3\]
**Out... | Use greedy approach. For each kid check if candies[i] + extraCandies ≥ maximum in Candies[i]. |
Python 3 lines easy O(n) | shuffle-string | 0 | 1 | Using a list to store all the chars and joining it to return the answer string. \n```\nclass Solution:\n def restoreString(self, s: str, indices: List[int]) -> str:\n res = [\'\'] * len(s)\n for index, char in enumerate(s):\n res[indices[index]] = char\n return "".join(res) | 55 | You are given a string `s` and an integer array `indices` of the **same length**. The string `s` will be shuffled such that the character at the `ith` position moves to `indices[i]` in the shuffled string.
Return _the shuffled string_.
**Example 1:**
**Input:** s = "codeleet ", `indices` = \[4,5,6,7,0,2,1,3\]
**Out... | Use greedy approach. For each kid check if candies[i] + extraCandies ≥ maximum in Candies[i]. |
Simple O(1) Space Python Solution ✅ | minimum-suffix-flips | 0 | 1 | # Intuition\nWe want to find the minimum number of flips required to make all elements of the given binary string \'target\' the same.\n\n# Approach\nWe initialize a counter \'count\' to keep track of the number of flips required. We also initialize a variable \'last\' to store the last encountered character, initially... | 2 | You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`.
In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the **inclusive** range `[i, n - 1]`. Flip... | We need to get the max and min value after changing num and the answer is max - min. Use brute force, try all possible changes and keep the minimum and maximum values. |
Simple O(1) Space Python Solution ✅ | minimum-suffix-flips | 0 | 1 | # Intuition\nWe want to find the minimum number of flips required to make all elements of the given binary string \'target\' the same.\n\n# Approach\nWe initialize a counter \'count\' to keep track of the number of flips required. We also initialize a variable \'last\' to store the last encountered character, initially... | 2 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
[Python3] 1-line | minimum-suffix-flips | 0 | 1 | Algo: \n\nTo abstract this problem in math terms, the purpose of it is to simply convert a string composed of `0`\'s and `1`\'s to all `0`\'s using a predefined flip operation that flips everything from a given position to the end. As a result, at any step, one could focus on the left-most `1`. By fliping it, a desirab... | 19 | You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`.
In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the **inclusive** range `[i, n - 1]`. Flip... | We need to get the max and min value after changing num and the answer is max - min. Use brute force, try all possible changes and keep the minimum and maximum values. |
[Python3] 1-line | minimum-suffix-flips | 0 | 1 | Algo: \n\nTo abstract this problem in math terms, the purpose of it is to simply convert a string composed of `0`\'s and `1`\'s to all `0`\'s using a predefined flip operation that flips everything from a given position to the end. As a result, at any step, one could focus on the left-most `1`. By fliping it, a desirab... | 19 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
✅ [Python/C++] O(N) using flips parity | minimum-suffix-flips | 0 | 1 | The strategy here is to keep track of parity of the already made flips. The code is self-explanatory.\n\n```python []\nclass Solution:\n def minFlips(self, target: str) -> int:\n \n flips = 0\n for b in target:\n if flips % 2 == 1 - int(b):\n flips += 1\n\n retur... | 1 | You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`.
In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the **inclusive** range `[i, n - 1]`. Flip... | We need to get the max and min value after changing num and the answer is max - min. Use brute force, try all possible changes and keep the minimum and maximum values. |
✅ [Python/C++] O(N) using flips parity | minimum-suffix-flips | 0 | 1 | The strategy here is to keep track of parity of the already made flips. The code is self-explanatory.\n\n```python []\nclass Solution:\n def minFlips(self, target: str) -> int:\n \n flips = 0\n for b in target:\n if flips % 2 == 1 - int(b):\n flips += 1\n\n retur... | 1 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Python Solution in 3 lines || Easy to understand | minimum-suffix-flips | 0 | 1 | ```\nclass Solution:\n def minFlips(self, target: str) -> int:\n\t\t# to keep counter of number of flip bits\n flips = 0\n\t\t\n\t\t# 0 will become 1 and 1 will become 0 after each move\n\t\t# but the substring before current index in unchanged so traverse from left to right\n for letter in target:\n\t... | 3 | You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`.
In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the **inclusive** range `[i, n - 1]`. Flip... | We need to get the max and min value after changing num and the answer is max - min. Use brute force, try all possible changes and keep the minimum and maximum values. |
Python Solution in 3 lines || Easy to understand | minimum-suffix-flips | 0 | 1 | ```\nclass Solution:\n def minFlips(self, target: str) -> int:\n\t\t# to keep counter of number of flip bits\n flips = 0\n\t\t\n\t\t# 0 will become 1 and 1 will become 0 after each move\n\t\t# but the substring before current index in unchanged so traverse from left to right\n for letter in target:\n\t... | 3 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
73% O(n) TC and 70% O(1) SC easy python solution | minimum-suffix-flips | 0 | 1 | ```\ndef minFlips(self, target: str) -> int:\n\tn = len(target)\n\tans = 0\n\tfor i in range(n):\n\t\tif (target[i] == "0" and ans%2) or (target[i] == "1" and ans%2 == 0):\n\t\t\tans += 1\n\treturn ans\n``` | 1 | You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`.
In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the **inclusive** range `[i, n - 1]`. Flip... | We need to get the max and min value after changing num and the answer is max - min. Use brute force, try all possible changes and keep the minimum and maximum values. |
73% O(n) TC and 70% O(1) SC easy python solution | minimum-suffix-flips | 0 | 1 | ```\ndef minFlips(self, target: str) -> int:\n\tn = len(target)\n\tans = 0\n\tfor i in range(n):\n\t\tif (target[i] == "0" and ans%2) or (target[i] == "1" and ans%2 == 0):\n\t\t\tans += 1\n\treturn ans\n``` | 1 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Python3 O(N) solution with constant memory (98.27% Runtime) | minimum-suffix-flips | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nCount how many times "bit" change occurs from the beginning of the array\n\n# Approach\n<!-- Describe your approach to sol... | 0 | You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`.
In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the **inclusive** range `[i, n - 1]`. Flip... | We need to get the max and min value after changing num and the answer is max - min. Use brute force, try all possible changes and keep the minimum and maximum values. |
Python3 O(N) solution with constant memory (98.27% Runtime) | minimum-suffix-flips | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nCount how many times "bit" change occurs from the beginning of the array\n\n# Approach\n<!-- Describe your approach to sol... | 0 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Simple Python Solution Beats 91% | minimum-suffix-flips | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimple solution to just increase count when most recent value is different\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)$$ -->\nO(... | 0 | You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`.
In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the **inclusive** range `[i, n - 1]`. Flip... | We need to get the max and min value after changing num and the answer is max - min. Use brute force, try all possible changes and keep the minimum and maximum values. |
Simple Python Solution Beats 91% | minimum-suffix-flips | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimple solution to just increase count when most recent value is different\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)$$ -->\nO(... | 0 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Python one-liner | minimum-suffix-flips | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRemove leftmost zeroes, as they don\'t contribute to the final result, then count the number of groups of consecutive zeroes and ones.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n... | 0 | You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`.
In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the **inclusive** range `[i, n - 1]`. Flip... | We need to get the max and min value after changing num and the answer is max - min. Use brute force, try all possible changes and keep the minimum and maximum values. |
Python one-liner | minimum-suffix-flips | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRemove leftmost zeroes, as they don\'t contribute to the final result, then count the number of groups of consecutive zeroes and ones.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n... | 0 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Python solution Fast with explanation | number-of-good-leaf-nodes-pairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought on how to solve this problem is to use a depth-first search (DFS) approach to traverse through the binary tree. For each node, we need to find all its possible distances from its descendants and calculate the number of pa... | 7 | You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`.
Return _the number of good leaf node pairs_ in the tree.
**Example 1:**
**Input:** r... | Sort both strings and then check if one of them can break the other. |
Python solution Fast with explanation | number-of-good-leaf-nodes-pairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought on how to solve this problem is to use a depth-first search (DFS) approach to traverse through the binary tree. For each node, we need to find all its possible distances from its descendants and calculate the number of pa... | 7 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
[Python] Convert to graph + BFS | number-of-good-leaf-nodes-pairs | 0 | 1 | ```\nclass Solution:\n def countPairs(self, root: TreeNode, distance: int) -> int:\n graph = collections.defaultdict(list)\n \n def dfs(node, par = None):\n if node:\n graph[node].append(par)\n graph[par].append(node)\n dfs(node.left, node)... | 28 | You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`.
Return _the number of good leaf node pairs_ in the tree.
**Example 1:**
**Input:** r... | Sort both strings and then check if one of them can break the other. |
[Python] Convert to graph + BFS | number-of-good-leaf-nodes-pairs | 0 | 1 | ```\nclass Solution:\n def countPairs(self, root: TreeNode, distance: int) -> int:\n graph = collections.defaultdict(list)\n \n def dfs(node, par = None):\n if node:\n graph[node].append(par)\n graph[par].append(node)\n dfs(node.left, node)... | 28 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
Easy Python Solution with Diagram Explanation | number-of-good-leaf-nodes-pairs | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n\nThe image above gives some idea about the approach. We will traverse the tree using dfs. When we reach the leaf node, we will retur... | 2 | You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`.
Return _the number of good leaf node pairs_ in the tree.
**Example 1:**
**Input:** r... | Sort both strings and then check if one of them can break the other. |
Easy Python Solution with Diagram Explanation | number-of-good-leaf-nodes-pairs | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n\nThe image above gives some idea about the approach. We will traverse the tree using dfs. When we reach the leaf node, we will retur... | 2 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
Beats 99.35% using recursion in Python | number-of-good-leaf-nodes-pairs | 0 | 1 | The idea is to use recursion for each node.\nIn the `rec(node)` function below, it returns the the number of the leaves from that node for each height. For example, `{1: 1, 2: 3}` means that the node has one leaf with the height 1 and three leaves with the height 2.\nThe point is that if you connect two leaves, there i... | 7 | You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`.
Return _the number of good leaf node pairs_ in the tree.
**Example 1:**
**Input:** r... | Sort both strings and then check if one of them can break the other. |
Beats 99.35% using recursion in Python | number-of-good-leaf-nodes-pairs | 0 | 1 | The idea is to use recursion for each node.\nIn the `rec(node)` function below, it returns the the number of the leaves from that node for each height. For example, `{1: 1, 2: 3}` means that the node has one leaf with the height 1 and three leaves with the height 2.\nThe point is that if you connect two leaves, there i... | 7 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
50% TC and 80% SC easy python solution | number-of-good-leaf-nodes-pairs | 0 | 1 | ```\ndef countPairs(self, root: TreeNode, distance: int) -> int:\n\tans = [0]\n\tlru_cache(None)\n\tdef dfs(node):\n\t\tif(not node):\n\t\t\treturn []\n\t\tif not(node.left or node.right):\n\t\t\treturn [1]\n\t\tl = dfs(node.left)\n\t\tr = dfs(node.right)\n\t\tfor i in l:\n\t\t\tfor j in r:\n\t\t\t\tif(i+j <= distance)... | 4 | You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`.
Return _the number of good leaf node pairs_ in the tree.
**Example 1:**
**Input:** r... | Sort both strings and then check if one of them can break the other. |
50% TC and 80% SC easy python solution | number-of-good-leaf-nodes-pairs | 0 | 1 | ```\ndef countPairs(self, root: TreeNode, distance: int) -> int:\n\tans = [0]\n\tlru_cache(None)\n\tdef dfs(node):\n\t\tif(not node):\n\t\t\treturn []\n\t\tif not(node.left or node.right):\n\t\t\treturn [1]\n\t\tl = dfs(node.left)\n\t\tr = dfs(node.right)\n\t\tfor i in l:\n\t\t\tfor j in r:\n\t\t\t\tif(i+j <= distance)... | 4 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
SIMPLEST PYTHON SOLUTION | string-compression-ii | 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)$$ --... | 1 | [Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compr... | Dynamic programming + bitmask. dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1. |
SIMPLEST PYTHON SOLUTION | string-compression-ii | 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)$$ --... | 1 | Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the ... | Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range. |
python3 | string-compression-ii | 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# We define f(i, curr_run_ch, run_length, nb_dels_remain) to return \n # the minimum, additional, number of characters it will cost to run-length \n # co... | 1 | [Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compr... | Dynamic programming + bitmask. dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1. |
python3 | string-compression-ii | 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# We define f(i, curr_run_ch, run_length, nb_dels_remain) to return \n # the minimum, additional, number of characters it will cost to run-length \n # co... | 1 | Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the ... | Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range. |
Python with Comments 💚 | string-compression-ii | 0 | 1 | ```\nclass Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n #traverse the string\n #keep track of the status of delete or not delete current character\n #the status includes current index, number of delete, the previous character, and the runing length of previous ch... | 4 | [Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compr... | Dynamic programming + bitmask. dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1. |
Python with Comments 💚 | string-compression-ii | 0 | 1 | ```\nclass Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n #traverse the string\n #keep track of the status of delete or not delete current character\n #the status includes current index, number of delete, the previous character, and the runing length of previous ch... | 4 | Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the ... | Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range. |
[python] Simple clear DP solution | string-compression-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTruly a hard problem.\nThe key point is to think of:\n(1) The definition of dp[i][j] is: for the first i chars, the shortest final length if j chars are deleted.\n(2) The transfer relationship is:\na. if s[i - 1] is deleted, then dp[i][j]... | 2 | [Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compr... | Dynamic programming + bitmask. dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1. |
[python] Simple clear DP solution | string-compression-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTruly a hard problem.\nThe key point is to think of:\n(1) The definition of dp[i][j] is: for the first i chars, the shortest final length if j chars are deleted.\n(2) The transfer relationship is:\na. if s[i - 1] is deleted, then dp[i][j]... | 2 | Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the ... | Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range. |
Time(78%) Memory(99.9%), You can remove triple-for-statement with itertool. | count-good-triplets | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou can use itertool.\nAnd there are awesome $$O(nlogn)$$ solution using fenwick tree\nLook at the other solution down below\n# Complexity\n- Time complexity: $$O(N^3)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space co... | 1 | Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]|... | keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak". |
Time(78%) Memory(99.9%), You can remove triple-for-statement with itertool. | count-good-triplets | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou can use itertool.\nAnd there are awesome $$O(nlogn)$$ solution using fenwick tree\nLook at the other solution down below\n# Complexity\n- Time complexity: $$O(N^3)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space co... | 1 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
Naive Approach || Count Good Triplets | count-good-triplets | 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)$$ --... | 1 | Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]|... | keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak". |
Naive Approach || Count Good Triplets | count-good-triplets | 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)$$ --... | 1 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
Pyhton3 solution Triple nested loop | count-good-triplets | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought on how to solve this problem is to use a triple nested loop. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo solve this problem, I will use a triple nested loop. The outer loop will iterate throu... | 1 | Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]|... | keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak". |
Pyhton3 solution Triple nested loop | count-good-triplets | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought on how to solve this problem is to use a triple nested loop. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo solve this problem, I will use a triple nested loop. The outer loop will iterate throu... | 1 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
Obvious Brute force that gets accepted | count-good-triplets | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def countGoodTriplets(self, A: List[int], a: int, b: int, c: int) -> int:\n n = len(A)\n cnt = 0\n for i in range(n):\n for j in range(i+1, n):\n for k in range(j+1, n):\n if abs(A[i]-A[j]) <= a and abs(A[k]-A[j]) <=... | 2 | Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]|... | keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak". |
Obvious Brute force that gets accepted | count-good-triplets | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def countGoodTriplets(self, A: List[int], a: int, b: int, c: int) -> int:\n n = len(A)\n cnt = 0\n for i in range(n):\n for j in range(i+1, n):\n for k in range(j+1, n):\n if abs(A[i]-A[j]) <= a and abs(A[k]-A[j]) <=... | 2 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
[PYTHON] Self Explanatory Simple Code | count-good-triplets | 0 | 1 | Runtime: 645 ms, faster than 80.95% of Python3 online submissions for Count Good Triplets.\nMemory Usage: 14 MB, less than 16.30% of Python3 online submissions for Count Good Triplets.\n\n```class Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n co = 0\n for i i... | 3 | Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]|... | keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak". |
[PYTHON] Self Explanatory Simple Code | count-good-triplets | 0 | 1 | Runtime: 645 ms, faster than 80.95% of Python3 online submissions for Count Good Triplets.\nMemory Usage: 14 MB, less than 16.30% of Python3 online submissions for Count Good Triplets.\n\n```class Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n co = 0\n for i i... | 3 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
simple brute force ||python solution | count-good-triplets | 0 | 1 | Time Complexcity O(N^3)\nSpace complexcity O(1)\n```\nclass Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n count=0\n n=len(arr)\n for i in range(n-2):\n for j in range(i+1,n-1):\n for k in range(j+1,n):\n if ... | 1 | Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]|... | keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak". |
simple brute force ||python solution | count-good-triplets | 0 | 1 | Time Complexcity O(N^3)\nSpace complexcity O(1)\n```\nclass Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n count=0\n n=len(arr)\n for i in range(n-2):\n for j in range(i+1,n-1):\n for k in range(j+1,n):\n if ... | 1 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
Python sol with generator and loops | count-good-triplets | 0 | 1 | Python sol with generator and loops\n\n---\n\n**Implementation** by nested loops:\n\n```\nclass Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n \n size = len(arr)\n \n good_count = 0\n \n for i in range(size-2):\n for j in... | 28 | Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]|... | keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak". |
Python sol with generator and loops | count-good-triplets | 0 | 1 | Python sol with generator and loops\n\n---\n\n**Implementation** by nested loops:\n\n```\nclass Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n \n size = len(arr)\n \n good_count = 0\n \n for i in range(size-2):\n for j in... | 28 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
[Python] Roughly O(n log n) with Fenwick Tree | count-good-triplets | 0 | 1 | This is merely a python spin-off of 2 great solutions.\n1. [Bucket sort ](https://leetcode.com/problems/count-good-triplets/discuss/769821/Java.-O(n).-Well-it-is-really-O(1000-*-n))\n2. [Fenwick tree](https://leetcode.com/problems/count-good-triplets/discuss/951019/Java-Roughly-O(n-log-n)-with-Fenwick-Tree)\n\nI kid yo... | 8 | Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]|... | keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak". |
[Python] Roughly O(n log n) with Fenwick Tree | count-good-triplets | 0 | 1 | This is merely a python spin-off of 2 great solutions.\n1. [Bucket sort ](https://leetcode.com/problems/count-good-triplets/discuss/769821/Java.-O(n).-Well-it-is-really-O(1000-*-n))\n2. [Fenwick tree](https://leetcode.com/problems/count-good-triplets/discuss/951019/Java-Roughly-O(n-log-n)-with-Fenwick-Tree)\n\nI kid yo... | 8 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
C++/Python 1 loop vs deque||30ms Beats 100% | find-the-winner-of-an-array-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf k>=len(arr) return max(arr)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOtherwise use a loop to proceed.\n\n`getWinner` finds the `winner` in an array by iterating through it and keeping track of the maximum v... | 11 | Given an integer array `arr` of **distinct** integers and an integer `k`.
A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to t... | Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b. Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k cha... |
C++/Python 1 loop vs deque||30ms Beats 100% | find-the-winner-of-an-array-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf k>=len(arr) return max(arr)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOtherwise use a loop to proceed.\n\n`getWinner` finds the `winner` in an array by iterating through it and keeping track of the maximum v... | 11 | Two strings are considered **close** if you can attain one from the other using the following operations:
* Operation 1: Swap any two **existing** characters.
* For example, `abcde -> aecdb`
* Operation 2: Transform **every** occurrence of one **existing** character into another **existing** character, and d... | If k ≥ arr.length return the max element of the array. If k < arr.length simulate the game until a number wins k consecutive games. |
🚀 96.74% || Simulation Game || Explained Intuition 🚀 | find-the-winner-of-an-array-game | 1 | 1 | # Problem Description\n\nGiven an array of distinct integers, `arr`, and an integer `k`. A game is played between the first **two** elements of the array, `arr[0]` and `arr[1]`. In each round, the **larger** integer remains at position `0`, while the smaller integer is **moved** to the **end** of the array. The game **... | 26 | Given an integer array `arr` of **distinct** integers and an integer `k`.
A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to t... | Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b. Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k cha... |
🚀 96.74% || Simulation Game || Explained Intuition 🚀 | find-the-winner-of-an-array-game | 1 | 1 | # Problem Description\n\nGiven an array of distinct integers, `arr`, and an integer `k`. A game is played between the first **two** elements of the array, `arr[0]` and `arr[1]`. In each round, the **larger** integer remains at position `0`, while the smaller integer is **moved** to the **end** of the array. The game **... | 26 | Two strings are considered **close** if you can attain one from the other using the following operations:
* Operation 1: Swap any two **existing** characters.
* For example, `abcde -> aecdb`
* Operation 2: Transform **every** occurrence of one **existing** character into another **existing** character, and d... | If k ≥ arr.length return the max element of the array. If k < arr.length simulate the game until a number wins k consecutive games. |
💯Faster✅💯 Lesser✅3 Methods🔥Simulation Approach🔥Dequeue🔥Two Pointer and Hashtable🔥LinkedList🔥 | find-the-winner-of-an-array-game | 1 | 1 | # \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share 4 ways to solve this question with detailed explanation of each approach:\n\n# Problem Description: \nWe are given an integer array arr containing distinct integers and an integer k. We need t... | 43 | Given an integer array `arr` of **distinct** integers and an integer `k`.
A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to t... | Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b. Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k cha... |
💯Faster✅💯 Lesser✅3 Methods🔥Simulation Approach🔥Dequeue🔥Two Pointer and Hashtable🔥LinkedList🔥 | find-the-winner-of-an-array-game | 1 | 1 | # \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share 4 ways to solve this question with detailed explanation of each approach:\n\n# Problem Description: \nWe are given an integer array arr containing distinct integers and an integer k. We need t... | 43 | Two strings are considered **close** if you can attain one from the other using the following operations:
* Operation 1: Swap any two **existing** characters.
* For example, `abcde -> aecdb`
* Operation 2: Transform **every** occurrence of one **existing** character into another **existing** character, and d... | If k ≥ arr.length return the max element of the array. If k < arr.length simulate the game until a number wins k consecutive games. |
✅ 98.37% O(n) Final Winner | find-the-winner-of-an-array-game | 1 | 1 | # Intuition\nWhen first approaching this problem, we might think about simulating the entire process: comparing numbers, moving the smaller one to the end, and keeping track of the number of consecutive wins. However, a closer inspection reveals a couple of key insights. Firstly, if the game needs only one win (i.e., $... | 103 | Given an integer array `arr` of **distinct** integers and an integer `k`.
A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to t... | Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b. Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k cha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.