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
SImple DP in python3
minimum-distance-to-type-a-word-using-two-fingers
0
1
# Code\n```\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n def place(l):\n a = ord(l) - ord(\'A\')\n return (a//6,a%6)\n places = {a:place(a) for a in \'ABCDEFGHIJKLMNOPQRSTUVWXYZ\'}\n def dist(a,b):\n if a == None:\n return 0\n ...
0
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex....
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
Solution
minimum-distance-to-type-a-word-using-two-fingers
1
1
```C++ []\nclass Solution {\npublic:\n int minimumDistance(string word) {\n int n = word.length();\n int* dp = new int[n];\n dp[0] = 0;\n for (int w=1; w<n; w++) {\n int d = dist(word, w, w-1);\n dp[w] = dp[w-1] + d;\n\n for (int j=0; j<w-1; j++) {\n ...
0
You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate. * For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `...
Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character.
Solution
minimum-distance-to-type-a-word-using-two-fingers
1
1
```C++ []\nclass Solution {\npublic:\n int minimumDistance(string word) {\n int n = word.length();\n int* dp = new int[n];\n dp[0] = 0;\n for (int w=1; w<n; w++) {\n int d = dist(word, w, w-1);\n dp[w] = dp[w-1] + d;\n\n for (int j=0; j<w-1; j++) {\n ...
0
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex....
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
Cache | Simple | Fast | Python Solution
minimum-distance-to-type-a-word-using-two-fingers
0
1
# Code\n```\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n def dist(pre,cur):\n if pre==None:\n return 0\n x1,y1 = divmod(ord(pre)-ord(\'A\'),6)\n x2,y2 = divmod(ord(cur)-ord(\'A\'),6)\n return abs(x1-x2) + abs(y1-y2)\n \n ...
0
You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate. * For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `...
Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character.
Cache | Simple | Fast | Python Solution
minimum-distance-to-type-a-word-using-two-fingers
0
1
# Code\n```\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n def dist(pre,cur):\n if pre==None:\n return 0\n x1,y1 = divmod(ord(pre)-ord(\'A\'),6)\n x2,y2 = divmod(ord(cur)-ord(\'A\'),6)\n return abs(x1-x2) + abs(y1-y2)\n \n ...
0
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex....
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
Python DP with Reused Storage -- Time O(27N) beats 100%; Space O(4 * 27 N) beats 94%
minimum-distance-to-type-a-word-using-two-fingers
0
1
# Code\n```\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n n = len(word)\n if n == 2: return 0\n dp01, dp02, dp11, dp12 = ([0] * 27 for _ in range(4))\n dm = divmod\n c = ord(word[-1]) - 0x41\n i = n - 1\n while i > 0:\n pc = ord(word[i-1...
0
You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate. * For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `...
Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character.
Python DP with Reused Storage -- Time O(27N) beats 100%; Space O(4 * 27 N) beats 94%
minimum-distance-to-type-a-word-using-two-fingers
0
1
# Code\n```\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n n = len(word)\n if n == 2: return 0\n dp01, dp02, dp11, dp12 = ([0] * 27 for _ in range(4))\n dm = divmod\n c = ord(word[-1]) - 0x41\n i = n - 1\n while i > 0:\n pc = ord(word[i-1...
0
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex....
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
Python (Simple DP)
minimum-distance-to-type-a-word-using-two-fingers
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 have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate. * For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `...
Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character.
Python (Simple DP)
minimum-distance-to-type-a-word-using-two-fingers
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 an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex....
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
Easy Python Solution
maximum-69-number
0
1
# Complexity\nThe current complexity is $O(n^2)$ because of the for loop and the max function, but it can be brought done to $O(n)$ if we replace max with normal if condition to check if m<temp: m=temp\n# Code\n```\nclass Solution:\n def maximum69Number (self, num: int) -> int:\n m=num\n s=(str(num))\n...
2
You are given a positive integer `num` consisting only of digits `6` and `9`. Return _the maximum number you can get by changing **at most** one digit (_`6` _becomes_ `9`_, and_ `9` _becomes_ `6`_)_. **Example 1:** **Input:** num = 9669 **Output:** 9969 **Explanation:** Changing the first digit results in 6669. Cha...
null
Easy Python Solution
maximum-69-number
0
1
# Complexity\nThe current complexity is $O(n^2)$ because of the for loop and the max function, but it can be brought done to $O(n)$ if we replace max with normal if condition to check if m<temp: m=temp\n# Code\n```\nclass Solution:\n def maximum69Number (self, num: int) -> int:\n m=num\n s=(str(num))\n...
2
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good*...
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
Not a obtained solution
maximum-69-number
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
You are given a positive integer `num` consisting only of digits `6` and `9`. Return _the maximum number you can get by changing **at most** one digit (_`6` _becomes_ `9`_, and_ `9` _becomes_ `6`_)_. **Example 1:** **Input:** num = 9669 **Output:** 9969 **Explanation:** Changing the first digit results in 6669. Cha...
null
Not a obtained solution
maximum-69-number
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 a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good*...
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
Python Elegant & Short | No loops | 1 line
print-words-vertically
0
1
```\nfrom itertools import zip_longest\nfrom typing import Iterable\n\n\nclass Solution:\n def printVertically(self, s: str) -> Iterable[str]:\n return map(str.rstrip, map(\'\'.join, zip_longest(*s.split(), fillvalue=\' \')))\n\n```
1
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Exam...
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
Python Elegant & Short | No loops | 1 line
print-words-vertically
0
1
```\nfrom itertools import zip_longest\nfrom typing import Iterable\n\n\nclass Solution:\n def printVertically(self, s: str) -> Iterable[str]:\n return map(str.rstrip, map(\'\'.join, zip_longest(*s.split(), fillvalue=\' \')))\n\n```
1
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
Python simple solution (92.9% Faster)
print-words-vertically
0
1
\n\n# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n yo = s.split()\n max = 0\n for i in yo:\n if len(i)>max: max = len(i)\n m = {}\n for i in yo:\n for j in range(max):\n try:\n if j not in m:\...
1
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Exam...
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
Python simple solution (92.9% Faster)
print-words-vertically
0
1
\n\n# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n yo = s.split()\n max = 0\n for i in yo:\n if len(i)>max: max = len(i)\n m = {}\n for i in yo:\n for j in range(max):\n try:\n if j not in m:\...
1
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
Python 3 Zip solution
print-words-vertically
0
1
\n# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n a, b, words = [], [], s.split()\n max_length = len(max(words, key=len))\n for i in words:\n if len(i) < max_length:\n i = i + " " * (max_length - len(i)) \n a.append(i)\n ...
1
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Exam...
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
Python 3 Zip solution
print-words-vertically
0
1
\n# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n a, b, words = [], [], s.split()\n max_length = len(max(words, key=len))\n for i in words:\n if len(i) < max_length:\n i = i + " " * (max_length - len(i)) \n a.append(i)\n ...
1
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
Python3 solution using try and except block
print-words-vertically
0
1
\n\n# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n w=[]\n l=s.split()\n for i in range(len(sorted(s.split(),key=len,reverse=1)[0])):\n ss=""\n for j in range(len(s.split())):\n try:\n ss+=l[j][i]\n ...
1
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Exam...
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
Python3 solution using try and except block
print-words-vertically
0
1
\n\n# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n w=[]\n l=s.split()\n for i in range(len(sorted(s.split(),key=len,reverse=1)[0])):\n ss=""\n for j in range(len(s.split())):\n try:\n ss+=l[j][i]\n ...
1
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
Beats 90% || Python || Easy To Understand
print-words-vertically
0
1
# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n s=list(s.split())\n\n max_len=0\n for ele in s:\n max_len=max(max_len,len(ele))\n\n for i in range(len(s)):\n if len(s[i])<max_len:\n s[i]=s[i]+" "*(max_len-len(s[i]))\n\n...
2
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Exam...
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
Beats 90% || Python || Easy To Understand
print-words-vertically
0
1
# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n s=list(s.split())\n\n max_len=0\n for ele in s:\n max_len=max(max_len,len(ele))\n\n for i in range(len(s)):\n if len(s[i])<max_len:\n s[i]=s[i]+" "*(max_len-len(s[i]))\n\n...
2
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
Python3 Sloution . Beats 100%
print-words-vertically
0
1
\n\n# Approach\nfirst split the string and then collect all the values in the same index then strip all the trailling white spaces.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n\n\n# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n temp = s.split()\n res = []\n\n ...
0
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Exam...
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
Python3 Sloution . Beats 100%
print-words-vertically
0
1
\n\n# Approach\nfirst split the string and then collect all the values in the same index then strip all the trailling white spaces.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n\n\n# Code\n```\nclass Solution:\n def printVertically(self, s: str) -> List[str]:\n temp = s.split()\n res = []\n\n ...
0
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
cool python
print-words-vertically
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 a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Exam...
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
cool python
print-words-vertically
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 an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
Python3 O(N) solution with DFS (99.65% Runtime)
delete-leaves-with-a-given-value
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/041ad083-9bf5-46fd-a965-fe9fd0aaa703_1702480068.849295.png)\nUtilize depth first search with leaf node check and check if it become leaf node \n\n# Approach\n<!-- Describe your approac...
1
Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`. Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also be deleted (you need to continue doing that until you cannot). **Examp...
Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs.
Python3 O(N) solution with DFS (99.65% Runtime)
delete-leaves-with-a-given-value
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/041ad083-9bf5-46fd-a965-fe9fd0aaa703_1702480068.849295.png)\nUtilize depth first search with leaf node check and check if it become leaf node \n\n# Approach\n<!-- Describe your approac...
1
Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`. The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`. Return _the number of students_ doing their homework at time `queryTime`. More formally, return the number of students wh...
Use the DFS to reconstruct the tree such that no leaf node is equal to the target. If the leaf node is equal to the target, return an empty object instead.
python, >90%, short (6 lines) and easy, explained
delete-leaves-with-a-given-value
0
1
\n\n```\nclass Solution:\n def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode:\n if root:\n root.left = self.removeLeafNodes(root.left, target)\n root.right = self.removeLeafNodes(root.right, target) \n if root.val == target and not root.left and not root.right...
36
Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`. Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also be deleted (you need to continue doing that until you cannot). **Examp...
Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs.
python, >90%, short (6 lines) and easy, explained
delete-leaves-with-a-given-value
0
1
\n\n```\nclass Solution:\n def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode:\n if root:\n root.left = self.removeLeafNodes(root.left, target)\n root.right = self.removeLeafNodes(root.right, target) \n if root.val == target and not root.left and not root.right...
36
Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`. The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`. Return _the number of students_ doing their homework at time `queryTime`. More formally, return the number of students wh...
Use the DFS to reconstruct the tree such that no leaf node is equal to the target. If the leaf node is equal to the target, return an empty object instead.
2 solutions | DFS | Easy to understand | Faster | Python Solutions
delete-leaves-with-a-given-value
0
1
```\n def dfs_second(self, root, target):\n def rec(node):\n if node:\n left = rec(node.left)\n right = rec(node.right)\n if not left and not right and node.val == target:\n return None\n node.left = left\n ...
9
Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`. Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also be deleted (you need to continue doing that until you cannot). **Examp...
Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs.
2 solutions | DFS | Easy to understand | Faster | Python Solutions
delete-leaves-with-a-given-value
0
1
```\n def dfs_second(self, root, target):\n def rec(node):\n if node:\n left = rec(node.left)\n right = rec(node.right)\n if not left and not right and node.val == target:\n return None\n node.left = left\n ...
9
Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`. The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`. Return _the number of students_ doing their homework at time `queryTime`. More formally, return the number of students wh...
Use the DFS to reconstruct the tree such that no leaf node is equal to the target. If the leaf node is equal to the target, return an empty object instead.
⏰3 Minutes To Realise \\\ Greedy Approach \\\ Beats 99%
minimum-number-of-taps-to-open-to-water-a-garden
0
1
# Make sure that the following works\n**Simple algorithm O(n) space, time.**\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n arr = [0] * (n + 1)\n for idx, cur_radius in enumerate(ranges):\n if cur_radius == 0:\n continue\n \n ...
6
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
⏰3 Minutes To Realise \\\ Greedy Approach \\\ Beats 99%
minimum-number-of-taps-to-open-to-water-a-garden
0
1
# Make sure that the following works\n**Simple algorithm O(n) space, time.**\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n arr = [0] * (n + 1)\n for idx, cur_radius in enumerate(ranges):\n if cur_radius == 0:\n continue\n \n ...
6
Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format: * First letter is in upper case. * Each word in `text` are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If tw...
Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not...
[Python3][Stack] Easy Stack Solution beats 94% runtime.
minimum-number-of-taps-to-open-to-water-a-garden
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an empty stack called `range_stack` to keep track of the ranges being used.\n2. Initialize a variable `covered` to keep track of the total coverage achieved.\n3. Iterate through the given ranges. For each range, check if the current rang...
3
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
[Python3][Stack] Easy Stack Solution beats 94% runtime.
minimum-number-of-taps-to-open-to-water-a-garden
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an empty stack called `range_stack` to keep track of the ranges being used.\n2. Initialize a variable `covered` to keep track of the total coverage achieved.\n3. Iterate through the given ranges. For each range, check if the current rang...
3
Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format: * First letter is in upper case. * Each word in `text` are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If tw...
Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not...
Python3 👍||⚡95% faster beats, not dp 🔥|| clean solution || simple explain ||
minimum-number-of-taps-to-open-to-water-a-garden
0
1
![image.png](https://assets.leetcode.com/users/images/a2a85df7-9685-4745-9542-e7fbdeeae2b6_1693476154.3244436.png)\n\n# Complexity\n- Time complexity: O (*N logN*)\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```...
2
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Python3 👍||⚡95% faster beats, not dp 🔥|| clean solution || simple explain ||
minimum-number-of-taps-to-open-to-water-a-garden
0
1
![image.png](https://assets.leetcode.com/users/images/a2a85df7-9685-4745-9542-e7fbdeeae2b6_1693476154.3244436.png)\n\n# Complexity\n- Time complexity: O (*N logN*)\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```...
2
Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format: * First letter is in upper case. * Each word in `text` are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If tw...
Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not...
Python3 Solution
minimum-number-of-taps-to-open-to-water-a-garden
0
1
\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n dp=[0]+[n+2]*n\n for i,x in enumerate(ranges):\n for j in range(max(i-x+1,0),min(i+x,n)+1):\n dp[j]=min(dp[j],dp[max(0,i-x)]+1)\n\n return dp[n] if dp[n]<n+2 else -1 \n```
2
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Python3 Solution
minimum-number-of-taps-to-open-to-water-a-garden
0
1
\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n dp=[0]+[n+2]*n\n for i,x in enumerate(ranges):\n for j in range(max(i-x+1,0),min(i+x,n)+1):\n dp[j]=min(dp[j],dp[max(0,i-x)]+1)\n\n return dp[n] if dp[n]<n+2 else -1 \n```
2
Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format: * First letter is in upper case. * Each word in `text` are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If tw...
Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not...
Python Top Down and Bottom Up Solution
minimum-number-of-taps-to-open-to-water-a-garden
0
1
# Intuition\nThe problem can be solved using a dynamic programming approach with memoization. The idea is to work backwards from the end of the garden and determine the minimum number of taps needed to water each position, while considering the coverage of each tap.\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- ...
1
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Python Top Down and Bottom Up Solution
minimum-number-of-taps-to-open-to-water-a-garden
0
1
# Intuition\nThe problem can be solved using a dynamic programming approach with memoization. The idea is to work backwards from the end of the garden and determine the minimum number of taps needed to water each position, while considering the coverage of each tap.\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- ...
1
Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format: * First letter is in upper case. * Each word in `text` are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If tw...
Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not...
Greedy Approach | Python/ JS Solution
minimum-number-of-taps-to-open-to-water-a-garden
0
1
Hello **Tenno Leetcoders**, \n\nFor this problem, we have a one-dimensional garden represented by a line starting from point 0 and ending at point n. There are taps placed along this line at various points, and each tap has a coverage range that can water a specific area around it.\n\nYour goal is to determine the mini...
1
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Greedy Approach | Python/ JS Solution
minimum-number-of-taps-to-open-to-water-a-garden
0
1
Hello **Tenno Leetcoders**, \n\nFor this problem, we have a one-dimensional garden represented by a line starting from point 0 and ending at point n. There are taps placed along this line at various points, and each tap has a coverage range that can water a specific area around it.\n\nYour goal is to determine the mini...
1
Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format: * First letter is in upper case. * Each word in `text` are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If tw...
Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not...
✅ 99.5% Greedy with Dynamic + DP
minimum-number-of-taps-to-open-to-water-a-garden
1
1
# Interview Guide - Minimum Number of Taps to Open to Water a Garden\n\n## Problem Understanding\n\n### Description\nAt its core, this problem is a fascinating blend of interval merging and greedy optimization. You are provided with a one-dimensional garden and the ability to water certain intervals of it by opening ta...
84
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
✅ 99.5% Greedy with Dynamic + DP
minimum-number-of-taps-to-open-to-water-a-garden
1
1
# Interview Guide - Minimum Number of Taps to Open to Water a Garden\n\n## Problem Understanding\n\n### Description\nAt its core, this problem is a fascinating blend of interval merging and greedy optimization. You are provided with a one-dimensional garden and the ability to water certain intervals of it by opening ta...
84
Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format: * First letter is in upper case. * Each word in `text` are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If tw...
Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not...
✅Easy Solution✅Python/C#/C++/Java/C🔥Clean Code🔥
minimum-number-of-taps-to-open-to-water-a-garden
1
1
# Problem\n***\nThis problem involves finding the minimum number of taps that need to be open to water the entire garden. The garden is represented as a one-dimensional axis from 0 to n, and each tap can water a specific range around its location. The goal is to determine the minimum number of taps you need to turn on ...
13
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
✅Easy Solution✅Python/C#/C++/Java/C🔥Clean Code🔥
minimum-number-of-taps-to-open-to-water-a-garden
1
1
# Problem\n***\nThis problem involves finding the minimum number of taps that need to be open to water the entire garden. The garden is represented as a one-dimensional axis from 0 to n, and each tap can water a specific range around its location. The goal is to determine the minimum number of taps you need to turn on ...
13
Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format: * First letter is in upper case. * Each word in `text` are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If tw...
Create intervals of the area covered by each tap, sort intervals by the left end. We need to cover the interval [0, n]. we can start with the first interval and out of all intervals that intersect with it we choose the one that covers the farthest point to the right. What if there is a gap between intervals that is not...
Simple Python Solution
sort-the-matrix-diagonally
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing Hashmap\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:94.27%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:86.07%\n<!-- Add your space comple...
2
A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `ma...
The first move keeps the parity of the element as it is. The second move changes the parity of the element. Since the first move is free, if all the numbers have the same parity, the answer would be zero. Find the minimum cost to make all the numbers have the same parity.
Simple Python Solution
sort-the-matrix-diagonally
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing Hashmap\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:94.27%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:86.07%\n<!-- Add your space comple...
2
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
[Python 3] Intuitive solution (sort each diagonal)
sort-the-matrix-diagonally
0
1
```\nclass Solution:\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n m = len(mat)\n n = len(mat[0])\n \n if m == 1 or n == 1:\n return mat\n \n # each column\n for j in range(n):\n self.sort(mat, 0, j, m, n)\n \n ...
1
A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `ma...
The first move keeps the parity of the element as it is. The second move changes the parity of the element. Since the first move is free, if all the numbers have the same parity, the answer would be zero. Find the minimum cost to make all the numbers have the same parity.
[Python 3] Intuitive solution (sort each diagonal)
sort-the-matrix-diagonally
0
1
```\nclass Solution:\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n m = len(mat)\n n = len(mat[0])\n \n if m == 1 or n == 1:\n return mat\n \n # each column\n for j in range(n):\n self.sort(mat, 0, j, m, n)\n \n ...
1
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
python3 | easy-understanding | explained | sort
sort-the-matrix-diagonally
0
1
```\nclass Solution:\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n lst = []\n n, m = len(mat), len(mat[0])\n \n # leftmost column\n for i in range(n):\n lst.append([i, 0])\n \n # rightmost row\n for i in range(m):\n ...
2
A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `ma...
The first move keeps the parity of the element as it is. The second move changes the parity of the element. Since the first move is free, if all the numbers have the same parity, the answer would be zero. Find the minimum cost to make all the numbers have the same parity.
python3 | easy-understanding | explained | sort
sort-the-matrix-diagonally
0
1
```\nclass Solution:\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n lst = []\n n, m = len(mat), len(mat[0])\n \n # leftmost column\n for i in range(n):\n lst.append([i, 0])\n \n # rightmost row\n for i in range(m):\n ...
2
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Python sorting one diag at a time | O(min(M,N)) space | explained
sort-the-matrix-diagonally
0
1
zip takes two lists A and B and turns them into a 2d list\nA = [1,2,3]\nB = [0,0,0]\nzip(A,B) will be [ (1,0), (2,0), (3,0) ]\n\nfor m=2 and n = 3\nstarting points will be [ (0,1), (1,0), (0,1), (0,2) ] \nwe use this zip function to make a list having starting rows and columns of all diagonals\nwe get the rest of th...
2
A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `ma...
The first move keeps the parity of the element as it is. The second move changes the parity of the element. Since the first move is free, if all the numbers have the same parity, the answer would be zero. Find the minimum cost to make all the numbers have the same parity.
Python sorting one diag at a time | O(min(M,N)) space | explained
sort-the-matrix-diagonally
0
1
zip takes two lists A and B and turns them into a 2d list\nA = [1,2,3]\nB = [0,0,0]\nzip(A,B) will be [ (1,0), (2,0), (3,0) ]\n\nfor m=2 and n = 3\nstarting points will be [ (0,1), (1,0), (0,1), (0,2) ] \nwe use this zip function to make a list having starting rows and columns of all diagonals\nwe get the rest of th...
2
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Concise | Simple | Fast | Python Solution
reverse-subarray-to-maximize-array-value
0
1
# Code\n```\nclass Solution:\n def maxValueAfterReverse(self, nums: List[int]) -> int:\n originalValue, sz = 0, len(nums)\n for idx in range(sz - 1):\n originalValue += abs(nums[idx] - nums[idx + 1])\n finalValue = originalValue\n for idx in range(1, sz - 1):\n final...
0
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Concise | Simple | Fast | Python Solution
reverse-subarray-to-maximize-array-value
0
1
# Code\n```\nclass Solution:\n def maxValueAfterReverse(self, nums: List[int]) -> int:\n originalValue, sz = 0, len(nums)\n for idx in range(sz - 1):\n originalValue += abs(nums[idx] - nums[idx + 1])\n finalValue = originalValue\n for idx in range(1, sz - 1):\n final...
0
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only...
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[...
Python Linear Time Solution | Faster than 60%
reverse-subarray-to-maximize-array-value
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nIn this problem we can use a math tool ... to say that ```abs(a - b)``` is a range, where ```a``` and ```b``` are some values in the array that are next to each other ```[num[0], ..., a, b, ..., nums[n - 1]]```. If we follow this line of thought and c...
0
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Python Linear Time Solution | Faster than 60%
reverse-subarray-to-maximize-array-value
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nIn this problem we can use a math tool ... to say that ```abs(a - b)``` is a range, where ```a``` and ```b``` are some values in the array that are next to each other ```[num[0], ..., a, b, ..., nums[n - 1]]```. If we follow this line of thought and c...
0
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only...
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[...
Super Easy Python | O(nlogn) | Beats 97.96% submissions
rank-transform-of-an-array
0
1
Upvote if you find it helpful :-) \n# Intuition\n1. Sort the input array and store its index\n2. Map that index with the value of the input array\n3. Use hashmap for $$O(1)$$ access time\n\n# Approach\n1. Create hashmap\n2. Sort unique elements using sorted and set functions\n3. update the arr or create new list and ma...
0
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
Python3 || Beats 84.44%
rank-transform-of-an-array
0
1
# Please upvote if you find the solution helpful.\n\n# Code\n```\nclass Solution:\n def arrayRankTransform(self, arr: List[int]) -> List[int]:\n d = {}\n f_lst=[]\n arr1 = sorted(list(set(arr)))\n for i in range(len(arr1)):\n d[arr1[i]] = i+1\n for i in arr:\n ...
3
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
Easy Python Solution| Beats 95% Run Time
rank-transform-of-an-array
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)$$ --...
3
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
Python Easy Solution || Sorting || Hashmap
rank-transform-of-an-array
0
1
# Complexity\n- Time complexity:\nO(nlogn) \nBecause of sorting\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def arrayRankTransform(self, arr: List[int]) -> List[int]:\n dic={}\n lis=list(set(arr))\n lis.sort()\n for i in range(len(lis)):\n dic[lis[i]]=i\n ...
2
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
Easiest solution you ever find.#python3
rank-transform-of-an-array
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
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
Python Easy Solution
rank-transform-of-an-array
0
1
```\nclass Solution:\n def arrayRankTransform(self, arr: List[int]) -> List[int]:\n \n arrx = [i for i in set(arr)]\n arrx.sort()\n \n hp={}\n for i in range(len(arrx)):\n if arrx[i] in hp:\n continue\n else:\n hp[arrx[i]] ...
1
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
1331. Rank Transform of an Array | using python| beats 95%
rank-transform-of-an-array
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)$$ --> O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)...
1
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
✅ Python || 2 Easy || One liner
remove-palindromic-subsequences
0
1
The input `s` meets the following requirements:\n>s[i] is either \'a\' or \'b\'.\n>1 <= s.length <= 1000\n\nSo if you take this as a hint, you can observe there are only two possible outputs:\n1. if `s` is pallindrome, return `1`\n2. else return `2`. \n\nIf the `s` is not pallindrome, it will always be reduced to empty...
48
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
Easiest solution O(1) complexity in python
remove-palindromic-subsequences
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)$$ --...
2
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
1 Line Super simple: return 1 if s==s[::-1] else 2
remove-palindromic-subsequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\naaa...aaa is palindrome. So as bbbb...bbb.\nWe can disassemble every string s as this form.\nSo maximum return value is 2\nIf and only if s is palindrome, it returns 1\n\n# Code\n```\nclass Solution:\n def removePalindromeSub(self, s: ...
1
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
1-liner Python easy to understand
remove-palindromic-subsequences
0
1
Pay attention to the constraints! It says that s[i] is either \'a\' or \'b\', so we can have at most two cases, \n\n1) If the string already is palindrome then the result is 1 \n\n2) The string is not a palindrome, which is we can think of as removing all letters \'a\' and \'b\', resulting in 2.\n\nI really lost real t...
1
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
remove-palindromic-subsequences
remove-palindromic-subsequences
0
1
# Code\n```\nclass Solution:\n def removePalindromeSub(self, s: str) -> int:\n if s=="":\n return 0\n elif s==s[::-1]:\n return 1\n return 2\n\n \n```
1
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
Python Easy Solution || Sorting
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
# Code\n```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n rating=[]\n res=[]\n for restro in restaurants:\n if (restro[3]<=maxPrice) and (restro[4]<=maxDistance):\n if (v...
1
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Python Easy Solution || Sorting
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
# Code\n```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n rating=[]\n res=[]\n for restro in restaurants:\n if (restro[3]<=maxPrice) and (restro[4]<=maxDistance):\n if (v...
1
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
Easy Python Solution
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
# Code\n```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n restaurants.sort(key=itemgetter(1,0),reverse=True)\n lst=[]\n """for i in restaurants:\n print(i)"""\n for i in restaura...
2
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Easy Python Solution
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
# Code\n```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n restaurants.sort(key=itemgetter(1,0),reverse=True)\n lst=[]\n """for i in restaurants:\n print(i)"""\n for i in restaura...
2
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
Python3 solution
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n def f(x):\n if (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or (veganFriendly == 0 and x[3] <= maxPrice and x[4] <...
3
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Python3 solution
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n def f(x):\n if (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or (veganFriendly == 0 and x[3] <= maxPrice and x[4] <...
3
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
Simple python3 solution | Filter + Sorting
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
# Complexity\n- Time complexity: $$O(n \\cdot \\log(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``` python3 []\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly...
0
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Simple python3 solution | Filter + Sorting
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
# Complexity\n- Time complexity: $$O(n \\cdot \\log(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``` python3 []\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly...
0
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
Easy to understand Python3 solution
filter-restaurants-by-vegan-friendly-price-and-distance
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 array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Easy to understand Python3 solution
filter-restaurants-by-vegan-friendly-price-and-distance
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 a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
Very east simple for beginners !!!!
filter-restaurants-by-vegan-friendly-price-and-distance
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 array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Very east simple for beginners !!!!
filter-restaurants-by-vegan-friendly-price-and-distance
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 a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
Python solution using sorting
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n res = []\n for restaurant in restaurants:\n if restaurant[2] >= veganFriendly and restaurant[3] <= maxPrice and restaurant[4] <= maxDistance:\...
0
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Python solution using sorting
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n res = []\n for restaurant in restaurants:\n if restaurant[2] >= veganFriendly and restaurant[3] <= maxPrice and restaurant[4] <= maxDistance:\...
0
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
Beats 99.19%of users with Python3
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
\n# Code\n```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n selectedRes = []\n\n if veganFriendly == 0:\n for i in range(len(restaurants)):\n if restaurants[i][3] <= maxPrice an...
0
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Beats 99.19%of users with Python3
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
\n# Code\n```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n selectedRes = []\n\n if veganFriendly == 0:\n for i in range(len(restaurants)):\n if restaurants[i][3] <= maxPrice an...
0
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
Python 1-Liner
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n return [\n id for id, _, is_vegan, price, distance in sorted(restaurants, key=lambda x: (-x[1], -x[0])) if \n ((veganFriendly and is_vegan...
0
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Python 1-Liner
filter-restaurants-by-vegan-friendly-price-and-distance
0
1
```\nclass Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n return [\n id for id, _, is_vegan, price, distance in sorted(restaurants, key=lambda x: (-x[1], -x[0])) if \n ((veganFriendly and is_vegan...
0
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
[Python3] Easy way
filter-restaurants-by-vegan-friendly-price-and-distance
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 array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
[Python3] Easy way
filter-restaurants-by-vegan-friendly-price-and-distance
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 a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one wor...
Do the filtering and sort as said. Note that the id may not be the index in the array.
Python || 98.46% Faster || Explained || Floyd Warshall || Dijkstra's
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
0
1
**Brute Force Approach (Floyd Warshall) :**\n```\ndef findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n cost=[[float(\'inf\') if i!=j else 0 for j in range(n)] for i in range(n)]\n for u,v,d in edges:\n cost[u][v]=d\n cost[v][u]=d\n for via in...
7
There are `n` cities numbered from `0` to `n-1`. Given the array `edges` where `edges[i] = [fromi, toi, weighti]` represents a bidirectional and weighted edge between cities `fromi` and `toi`, and given the integer `distanceThreshold`. Return the city with the smallest number of cities that are reachable through some ...
null
Python || 98.46% Faster || Explained || Floyd Warshall || Dijkstra's
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
0
1
**Brute Force Approach (Floyd Warshall) :**\n```\ndef findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n cost=[[float(\'inf\') if i!=j else 0 for j in range(n)] for i in range(n)]\n for u,v,d in edges:\n cost[u][v]=d\n cost[v][u]=d\n for via in...
7
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`. **Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. **Example 1:** **Input:** s = "abciiidef ", k = 3 **Output:** 3 **Explanation:** The substring "iii " contains 3 vow...
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
ALL SOURCE SORTEST PATH | FLOYD ALGO
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
0
1
\n# Code\n```\nclass Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n\n k = float("inf")\n cost = [[k for _ in range(n)] for _ in range(n)]\n \n for u, v, w in edges:\n cost[u][v] = cost[v][u] = w\n\n for i in range(n):\...
4
There are `n` cities numbered from `0` to `n-1`. Given the array `edges` where `edges[i] = [fromi, toi, weighti]` represents a bidirectional and weighted edge between cities `fromi` and `toi`, and given the integer `distanceThreshold`. Return the city with the smallest number of cities that are reachable through some ...
null
ALL SOURCE SORTEST PATH | FLOYD ALGO
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
0
1
\n# Code\n```\nclass Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n\n k = float("inf")\n cost = [[k for _ in range(n)] for _ in range(n)]\n \n for u, v, w in edges:\n cost[u][v] = cost[v][u] = w\n\n for i in range(n):\...
4
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`. **Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. **Example 1:** **Input:** s = "abciiidef ", k = 3 **Output:** 3 **Explanation:** The substring "iii " contains 3 vow...
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
Help Needed|| Leetcode Community
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
0
1
## Help Needed \n\nSomeone please point out where i am wrong :)\n\n```\nimport heapq\nfrom typing import List\nclass Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n # code here\n graph = [[] for _ in range(n)]\n for u, v, w in edges:\n ...
2
There are `n` cities numbered from `0` to `n-1`. Given the array `edges` where `edges[i] = [fromi, toi, weighti]` represents a bidirectional and weighted edge between cities `fromi` and `toi`, and given the integer `distanceThreshold`. Return the city with the smallest number of cities that are reachable through some ...
null
Help Needed|| Leetcode Community
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
0
1
## Help Needed \n\nSomeone please point out where i am wrong :)\n\n```\nimport heapq\nfrom typing import List\nclass Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n # code here\n graph = [[] for _ in range(n)]\n for u, v, w in edges:\n ...
2
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`. **Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. **Example 1:** **Input:** s = "abciiidef ", k = 3 **Output:** 3 **Explanation:** The substring "iii " contains 3 vow...
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
91% Faster Solution
minimum-difficulty-of-a-job-schedule
0
1
```\nclass Solution:\n def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:\n jobCount = len(jobDifficulty) \n if jobCount < d:\n return -1\n\n @lru_cache(None)\n def topDown(jobIndex: int, remainDayCount: int) -> int:\n remainJobCount = jobCount - jo...
4
You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`). You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a da...
For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer.