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 short and clean. DP. Bitmask. Functional programming.
smallest-sufficient-team
0
1
# Approach\nTL;DR, Similar to [Editorial solution Approach 2](https://leetcode.com/problems/smallest-sufficient-team/editorial/) but written functionally.\n\n# Complexity\n- Time complexity: $$O(2^k \\cdot n \\cdot log(n))$$\n (Note: $$log(n)$$ is for `int.bit_count()`)\n\n- Space complexity: $$O(2^k)$$\n\nwhere,\n`n i...
1
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
Bottom-up + Bitmask | Python / JS Solution
smallest-sufficient-team
0
1
Hello **Tenno Leetcoders**, \n\nFor this problem, we have you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has.\n\nEach person in the `people` list has a set of skills represented as a list. Our objective is to form a team that...
12
In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in `req_skills`, there is at least one person in the team who has that skill. W...
What if you think of a tree hierarchy for the files?. A path is a node in the tree. Use a hash table to store the valid paths along with their values.
Bottom-up + Bitmask | Python / JS Solution
smallest-sufficient-team
0
1
Hello **Tenno Leetcoders**, \n\nFor this problem, we have you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has.\n\nEach person in the `people` list has a set of skills represented as a list. Our objective is to form a team that...
12
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
Python3 Solution
smallest-sufficient-team
0
1
\n```\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n m=len(req_skills)\n n=len(people)\n skill_index={v:i for i,v in enumerate(req_skills)}\n cand=[]\n for skills in people:\n val=0\n for ski...
5
In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in `req_skills`, there is at least one person in the team who has that skill. W...
What if you think of a tree hierarchy for the files?. A path is a node in the tree. Use a hash table to store the valid paths along with their values.
Python3 Solution
smallest-sufficient-team
0
1
\n```\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n m=len(req_skills)\n n=len(people)\n skill_index={v:i for i,v in enumerate(req_skills)}\n cand=[]\n for skills in people:\n val=0\n for ski...
5
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
🚀 [VIDEO] Faster than 90%🔥| ❗Long Explanation❗ | 2-D DP + BITMASK | Clean Code
smallest-sufficient-team
1
1
# \uD83C\uDF1F Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nMy initial intuition for solving this problem is to use a dynamic programming approach. Since we need to find the smallest sufficient team, it seems logical to consider all possible combinations of people and skills. By usi...
1
In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in `req_skills`, there is at least one person in the team who has that skill. W...
What if you think of a tree hierarchy for the files?. A path is a node in the tree. Use a hash table to store the valid paths along with their values.
🚀 [VIDEO] Faster than 90%🔥| ❗Long Explanation❗ | 2-D DP + BITMASK | Clean Code
smallest-sufficient-team
1
1
# \uD83C\uDF1F Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nMy initial intuition for solving this problem is to use a dynamic programming approach. Since we need to find the smallest sufficient team, it seems logical to consider all possible combinations of people and skills. By usi...
1
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
[Python3] Easy to understand. No DP, no bitmask
smallest-sufficient-team
0
1
```\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n n = len(req_skills)\n # 1. Assign indexes for each skill string\n skills = {\n skill: i for i, skill in enumerate(req_skills)\n }\n # 2. Create sets wi...
2
In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in `req_skills`, there is at least one person in the team who has that skill. W...
What if you think of a tree hierarchy for the files?. A path is a node in the tree. Use a hash table to store the valid paths along with their values.
[Python3] Easy to understand. No DP, no bitmask
smallest-sufficient-team
0
1
```\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n n = len(req_skills)\n # 1. Assign indexes for each skill string\n skills = {\n skill: i for i, skill in enumerate(req_skills)\n }\n # 2. Create sets wi...
2
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
am i stupid for thinking bfs? [python 3 bfs solution]
smallest-sufficient-team
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ni thought it was bfs because it said minimum number of people. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ni started off with a convert function, traversed the graph using a bfs function and marking things vis...
2
In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in `req_skills`, there is at least one person in the team who has that skill. W...
What if you think of a tree hierarchy for the files?. A path is a node in the tree. Use a hash table to store the valid paths along with their values.
am i stupid for thinking bfs? [python 3 bfs solution]
smallest-sufficient-team
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ni thought it was bfs because it said minimum number of people. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ni started off with a convert function, traversed the graph using a bfs function and marking things vis...
2
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
PYTHON DICTIONARY solution with explanation (252ms)
number-of-equivalent-domino-pairs
0
1
```\nclass Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n \n #Keep track of the dominoes with a dictionary\n\t\t#counter[ DOMINO ] = COUNT\n counter = defaultdict( int );\n \n #Total will be the total number of pairs\n total = 0;\n \n ...
6
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
PYTHON DICTIONARY solution with explanation (252ms)
number-of-equivalent-domino-pairs
0
1
```\nclass Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n \n #Keep track of the dominoes with a dictionary\n\t\t#counter[ DOMINO ] = COUNT\n counter = defaultdict( int );\n \n #Total will be the total number of pairs\n total = 0;\n \n ...
6
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
[python3] dictionary count
number-of-equivalent-domino-pairs
0
1
* Use a dictionary to count how many times an intrinsic domino appeared. Here we define intrinsic domino as a sorted domino. By sort the list, we can easily identify the intrinsic domino. Use the intrinsic domino as key, the intrinsic domino frequency as value, store the information we need in a dictionary.\n```\nExam...
23
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
[python3] dictionary count
number-of-equivalent-domino-pairs
0
1
* Use a dictionary to count how many times an intrinsic domino appeared. Here we define intrinsic domino as a sorted domino. By sort the list, we can easily identify the intrinsic domino. Use the intrinsic domino as key, the intrinsic domino frequency as value, store the information we need in a dictionary.\n```\nExam...
23
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
dictionary!!
number-of-equivalent-domino-pairs
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 list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
dictionary!!
number-of-equivalent-domino-pairs
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
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
number-of-equivalent-domino-pairs
number-of-equivalent-domino-pairs
0
1
# Code\n```\nclass Solution:\n def numEquivDominoPairs(self, t: List[List[int]]) -> int:\n d = {}\n for i in range(len(t)):\n a = tuple(sorted(t[i]))\n if a not in d:\n d[a] = 1\n else:\n d[a]+=1\n count = 0\n print(d)\n ...
0
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
number-of-equivalent-domino-pairs
number-of-equivalent-domino-pairs
0
1
# Code\n```\nclass Solution:\n def numEquivDominoPairs(self, t: List[List[int]]) -> int:\n d = {}\n for i in range(len(t)):\n a = tuple(sorted(t[i]))\n if a not in d:\n d[a] = 1\n else:\n d[a]+=1\n count = 0\n print(d)\n ...
0
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
Python O(n) solution
number-of-equivalent-domino-pairs
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- Using Dictionary\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 he...
0
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
Python O(n) solution
number-of-equivalent-domino-pairs
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- Using Dictionary\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 he...
0
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
Python Simple Solution Without using dictionary
number-of-equivalent-domino-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to compare two dominoes which can be either exactly equal or there are equal after rotating one of the domino.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst instead of checking for both exactly equal ...
0
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
Python Simple Solution Without using dictionary
number-of-equivalent-domino-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to compare two dominoes which can be either exactly equal or there are equal after rotating one of the domino.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst instead of checking for both exactly equal ...
0
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
Python Simple Solution!!
number-of-equivalent-domino-pairs
0
1
\n# Code\n```\nclass Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n \n occurrences: dict = {}\n count: int = 0\n \n for pair in dominoes:\n a, b = sorted(pair)\n occurrences[f"{a}{b}"] = occurrences.get(f"{a}{b}", 0) + 1\n\n ...
0
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
Python Simple Solution!!
number-of-equivalent-domino-pairs
0
1
\n# Code\n```\nclass Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n \n occurrences: dict = {}\n count: int = 0\n \n for pair in dominoes:\n a, b = sorted(pair)\n occurrences[f"{a}{b}"] = occurrences.get(f"{a}{b}", 0) + 1\n\n ...
0
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
Python solution
number-of-equivalent-domino-pairs
0
1
```\nclass Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n couples, pairs = {}, 0\n\n for couple in dominoes:\n couple = f"{sorted(couple)}"\n couples[couple] = couples.get(couple, 0) + 1\n \n for _, value in couples.items():\n ...
0
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
Python solution
number-of-equivalent-domino-pairs
0
1
```\nclass Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n couples, pairs = {}, 0\n\n for couple in dominoes:\n couple = f"{sorted(couple)}"\n couples[couple] = couples.get(couple, 0) + 1\n \n for _, value in couples.items():\n ...
0
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
Python3: find the number of combinations for each pair. T/M 90/59
number-of-equivalent-domino-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirst, we need to count the number of equal dominoes, where n is the number of dominoes. \nSecond, we need to find the number of combinations 2 from n for each pair and sum them.\n\n# Approach\n<!-- Describe your approach to solving the...
0
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
Python3: find the number of combinations for each pair. T/M 90/59
number-of-equivalent-domino-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirst, we need to count the number of equal dominoes, where n is the number of dominoes. \nSecond, we need to find the number of combinations 2 from n for each pair and sum them.\n\n# Approach\n<!-- Describe your approach to solving the...
0
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
Python solution: O(n) time and space
number-of-equivalent-domino-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst let\'s try to find out how many equal pairs we have, knowing that (a, b) == (b, a). Then for each count, see how many indices i<j we need to add to the final solution.\n\n# Approach\n<!-- Describe your approach to solving the proble...
0
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino. Return _the number of pairs_ `(i, j)` _for which_ `0 <= i < j < dominoes.length`_,...
Use a stack to process everything greedily.
Python solution: O(n) time and space
number-of-equivalent-domino-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst let\'s try to find out how many equal pairs we have, knowing that (a, b) == (b, a). Then for each count, see how many indices i<j we need to add to the final solution.\n\n# Approach\n<!-- Describe your approach to solving the proble...
0
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they find their seat occupied Return _the probability th...
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
Using BFS Alternating Path Length
shortest-path-with-alternating-colors
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thoughts on solving this problem are to use a breadth-first search approach where we explore all the neighbors of each node. We need to keep track of the distances from node 0, alternating between red and blue distances. We also ...
2
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
python bfs beats 95%
shortest-path-with-alternating-colors
0
1
- Use a hashmap to store all the edges and their colours\n- NO edge is travelled twice: during bfs, for each edge travelled, add the edge to a set\n- Only proceed with bfs for an edge if the colour it took to reach the current node, is different from the colour of the edge\n\n\n```\nclass Solution:\n def shortestAlt...
1
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
🗓️ Daily LeetCoding Challenge February, Day 11 [BFS SOLUTION]
shortest-path-with-alternating-colors
1
1
# Intuition \nuse BFS traversal with mindset of traversing..starting in two ways possible [RED&BLUE] . for that take a queue in which first element represents NODE and second represents COLOR. add into the queue with both red and blue. if started with RED , next we have to find BLUE one. vice-versa RED.\n\n<!-- Descr...
1
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
Python BFS solution
shortest-path-with-alternating-colors
0
1
```\nclass Solution:\n def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:\n red = defaultdict(list)\n blue = defaultdict(list)\n for s, d in redEdges:\n red[s].append(d)\n for s, d in blueEdges:\n blue[s].a...
1
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
EASY PYTHON SOLUTION || BFS APPROACH
shortest-path-with-alternating-colors
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N*K)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N*K)$$\n<!-- Add your space complexity ...
1
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
python - clean BFS - 90%
shortest-path-with-alternating-colors
0
1
\n# Code\n```\nclass Solution:\n def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:\n connections = defaultdict(list)\n for a, b in redEdges:\n connections[a].append((b, \'red\'))\n for a, b in blueEdges:\n connec...
1
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
Python short and clean. BFS
shortest-path-with-alternating-colors
0
1
# Approach\nExtend the classic `BFS` from `source` node to all nodes into `(source, color)` to all nodes, making sure to `flip` colors on each step. \n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def shortestAlternatingPaths(self, n: int, red_edg...
1
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
[Python] Simple BFS and tracking visited color; Explained
shortest-path-with-alternating-colors
0
1
This is a simple BFS problem with a speical handling of picking different path color in each step.\n\nStep 1: Build two graphs based on the edge color;\nStep 2: BFS traverse each node, and check the steps for each node. We update the path length when we found a shorter path.\n\nTwo things we need to handle in this spec...
1
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
simple & easy bfs solution in python
shortest-path-with-alternating-colors
0
1
\n# Code\n```\nclass Solution:\n def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:\n # Adjacent creation\n adj = [list() for _ in range(n)]\n\n for red_edge in redEdges:\n adj[red_edge[0]].append((red_edge[1], 0))\n\n ...
3
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
Python || Breadth-First Search 🔥
shortest-path-with-alternating-colors
0
1
# Code\n```\nclass Solution:\n def shortestAlternatingPaths(self, n, red_edges, blue_edges):\n graph = [[[], []] for i in range(n)]\n for i, j in red_edges:\n graph[i][0].append(j)\n for i, j in blue_edges:\n graph[i][1].append(j)\n ans = [[0, 0]] + [[n * 2, n * 2] f...
1
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
7ms (Beats 99.99%)🔥🔥|| Full Explanation✅|| Breadth First Search✅|| C++|| Java|| Python3
shortest-path-with-alternating-colors
1
1
# Intuition :\n- Here we are given a graph with two types of edges (red and blue), the goal is to find the shortest path from node 0 to every other node such that no two consecutive edges have the same color.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Explanation to Approach :\n- So we ar...
66
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there ...
Instead of adding a character, try deleting a character to form a chain in reverse. For each word in order of length, for each word2 which is word with one character removed, length[word2] = max(length[word2], length[word] + 1).
Simple DP Solution | Easy - To - Understand 🚀🚀
minimum-cost-tree-from-leaf-values
1
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
Given an array `arr` of positive integers, consider all binary trees such that: * Each node has either `0` or `2` children; * The values of `arr` correspond to the values of each **leaf** in an in-order traversal of the tree. * The value of each non-leaf node is equal to the product of the largest leaf value in ...
Think of the final answer as a sum of weights with + or - sign symbols infront of each weight. Actually, all sums with 1 of each sign symbol are possible. Use dynamic programming: for every possible sum with N stones, those sums +x or -x is possible with N+1 stones, where x is the value of the newest stone. (This ove...
[RZ] Summary of all the solutions I have learned from Discuss in Python
minimum-cost-tree-from-leaf-values
0
1
**1. Dynamic programming approach**\nWe are given a list of all the leaf nodes values for certain binary trees, but we do not know which leaf nodes belong to left subtree and which leaf nodes belong to right subtree. Since the given leaf nodes are result of inorder traversal, we know there will be pivots that divide ar...
440
Given an array `arr` of positive integers, consider all binary trees such that: * Each node has either `0` or `2` children; * The values of `arr` correspond to the values of each **leaf** in an in-order traversal of the tree. * The value of each non-leaf node is equal to the product of the largest leaf value in ...
Think of the final answer as a sum of weights with + or - sign symbols infront of each weight. Actually, all sums with 1 of each sign symbol are possible. Use dynamic programming: for every possible sum with N stones, those sums +x or -x is possible with N+1 stones, where x is the value of the newest stone. (This ove...
📌📌 Greedy-Approach || 97% faster || Well-Explained 🐍
minimum-cost-tree-from-leaf-values
0
1
## IDEA :\n**The key idea is to choose the minimum value leaf node and combine it with its neighbour which gives minimum product.**\n\nExample Taken from https://leetcode.com/swapnilsingh421\narr = [5,2,3,4]\n\'\'\'\n\n\t\t ( ) p1 \t\t \t\t\t\t\t ( ) p1\n\t\t / \\ \t\t\t\t\t\t / \\\n\t\t5 ...
23
Given an array `arr` of positive integers, consider all binary trees such that: * Each node has either `0` or `2` children; * The values of `arr` correspond to the values of each **leaf** in an in-order traversal of the tree. * The value of each non-leaf node is equal to the product of the largest leaf value in ...
Think of the final answer as a sum of weights with + or - sign symbols infront of each weight. Actually, all sums with 1 of each sign symbol are possible. Use dynamic programming: for every possible sum with N stones, those sums +x or -x is possible with N+1 stones, where x is the value of the newest stone. (This ove...
PYTHON | EXPLAINED WITH PICTURES | DP | TABULATION | INTUITIVE |
minimum-cost-tree-from-leaf-values
0
1
# EXPLANATION\n![image](https://assets.leetcode.com/users/images/537bdd3a-16c1-4bee-8a42-b79e5945709c_1656511289.7734911.png)\n\nThe idea is very simple:\n\nGiven an array : We can break the array into two subarrays :\nexample arr is (2,3,4,5) \nwhich can be broken as:\n1. (2) (3,4,5)\n2. (2,3) (4,5)\n3. (2,3,4) (5)\n\...
2
Given an array `arr` of positive integers, consider all binary trees such that: * Each node has either `0` or `2` children; * The values of `arr` correspond to the values of each **leaf** in an in-order traversal of the tree. * The value of each non-leaf node is equal to the product of the largest leaf value in ...
Think of the final answer as a sum of weights with + or - sign symbols infront of each weight. Actually, all sums with 1 of each sign symbol are possible. Use dynamic programming: for every possible sum with N stones, those sums +x or -x is possible with N+1 stones, where x is the value of the newest stone. (This ove...
Easy Python and Beats 96% along with explanation
maximum-of-absolute-value-expression
0
1
# Code\n```\nclass Solution:\n def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:\n \'\'\'\n |a1[i]-a1[j]| + |a2[i]-a2[j]| + |i-j|\n total 2(+ or -)**(no. of modules) == 2**3 cases\n\n --> a1[i]-a1[j]+a2[i]-a2[j]+i-j\n == (a1[i]+a2[i]+i) - (a1[j]+a2[j]+j)\n\n ...
3
Given two arrays of integers with equal lengths, return the maximum value of: `|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|` where the maximum is taken over all `0 <= i, j < arr1.length`. **Example 1:** **Input:** arr1 = \[1,2,3,4\], arr2 = \[-1,4,5,6\] **Output:** 13 **Example 2:** **Input:** arr1 = \[1,-...
What if we divide the string into substrings containing only one distinct character with maximal lengths? Now that you have sub-strings with only one distinct character, Try to come up with a formula that counts the number of its sub-strings. Alternatively, Observe that the constraints are small so you can use brute fo...
Python 3 | O(n)/O(1)
maximum-of-absolute-value-expression
0
1
```\nclass Solution:\n def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:\n minA = minB = minC = minD = math.inf\n maxA = maxB = maxC = maxD = -math.inf\n\n for i, (num1, num2) in enumerate(zip(arr1, arr2)):\n minA = min(minA, i + num1 + num2)\n maxA = max(ma...
2
Given two arrays of integers with equal lengths, return the maximum value of: `|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|` where the maximum is taken over all `0 <= i, j < arr1.length`. **Example 1:** **Input:** arr1 = \[1,2,3,4\], arr2 = \[-1,4,5,6\] **Output:** 13 **Example 2:** **Input:** arr1 = \[1,-...
What if we divide the string into substrings containing only one distinct character with maximal lengths? Now that you have sub-strings with only one distinct character, Try to come up with a formula that counts the number of its sub-strings. Alternatively, Observe that the constraints are small so you can use brute fo...
Python3: TC O(n) SC O(1), Very Clear with Derivation
maximum-of-absolute-value-expression
0
1
# Intuition\n\nIn simpler versions of this problem where you want the maximum difference, we can do the following:\n* rewrite the score of a pair in terms of `j` terms and `i` terms\n* for each `j`, compute the `j` terms\n* add/subtract the cumulative min/max of the `i` terms.\n\nIn this case the formula is more compli...
0
Given two arrays of integers with equal lengths, return the maximum value of: `|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|` where the maximum is taken over all `0 <= i, j < arr1.length`. **Example 1:** **Input:** arr1 = \[1,2,3,4\], arr2 = \[-1,4,5,6\] **Output:** 13 **Example 2:** **Input:** arr1 = \[1,-...
What if we divide the string into substrings containing only one distinct character with maximal lengths? Now that you have sub-strings with only one distinct character, Try to come up with a formula that counts the number of its sub-strings. Alternatively, Observe that the constraints are small so you can use brute fo...
Expansion
maximum-of-absolute-value-expression
0
1
# Intuition\nExpand the expression.\n\n# Approach\nRemove the mod and expand the expression, and check all possible expressions. Return the maximum value possible among all possible expressions.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$ \n\n# Code\n```\nclass Solution:\n def maxAbs...
0
Given two arrays of integers with equal lengths, return the maximum value of: `|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|` where the maximum is taken over all `0 <= i, j < arr1.length`. **Example 1:** **Input:** arr1 = \[1,2,3,4\], arr2 = \[-1,4,5,6\] **Output:** 13 **Example 2:** **Input:** arr1 = \[1,-...
What if we divide the string into substrings containing only one distinct character with maximal lengths? Now that you have sub-strings with only one distinct character, Try to come up with a formula that counts the number of its sub-strings. Alternatively, Observe that the constraints are small so you can use brute fo...
Python Elegant & Short | O(n) | 1-Pass
alphabet-board-path
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n MAPPING = {\n ltr: (i // 5, i % 5)\n for i, ltr in enumerate(ascii_lowercase)\n }\n\n def alphabetBoardPath(self, target: str) -> str:\n x, y = 0, 0\n path = \'\'\n\n for...
2
On an alphabet board, we start at position `(0, 0)`, corresponding to character `board[0][0]`. Here, `board = [ "abcde ", "fghij ", "klmno ", "pqrst ", "uvwxy ", "z "]`, as shown in the diagram below. We may make the following moves: * `'U'` moves our position up one row, if the position exists on the board; * `...
Say the store owner uses their power in minute 1 to X and we have some answer A. If they instead use their power from minute 2 to X+1, we only have to use data from minutes 1, 2, X and X+1 to update our answer A.
Python Elegant & Short | O(n) | 1-Pass
alphabet-board-path
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n MAPPING = {\n ltr: (i // 5, i % 5)\n for i, ltr in enumerate(ascii_lowercase)\n }\n\n def alphabetBoardPath(self, target: str) -> str:\n x, y = 0, 0\n path = \'\'\n\n for...
2
Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that : * `p[0] = start` * `p[i]` and `p[i+1]` differ by only one bit in their binary representation. * `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation. **Example 1:*...
Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board.
python || 7 lines, w/ comments || T/M: 95% / 99%
alphabet-board-path
0
1
```\nclass Solution:\n def alphabetBoardPath(self, target: str) -> str:\n \n rTrgt, cTrgt, ans = 0, 0, \'\' # <-- initialize some stuff\n f = lambda x: (abs(x)+x)//2 # <-- f returns the appropriate coefficient for\n ...
5
On an alphabet board, we start at position `(0, 0)`, corresponding to character `board[0][0]`. Here, `board = [ "abcde ", "fghij ", "klmno ", "pqrst ", "uvwxy ", "z "]`, as shown in the diagram below. We may make the following moves: * `'U'` moves our position up one row, if the position exists on the board; * `...
Say the store owner uses their power in minute 1 to X and we have some answer A. If they instead use their power from minute 2 to X+1, we only have to use data from minutes 1, 2, X and X+1 to update our answer A.
python || 7 lines, w/ comments || T/M: 95% / 99%
alphabet-board-path
0
1
```\nclass Solution:\n def alphabetBoardPath(self, target: str) -> str:\n \n rTrgt, cTrgt, ans = 0, 0, \'\' # <-- initialize some stuff\n f = lambda x: (abs(x)+x)//2 # <-- f returns the appropriate coefficient for\n ...
5
Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that : * `p[0] = start` * `p[i]` and `p[i+1]` differ by only one bit in their binary representation. * `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation. **Example 1:*...
Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board.
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9%
alphabet-board-path
0
1
\n# Code\n```\nclass Solution:\n def alphabetBoardPath(self, target: str) -> str:\n i = j = 0\n ans = []\n for c in target:\n diff = ord(c) - ord(\'a\')\n row, col = divmod(diff, 5)\n while i > row:\n i -= 1\n ans.append(\'U\')\n ...
1
On an alphabet board, we start at position `(0, 0)`, corresponding to character `board[0][0]`. Here, `board = [ "abcde ", "fghij ", "klmno ", "pqrst ", "uvwxy ", "z "]`, as shown in the diagram below. We may make the following moves: * `'U'` moves our position up one row, if the position exists on the board; * `...
Say the store owner uses their power in minute 1 to X and we have some answer A. If they instead use their power from minute 2 to X+1, we only have to use data from minutes 1, 2, X and X+1 to update our answer A.
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9%
alphabet-board-path
0
1
\n# Code\n```\nclass Solution:\n def alphabetBoardPath(self, target: str) -> str:\n i = j = 0\n ans = []\n for c in target:\n diff = ord(c) - ord(\'a\')\n row, col = divmod(diff, 5)\n while i > row:\n i -= 1\n ans.append(\'U\')\n ...
1
Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that : * `p[0] = start` * `p[i]` and `p[i+1]` differ by only one bit in their binary representation. * `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation. **Example 1:*...
Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board.
Python | O(N) | without BFS | Faster than 90% | Less space than 100%
alphabet-board-path
0
1
```\nclass Solution:\n def alphabetBoardPath(self, target: str):\n size = 5\n curx, cury = 0, 0\n offset = ord(\'a\')\n ans = \'\'\n \n for i in target:\n row = (ord(i)-offset)//size\n col = (ord(i)-offset)%size\n \n if curx > col:...
10
On an alphabet board, we start at position `(0, 0)`, corresponding to character `board[0][0]`. Here, `board = [ "abcde ", "fghij ", "klmno ", "pqrst ", "uvwxy ", "z "]`, as shown in the diagram below. We may make the following moves: * `'U'` moves our position up one row, if the position exists on the board; * `...
Say the store owner uses their power in minute 1 to X and we have some answer A. If they instead use their power from minute 2 to X+1, we only have to use data from minutes 1, 2, X and X+1 to update our answer A.
Python | O(N) | without BFS | Faster than 90% | Less space than 100%
alphabet-board-path
0
1
```\nclass Solution:\n def alphabetBoardPath(self, target: str):\n size = 5\n curx, cury = 0, 0\n offset = ord(\'a\')\n ans = \'\'\n \n for i in target:\n row = (ord(i)-offset)//size\n col = (ord(i)-offset)%size\n \n if curx > col:...
10
Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that : * `p[0] = start` * `p[i]` and `p[i+1]` differ by only one bit in their binary representation. * `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation. **Example 1:*...
Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board.
python runtime O(n) space O(n) using hash map
alphabet-board-path
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
On an alphabet board, we start at position `(0, 0)`, corresponding to character `board[0][0]`. Here, `board = [ "abcde ", "fghij ", "klmno ", "pqrst ", "uvwxy ", "z "]`, as shown in the diagram below. We may make the following moves: * `'U'` moves our position up one row, if the position exists on the board; * `...
Say the store owner uses their power in minute 1 to X and we have some answer A. If they instead use their power from minute 2 to X+1, we only have to use data from minutes 1, 2, X and X+1 to update our answer A.
python runtime O(n) space O(n) using hash map
alphabet-board-path
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 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that : * `p[0] = start` * `p[i]` and `p[i+1]` differ by only one bit in their binary representation. * `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation. **Example 1:*...
Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board.
✔ Python3 Solution | O(n * m * min(n, m))
largest-1-bordered-square
0
1
# Complexity\n- Time complexity: $$O(n * m * min(n, m))$$\n- Space complexity: $$O(n * m)$$\n\n# Code\n```\nclass Solution:\n def largest1BorderedSquare(self, A):\n n, m, ans = len(A), len(A[0]), 0\n H, V = [row[:] for row in A], [row[:] for row in A]\n for i in range(n):\n for j in r...
2
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
✔ Python3 Solution | O(n * m * min(n, m))
largest-1-bordered-square
0
1
# Complexity\n- Time complexity: $$O(n * m * min(n, m))$$\n- Space complexity: $$O(n * m)$$\n\n# Code\n```\nclass Solution:\n def largest1BorderedSquare(self, A):\n n, m, ans = len(A), len(A[0]), 0\n H, V = [row[:] for row in A], [row[:] for row in A]\n for i in range(n):\n for j in r...
2
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Python3: FT 100%: TC O(M^2 N), SC O(M N): Mostly DP with a Few Optimizations
largest-1-bordered-square
0
1
# Intuition\n\nFor most problems involving squares or sides in grids, we usually need to know the number of consecutive ones. We can do this with O(M N) DP.\n\nIn this case, 1-bordered squares mean we need to find cells with a specific number of consecutive 1s down and to the right. So we\'re probably on the right trac...
0
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
Python3: FT 100%: TC O(M^2 N), SC O(M N): Mostly DP with a Few Optimizations
largest-1-bordered-square
0
1
# Intuition\n\nFor most problems involving squares or sides in grids, we usually need to know the number of consecutive ones. We can do this with O(M N) DP.\n\nIn this case, 1-bordered squares mean we need to find cells with a specific number of consecutive 1s down and to the right. So we\'re probably on the right trac...
0
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
92% FASTER || BOTTOM-UP DP || count row, col
largest-1-bordered-square
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 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
92% FASTER || BOTTOM-UP DP || count row, col
largest-1-bordered-square
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Brute Force: O(N*M*min(N, M)^2), O(1)
largest-1-bordered-square
0
1
# Intuition\nJust write a brute force algorithm. Treat the start row and start col as the **top left edge** of the square, then search for 1ns on its sides until we have an invalid square. Kinda suprised this passed as this can be O(N^4)\n\n\n\n# Code\n### Time Complexity: $$O(N * M * min(N, M)^2)$$\n### Space Complexi...
0
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
Brute Force: O(N*M*min(N, M)^2), O(1)
largest-1-bordered-square
0
1
# Intuition\nJust write a brute force algorithm. Treat the start row and start col as the **top left edge** of the square, then search for 1ns on its sides until we have an invalid square. Kinda suprised this passed as this can be O(N^4)\n\n\n\n# Code\n### Time Complexity: $$O(N * M * min(N, M)^2)$$\n### Space Complexi...
0
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
[Python3] Prefix Sum Solution
largest-1-bordered-square
0
1
# Code\n```\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n horiPrefix = [[0 for j in range(n)] for i in range(m)]\n vertiPrefix = [[0 for j in range(n)] for i in range(m)]\n\n for i in range(m):\n ...
0
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
[Python3] Prefix Sum Solution
largest-1-bordered-square
0
1
# Code\n```\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n\n horiPrefix = [[0 for j in range(n)] for i in range(m)]\n vertiPrefix = [[0 for j in range(n)] for i in range(m)]\n\n for i in range(m):\n ...
0
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9%
largest-1-bordered-square
0
1
\n\n# Code\n```\nclass Solution:\n def largest1BorderedSquare(self, A):\n m, n = len(A), len(A[0])\n res = 0\n top, left = [a[:] for a in A], [a[:] for a in A]\n for i in range(m):\n for j in range(n):\n if A[i][j]:\n if i: top[i][j] = top[i - ...
0
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9%
largest-1-bordered-square
0
1
\n\n# Code\n```\nclass Solution:\n def largest1BorderedSquare(self, A):\n m, n = len(A), len(A[0])\n res = 0\n top, left = [a[:] for a in A], [a[:] for a in A]\n for i in range(m):\n for j in range(n):\n if A[i][j]:\n if i: top[i][j] = top[i - ...
0
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Python3 || Beats 100% || Easy Solution
largest-1-bordered-square
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 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
Python3 || Beats 100% || Easy Solution
largest-1-bordered-square
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Python Easy DP Solution
largest-1-bordered-square
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDynamic Programming should be used to calculate efficiently\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe initialise 2 DP grids, ```top``` and ```left``` to store number of 1s on top of the cell and on left of...
0
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
Python Easy DP Solution
largest-1-bordered-square
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDynamic Programming should be used to calculate efficiently\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe initialise 2 DP grids, ```top``` and ```left``` to store number of 1s on top of the cell and on left of...
0
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Python easy to read and understand | dp
largest-1-bordered-square
0
1
```\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n left = [[0 for _ in range(n)] for _ in range(m)]\n top = [[0 for _ in range(n)] for _ in range(m)]\n \n for i in range(m):\n for j in range...
0
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
Python easy to read and understand | dp
largest-1-bordered-square
0
1
```\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n left = [[0 for _ in range(n)] for _ in range(m)]\n top = [[0 for _ in range(n)] for _ in range(m)]\n \n for i in range(m):\n for j in range...
0
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Python (Simple DP)
largest-1-bordered-square
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 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
Python (Simple DP)
largest-1-bordered-square
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Python 3 | Prefix-sum, DP, O(N^3) | Explanation
largest-1-bordered-square
0
1
- Implementation as __*hint*__ section suggested\n- See below comments for more detail\n```\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n dp = [[(0, 0)] * (n) for _ in range((m))] \n for i in range(m): #...
3
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
Python 3 | Prefix-sum, DP, O(N^3) | Explanation
largest-1-bordered-square
0
1
- Implementation as __*hint*__ section suggested\n- See below comments for more detail\n```\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n dp = [[(0, 0)] * (n) for _ in range((m))] \n for i in range(m): #...
3
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
python, dp, faster than 98+%
largest-1-bordered-square
0
1
If anyone doesn\'t understand my solution, comment.\n![image](https://assets.leetcode.com/users/images/b1ba9f24-c30b-4b60-a6ef-2b96cb931e95_1623235285.7297766.png)\n```\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n \n width = len(grid[0])\n height = len(gri...
3
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`. **Example 1:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 9 **Example 2:** **Input:** grid = \[\[1,1,0,0...
You need to swap two values, one larger than the other. Where is the larger one located?
python, dp, faster than 98+%
largest-1-bordered-square
0
1
If anyone doesn\'t understand my solution, comment.\n![image](https://assets.leetcode.com/users/images/b1ba9f24-c30b-4b60-a6ef-2b96cb931e95_1623235285.7297766.png)\n```\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n \n width = len(grid[0])\n height = len(gri...
3
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ...
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
EASY PYTHON SOLUTION USING DP
stone-game-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)$$ --...
4
Alice and Bob continue their games with piles of stones. There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. Initially, `M = 1`. On each playe...
We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?
EASY PYTHON SOLUTION USING DP
stone-game-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)$$ --...
4
Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectangle. `2` (squares of `1x1`) `1` (square of `2x2`) **Example 2:** **Input:** n = 5, m =...
Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.
[Python3] See this post if you are frustrating with cryptic codes.
stone-game-ii
0
1
```\nfrom functools import cache\n\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n \n\t\t# Constants\n ALICE = 1 # To represent current turn.\n BOB = -1 # To represent current turn.\n N = len(piles)\n \n\t\t# Helpers\n @cache\n def max_piles_from(...
2
Alice and Bob continue their games with piles of stones. There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. Initially, `M = 1`. On each playe...
We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?
[Python3] See this post if you are frustrating with cryptic codes.
stone-game-ii
0
1
```\nfrom functools import cache\n\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n \n\t\t# Constants\n ALICE = 1 # To represent current turn.\n BOB = -1 # To represent current turn.\n N = len(piles)\n \n\t\t# Helpers\n @cache\n def max_piles_from(...
2
Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectangle. `2` (squares of `1x1`) `1` (square of `2x2`) **Example 2:** **Input:** n = 5, m =...
Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.
Python3 Solution
stone-game-ii
0
1
\n```\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n def dp(i,m):\n if (i,m) in memo:\n return memo[(i,m)]\n if i>n-1:\n return 0\n ans=-sys.maxsize\n if n-i<2*m:\n ans=pre_sum[n-1]-pre_sum[i-1]\n ...
1
Alice and Bob continue their games with piles of stones. There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. Initially, `M = 1`. On each playe...
We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?
Python3 Solution
stone-game-ii
0
1
\n```\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n def dp(i,m):\n if (i,m) in memo:\n return memo[(i,m)]\n if i>n-1:\n return 0\n ans=-sys.maxsize\n if n-i<2*m:\n ans=pre_sum[n-1]-pre_sum[i-1]\n ...
1
Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectangle. `2` (squares of `1x1`) `1` (square of `2x2`) **Example 2:** **Input:** n = 5, m =...
Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.
Beating 84.33% Python Easy Solution
stone-game-ii
0
1
![image.png](https://assets.leetcode.com/users/images/d3131b98-7823-4803-8845-b039fce14980_1685079502.8840265.png)\n\n# Code\n```\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n @lru_cache(None)\n def play(i, m):\n s = sum(piles[i:])\n if i + 2 * m >= len(pile...
1
Alice and Bob continue their games with piles of stones. There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. Initially, `M = 1`. On each playe...
We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?
Beating 84.33% Python Easy Solution
stone-game-ii
0
1
![image.png](https://assets.leetcode.com/users/images/d3131b98-7823-4803-8845-b039fce14980_1685079502.8840265.png)\n\n# Code\n```\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n @lru_cache(None)\n def play(i, m):\n s = sum(piles[i:])\n if i + 2 * m >= len(pile...
1
Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectangle. `2` (squares of `1x1`) `1` (square of `2x2`) **Example 2:** **Input:** n = 5, m =...
Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.
The best solutions you can find here 🦊 🚀
stone-game-ii
0
1
# Option 1:\n```\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n n = len(piles)\n\n @cache\n def dp(l, M=1):\n min_stones = left_stones = sum(piles[l:])\n \n R = min(l + 2*M, n) + 1\n for r in range(l+1, R):\n stones...
3
Alice and Bob continue their games with piles of stones. There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. Initially, `M = 1`. On each playe...
We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?
The best solutions you can find here 🦊 🚀
stone-game-ii
0
1
# Option 1:\n```\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n n = len(piles)\n\n @cache\n def dp(l, M=1):\n min_stones = left_stones = sum(piles[l:])\n \n R = min(l + 2*M, n) + 1\n for r in range(l+1, R):\n stones...
3
Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectangle. `2` (squares of `1x1`) `1` (square of `2x2`) **Example 2:** **Input:** n = 5, m =...
Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.
Image Explanation🏆- [Recursion Tree] [Recursion->Memo->Bottom Up + Suffix Sums] - C++/Java/Python
stone-game-ii
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Stone Game II` by `Aryan Mittal`\n![lc.png](https://assets.leetcode.com/users/images/2441a610-e666-470f-9e6e-bf978fd40c43_1685070892.2972043.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/users/images/997041e7-0b32-4905-9f3d-39fbe...
64
Alice and Bob continue their games with piles of stones. There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. Initially, `M = 1`. On each playe...
We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?
Image Explanation🏆- [Recursion Tree] [Recursion->Memo->Bottom Up + Suffix Sums] - C++/Java/Python
stone-game-ii
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Stone Game II` by `Aryan Mittal`\n![lc.png](https://assets.leetcode.com/users/images/2441a610-e666-470f-9e6e-bf978fd40c43_1685070892.2972043.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/users/images/997041e7-0b32-4905-9f3d-39fbe...
64
Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectangle. `2` (squares of `1x1`) `1` (square of `2x2`) **Example 2:** **Input:** n = 5, m =...
Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.
Python short and clean. Functional programming.
stone-game-ii
0
1
# Approach: Recursive DP\n\n# Complexity\n- Time complexity: $$O(n ^ 3)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\nwhere, `n is number of piles.`\n\n# Code\n```python\nclass Solution:\n def stoneGameII(self, piles: list[int]) -> int:\n suffix_sums = tuple(reversed(tuple(accumulate(reversed(piles)))))\n\n ...
2
Alice and Bob continue their games with piles of stones. There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. Initially, `M = 1`. On each playe...
We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?
Python short and clean. Functional programming.
stone-game-ii
0
1
# Approach: Recursive DP\n\n# Complexity\n- Time complexity: $$O(n ^ 3)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\nwhere, `n is number of piles.`\n\n# Code\n```python\nclass Solution:\n def stoneGameII(self, piles: list[int]) -> int:\n suffix_sums = tuple(reversed(tuple(accumulate(reversed(piles)))))\n\n ...
2
Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectangle. `2` (squares of `1x1`) `1` (square of `2x2`) **Example 2:** **Input:** n = 5, m =...
Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.
[python] DP Thought process explained
stone-game-ii
0
1
This was a really tough problem for me. It is so easy in the end when you got the idea, but it was pretty hard to get there (at least for me). So I\'m going to share here how I\'ve got to the optimal bottom-up DP solution for this task.\n\nThe first step was to write the straightforward top-down solution.\nThe basic id...
43
Alice and Bob continue their games with piles of stones. There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. Initially, `M = 1`. On each playe...
We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?
[python] DP Thought process explained
stone-game-ii
0
1
This was a really tough problem for me. It is so easy in the end when you got the idea, but it was pretty hard to get there (at least for me). So I\'m going to share here how I\'ve got to the optimal bottom-up DP solution for this task.\n\nThe first step was to write the straightforward top-down solution.\nThe basic id...
43
Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectangle. `2` (squares of `1x1`) `1` (square of `2x2`) **Example 2:** **Input:** n = 5, m =...
Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m.