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
Z algorithm
sum-of-scores-of-built-strings
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 **building** a string `s` of length `n` **one** character at a time, **prepending** each new character to the **front** of the string. The strings are labeled from `1` to `n`, where the string with length `i` is labeled `si`. * For example, for `s = "abaca "`, `s1 == "a "`, `s2 == "ca "`, `s3 == "aca "`, etc...
null
prefix arr and binary search with no additional spaces
sum-of-scores-of-built-strings
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 **building** a string `s` of length `n` **one** character at a time, **prepending** each new character to the **front** of the string. The strings are labeled from `1` to `n`, where the string with length `i` is labeled `si`. * For example, for `s = "abaca "`, `s1 == "a "`, `s2 == "ca "`, `s3 == "aca "`, etc...
null
Python (Simple KMP)
sum-of-scores-of-built-strings
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 **building** a string `s` of length `n` **one** character at a time, **prepending** each new character to the **front** of the string. The strings are labeled from `1` to `n`, where the string with length `i` is labeled `si`. * For example, for `s = "abaca "`, `s1 == "a "`, `s2 == "ca "`, `s3 == "aca "`, etc...
null
Fully annotated Z algorithm Python Solution
sum-of-scores-of-built-strings
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 **building** a string `s` of length `n` **one** character at a time, **prepending** each new character to the **front** of the string. The strings are labeled from `1` to `n`, where the string with length `i` is labeled `si`. * For example, for `s = "abaca "`, `s1 == "a "`, `s2 == "ca "`, `s3 == "aca "`, etc...
null
Python solution | KMP-prefix | Z-function
sum-of-scores-of-built-strings
0
1
# Approach 1\n<!-- Describe your approach to solving the problem. -->\nKMP-prefix computation\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sumSc...
0
You are **building** a string `s` of length `n` **one** character at a time, **prepending** each new character to the **front** of the string. The strings are labeled from `1` to `n`, where the string with length `i` is labeled `si`. * For example, for `s = "abaca "`, `s1 == "a "`, `s2 == "ca "`, `s3 == "aca "`, etc...
null
⭐Easy Python Solution | Convert time to minutes
minimum-number-of-operations-to-convert-time
0
1
1. Convert times into minutes and then the problem becomes simpler. \n2. To minimize the number of total operations we try to use the largest possible change from `[60,15,5,1]` till possible.\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n current_time = 60 * int(current[0:...
35
You are given two strings `current` and `correct` representing two **24-hour times**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. In one operation you can increase the time `current`...
null
🔥[Python 3] Convert to minutes and find parts using divmod, beats 85%
minimum-number-of-operations-to-convert-time
0
1
```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n def toMinutes(s):\n h, m = s.split(\':\')\n return 60 * int(h) + int(m)\n \n minutes = toMinutes(correct) - toMinutes(current)\n hours, minutes = divmod(minutes, 60)\n quaters, ...
5
You are given two strings `current` and `correct` representing two **24-hour times**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. In one operation you can increase the time `current`...
null
Python convert to minutes
minimum-number-of-operations-to-convert-time
0
1
```\ndef convertTime(self, current: str, correct: str) -> int:\n\tans = 0\n\th, m = list(map(int, current.split(\':\')))\n\tnewH, newM = list(map(int, correct.split(\':\')))\n\td = 60*(newH - h) + newM - m\n\tfor x in [60, 15, 5, 1]:\n\t\tans += d//x\n\t\td %= x\n\treturn ans \n```
4
You are given two strings `current` and `correct` representing two **24-hour times**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. In one operation you can increase the time `current`...
null
Beat 99.29% 22ms Python3 easy solution
minimum-number-of-operations-to-convert-time
0
1
\n# Code\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n current, correct = current.replace(\':\',\'\'), correct.replace(\':\',\'\')\n a, count = (int(correct[:2]) * 60 + int(correct[2:])) - (int(current[:2]) * 60 + int(current[2:])), 0\n for i in [60, 15, 5, ...
2
You are given two strings `current` and `correct` representing two **24-hour times**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. In one operation you can increase the time `current`...
null
Python O(1) Time
minimum-number-of-operations-to-convert-time
0
1
```\nclass Solution:\n def convertTime(self, s: str, c: str) -> int:\n dif=(int(c[:2])*60+int(c[3:]))-(int(s[:2])*60+int(s[3:]))\n count=0\n print(dif)\n arr=[60,15,5,1]\n for x in arr:\n count+=dif//x\n dif=dif%x\n return count
3
You are given two strings `current` and `correct` representing two **24-hour times**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. In one operation you can increase the time `current`...
null
dictionary does the job
find-players-with-zero-or-one-losses
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)$$ --...
6
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
dictionary does the job
find-players-with-zero-or-one-losses
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)$$ --...
6
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
Most space optimized python solution
find-players-with-zero-or-one-losses
0
1
```\nfrom collections import defaultdict\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n dct=defaultdict(lambda :[0,0])\n for p1,p2 in matches:\n dct[p1][0]+=1\n dct[p1][1]+=1\n dct[p2][0]+=1\n wonAll=[]\n lossOne=[...
5
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
Most space optimized python solution
find-players-with-zero-or-one-losses
0
1
```\nfrom collections import defaultdict\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n dct=defaultdict(lambda :[0,0])\n for p1,p2 in matches:\n dct[p1][0]+=1\n dct[p1][1]+=1\n dct[p2][0]+=1\n wonAll=[]\n lossOne=[...
5
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
Python in 2 lines
find-players-with-zero-or-one-losses
0
1
\n```\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n win, lose = zip(*matches)\n return [sorted(set(win) - set(lose)), sorted(k for k, v in Counter(lose).items() if v == 1)]\n```
4
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
Python in 2 lines
find-players-with-zero-or-one-losses
0
1
\n```\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n win, lose = zip(*matches)\n return [sorted(set(win) - set(lose)), sorted(k for k, v in Counter(lose).items() if v == 1)]\n```
4
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
Easy Python Solution
find-players-with-zero-or-one-losses
0
1
# Code\n```\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n win=[]\n lose=[]\n for i in matches:\n win.append(i[0])\n lose.append(i[1])\n l=[] #0 lose\n m=[] #1 lose\n c=Counter(lose)\n for i in range(len(...
2
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
Easy Python Solution
find-players-with-zero-or-one-losses
0
1
# Code\n```\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n win=[]\n lose=[]\n for i in matches:\n win.append(i[0])\n lose.append(i[1])\n l=[] #0 lose\n m=[] #1 lose\n c=Counter(lose)\n for i in range(len(...
2
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
Beats 99% | python | hashmap
find-players-with-zero-or-one-losses
0
1
\n\n# Code\n```\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n d = {}\n for i in matches:\n if i[1] in d:\n d[i[1]] +=1\n else:\n d[i[1]] = 1\n a,b =set(),[]\n\n for i in matches:\n if...
1
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
Beats 99% | python | hashmap
find-players-with-zero-or-one-losses
0
1
\n\n# Code\n```\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n d = {}\n for i in matches:\n if i[1] in d:\n d[i[1]] +=1\n else:\n d[i[1]] = 1\n a,b =set(),[]\n\n for i in matches:\n if...
1
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
Python one liner (maybe some fooling around involved :P)
find-players-with-zero-or-one-losses
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst I tried to solve it with a hashmap to count the winners and loosers. Later I tried to solve it with a one-liner, which is actually not as readable as my original solution, but I want to post it anyway. :)\n\nHere are some explanatio...
1
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
Python one liner (maybe some fooling around involved :P)
find-players-with-zero-or-one-losses
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst I tried to solve it with a hashmap to count the winners and loosers. Later I tried to solve it with a one-liner, which is actually not as readable as my original solution, but I want to post it anyway. :)\n\nHere are some explanatio...
1
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
PYTHON | Hashmap and Set
find-players-with-zero-or-one-losses
0
1
Keep the loosers loosing count in hashmap , if player belongs to looser set then player must have lost exactly one match if not remove the player from looser set ( maybe lost 2 or more matches ) , if player belongs to winner set he will mot be in hashmap so add him to winner set if adding any looser in winner set remov...
1
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
PYTHON | Hashmap and Set
find-players-with-zero-or-one-losses
0
1
Keep the loosers loosing count in hashmap , if player belongs to looser set then player must have lost exactly one match if not remove the player from looser set ( maybe lost 2 or more matches ) , if player belongs to winner set he will mot be in hashmap so add him to winner set if adding any looser in winner set remov...
1
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
Identifying Players by Match Outcomes
find-players-with-zero-or-one-losses
0
1
# Intuition\nThe goal of this code is to find the players who have lost lost once or less in a given list of matches.\n\n# Approach\nThe approach taken by the code is as follows:\n\n1. Initialize a dictionary `loss` to store the number of losses for each player, and an empty list `res` to store the players who have won...
1
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
Identifying Players by Match Outcomes
find-players-with-zero-or-one-losses
0
1
# Intuition\nThe goal of this code is to find the players who have lost lost once or less in a given list of matches.\n\n# Approach\nThe approach taken by the code is as follows:\n\n1. Initialize a dictionary `loss` to store the number of losses for each player, and an empty list `res` to store the players who have won...
1
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
✔Python3 | Dictionary | Hashmap | Concise | easy-understanding 🔥
find-players-with-zero-or-one-losses
0
1
# Approach\n* Traverse the array and store the loss count in a Dictionary for each player\n* Traverse the dictionary and store the players with Zero value in one list and One value in another list\n* Sort these lists and put them in a single list to return the expected answer\n# Code\n```\nclass Solution:\n def find...
1
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
✔Python3 | Dictionary | Hashmap | Concise | easy-understanding 🔥
find-players-with-zero-or-one-losses
0
1
# Approach\n* Traverse the array and store the loss count in a Dictionary for each player\n* Traverse the dictionary and store the players with Zero value in one list and One value in another list\n* Sort these lists and put them in a single list to return the expected answer\n# Code\n```\nclass Solution:\n def find...
1
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
Python using Hashmap
find-players-with-zero-or-one-losses
0
1
\n# Code\n```\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n count = {}\n for match in matches:\n if match[0] not in count.keys():\n count[match[0]] = [1]\n else:\n count[match[0]].append(1)\n if ma...
1
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
Python using Hashmap
find-players-with-zero-or-one-losses
0
1
\n# Code\n```\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n count = {}\n for match in matches:\n if match[0] not in count.keys():\n count[match[0]] = [1]\n else:\n count[match[0]].append(1)\n if ma...
1
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
Only using Simple Set Operations | Easy Solution | Python
find-players-with-zero-or-one-losses
0
1
```\n#thanks to the legend who gave me an upvote :D, cuz that\'s my first one\nclass Solution(object):\n def findWinners(self, matches):\n """\n :type matches: List[List[int]]\n :rtype: List[List[int]]\n """\n win=set()\n loss=set()\n twicelost=set()\n for i in...
1
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
Only using Simple Set Operations | Easy Solution | Python
find-players-with-zero-or-one-losses
0
1
```\n#thanks to the legend who gave me an upvote :D, cuz that\'s my first one\nclass Solution(object):\n def findWinners(self, matches):\n """\n :type matches: List[List[int]]\n :rtype: List[List[int]]\n """\n win=set()\n loss=set()\n twicelost=set()\n for i in...
1
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
[ Python ] ✅✅ Simple Python Solution Using HashMap | Dictionary 🥳✌👍
find-players-with-zero-or-one-losses
0
1
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 2054 ms, faster than 84.05% of Python3 online submissions for Find Players With Zero or One Losses.\n# Memory Usage: 68.7 MB, less than 77.41% of Python3 online submissions for Find Players With Zero or One Losse...
1
You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match. Return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` is a list of all players that have **not** lost any matches. * `answer[1]` is a list of all players...
In the string "abacad", the letter "a" appears 3 times. How many substrings begin with the first "a" and end with any "a"? There are 3 substrings ("a", "aba", and "abaca"). How many substrings begin with the second "a" and end with any "a"? How about the third? 2 substrings begin with the second "a" ("a", and "aca") an...
[ Python ] ✅✅ Simple Python Solution Using HashMap | Dictionary 🥳✌👍
find-players-with-zero-or-one-losses
0
1
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 2054 ms, faster than 84.05% of Python3 online submissions for Find Players With Zero or One Losses.\n# Memory Usage: 68.7 MB, less than 77.41% of Python3 online submissions for Find Players With Zero or One Losse...
1
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
[Python] Hashmap & Counter Solution with Detailed Explanations, Very Clean & Concise
encrypt-and-decrypt-strings
0
1
This is the first time I get AK over the past few months. I would like to share my solution with the LC community.\n\n**Intuition**\nThe given constraints are not large, we can pre-compute all necessary quantities only once.\n\n\n**Explanation**\nWe can pre-compute two hashmaps as follows:\n\n(1) The first hashmap `sel...
26
You are given a character array `keys` containing **unique** characters and a string array `values` containing strings of length 2. You are also given another string array `dictionary` that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a **0-...
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
[Python] Hashmap & Counter Solution with Detailed Explanations, Very Clean & Concise
encrypt-and-decrypt-strings
0
1
This is the first time I get AK over the past few months. I would like to share my solution with the LC community.\n\n**Intuition**\nThe given constraints are not large, we can pre-compute all necessary quantities only once.\n\n\n**Explanation**\nWe can pre-compute two hashmaps as follows:\n\n(1) The first hashmap `sel...
26
Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa. A string `x` can break string `y` (both of size `n`) if `x[i] >= y[i]` (in alphabetical order) for all `i` between `0`...
For encryption, use hashmap to map each char of word1 to its value. For decryption, use trie to prune when necessary.
Two Hashmaps, pay attention when a letter is not present in keys
encrypt-and-decrypt-strings
0
1
I gotta say this is not a very clean and hard enough hard question\n# Code\n```\nclass Encrypter:\n\n def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):\n self.reflection = {k:v for k,v in zip(keys,values)}\n for a in \'abcdefghijklmnopqrstuvwxyz\':\n if a not in ...
0
You are given a character array `keys` containing **unique** characters and a string array `values` containing strings of length 2. You are also given another string array `dictionary` that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a **0-...
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
Two Hashmaps, pay attention when a letter is not present in keys
encrypt-and-decrypt-strings
0
1
I gotta say this is not a very clean and hard enough hard question\n# Code\n```\nclass Encrypter:\n\n def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):\n self.reflection = {k:v for k,v in zip(keys,values)}\n for a in \'abcdefghijklmnopqrstuvwxyz\':\n if a not in ...
0
Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa. A string `x` can break string `y` (both of size `n`) if `x[i] >= y[i]` (in alphabetical order) for all `i` between `0`...
For encryption, use hashmap to map each char of word1 to its value. For decryption, use trie to prune when necessary.
Python Simple solution beats 96.92%
encrypt-and-decrypt-strings
0
1
# Code\n```\nclass Encrypter:\n def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):\n self.key2value={}\n for k,v in zip(keys,values):\n self.key2value[k]=v\n self.dictionary=Counter()\n for d in dictionary:\n self.dictionary[self.encrypt(d...
0
You are given a character array `keys` containing **unique** characters and a string array `values` containing strings of length 2. You are also given another string array `dictionary` that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a **0-...
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
Python Simple solution beats 96.92%
encrypt-and-decrypt-strings
0
1
# Code\n```\nclass Encrypter:\n def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):\n self.key2value={}\n for k,v in zip(keys,values):\n self.key2value[k]=v\n self.dictionary=Counter()\n for d in dictionary:\n self.dictionary[self.encrypt(d...
0
Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa. A string `x` can break string `y` (both of size `n`) if `x[i] >= y[i]` (in alphabetical order) for all `i` between `0`...
For encryption, use hashmap to map each char of word1 to its value. For decryption, use trie to prune when necessary.
python3 | HashMap solution
encrypt-and-decrypt-strings
0
1
\n# Code\n```\nclass Encrypter:\n\n def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):\n self.mapping = {}\n self.countDict = defaultdict(int)\n for i in range(len(keys)):\n self.mapping[keys[i]]=values[i]\n for key in dictionary:\n self.c...
0
You are given a character array `keys` containing **unique** characters and a string array `values` containing strings of length 2. You are also given another string array `dictionary` that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a **0-...
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
python3 | HashMap solution
encrypt-and-decrypt-strings
0
1
\n# Code\n```\nclass Encrypter:\n\n def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):\n self.mapping = {}\n self.countDict = defaultdict(int)\n for i in range(len(keys)):\n self.mapping[keys[i]]=values[i]\n for key in dictionary:\n self.c...
0
Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa. A string `x` can break string `y` (both of size `n`) if `x[i] >= y[i]` (in alphabetical order) for all `i` between `0`...
For encryption, use hashmap to map each char of word1 to its value. For decryption, use trie to prune when necessary.
Python (Simple Hashmap)
encrypt-and-decrypt-strings
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 a character array `keys` containing **unique** characters and a string array `values` containing strings of length 2. You are also given another string array `dictionary` that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a **0-...
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
Python (Simple Hashmap)
encrypt-and-decrypt-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa. A string `x` can break string `y` (both of size `n`) if `x[i] >= y[i]` (in alphabetical order) for all `i` between `0`...
For encryption, use hashmap to map each char of word1 to its value. For decryption, use trie to prune when necessary.
max heap || easy
largest-number-after-digit-swaps-by-parity
0
1
\n\n# Code\n```\nclass Solution:\n def largestInteger(self, num: int) -> int:\n evenlist=[]\n oddlist=[]\n nums= [int(x) for x in str(num)]\n for i in nums:\n if i%2==0:\n evenlist.append(i)\n else:\n oddlist.append(i)\n even= [-x...
1
You are given a positive integer `num`. You may swap any two digits of `num` that have the same **parity** (i.e. both odd digits or both even digits). Return _the **largest** possible value of_ `num` _after **any** number of swaps._ **Example 1:** **Input:** num = 1234 **Output:** 3412 **Explanation:** Swap the digi...
Iterate through the elements in order. As soon as the current element is a palindrome, return it. To check if an element is a palindrome, can you reverse the string?
Python Solution using Sorting
largest-number-after-digit-swaps-by-parity
0
1
Since we need the largest number, what we want is basically to have the larger digits upfront and then the smaller ones. But we are given a parity condition that we need to comply to. We are allowed to swap odd digits with odd ones and even with even ones. So we simply maintain two arrays with odd and even digits. The ...
25
You are given a positive integer `num`. You may swap any two digits of `num` that have the same **parity** (i.e. both odd digits or both even digits). Return _the **largest** possible value of_ `num` _after **any** number of swaps._ **Example 1:** **Input:** num = 1234 **Output:** 3412 **Explanation:** Swap the digi...
Iterate through the elements in order. As soon as the current element is a palindrome, return it. To check if an element is a palindrome, can you reverse the string?
Python easy solution using heap | faster than 99%
largest-number-after-digit-swaps-by-parity
0
1
\nI have maintained two heaps: `odd_x` and `even_x`\nIf number is odd push into `odd_x` else push into`even_x`, also I am adding true (wherever odd number is encountered) so that its easy to track positions of odd numbers\n\nFor generating ans, I am popping out highest odd number for positions using heap where odd numb...
3
You are given a positive integer `num`. You may swap any two digits of `num` that have the same **parity** (i.e. both odd digits or both even digits). Return _the **largest** possible value of_ `num` _after **any** number of swaps._ **Example 1:** **Input:** num = 1234 **Output:** 3412 **Explanation:** Swap the digi...
Iterate through the elements in order. As soon as the current element is a palindrome, return it. To check if an element is a palindrome, can you reverse the string?
Python Solution using 2 Pointers Brute Force
minimize-result-by-adding-parentheses-to-expression
0
1
*Since the given maximum size is only 10, we can easily cover all possible options without TLE. Thus we use 2 pointers to cover all options.*\n\n**STEPS**\n1. Traverse two pointers `l` & `r`. **L** pointer goes from 0 to **plus_index** and **R** pointer goes from **plus_index+1** to **N**. **plus_index** is the index o...
16
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers. Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis *...
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for th...
Python 3 || 5 lines, w/ example || T/M: 82%/99%
minimize-result-by-adding-parentheses-to-expression
0
1
```\nclass Solution:\n def minimizeResult(self, expression: str) -> str: # Example: "247+38" \n # left, right = "247","38"\n left, right = expression.split(\'+\') \n value = lambda ...
5
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers. Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis *...
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for th...
Python | Intuitive method
minimize-result-by-adding-parentheses-to-expression
0
1
# Intuition\nJust split the string into three parts: \n- left before \'(\'\n- middle in the parenthisis\n- right after \')\'.\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(N^2)\n\n# Code\n```\nclass Solution:\n def minimizeResult(self, expression: str) -> str:\n n = len(expression)\n ...
0
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers. Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis *...
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for th...
Python | Brute Force
minimize-result-by-adding-parentheses-to-expression
0
1
# Code\n```\nclass Solution:\n def minimizeResult(self, e: str) -> str:\n lft, rgt = e.split("+")\n mi = inf\n for l in range(len(lft)):\n for r in range(1, len(rgt) + 1):\n cur = int(lft[:l] or 1) * (int(lft[l:]) + int(rgt[:r])) * int(rgt[r:] or 1)\n if ...
0
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers. Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis *...
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for th...
minimize-result-by-adding-parentheses-to-expression
minimize-result-by-adding-parentheses-to-expression
0
1
# Code\n```\nclass Solution:\n def minimizeResult(self, e: str) -> str:\n p = []\n b = e.split("+")\n p.append([int(b[0]) + int(b[1]),"(" + e + ")"]) \n for i in range(len(b[0])):\n a = b[0][:i]\n if len(a)>0:\n h = int(a)* (int(b[0][i:]) + int(...
0
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers. Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis *...
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for th...
Brute force Python solution, beats 100% runtime
minimize-result-by-adding-parentheses-to-expression
0
1
# Intuition\nBrute force\n\n# Approach\nIterate through all possible left and right parenthesis positions and remember when the value is the smallest.\n\nWe could bring down the complexity to $$O(n^2)$$ by keeping track of the current values inside the parentheses and calculating the impact of moving the parenthesis le...
0
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers. Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis *...
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for th...
python bruteforce
minimize-result-by-adding-parentheses-to-expression
0
1
```\nclass Solution:\n def minimizeResult(self, expression: str) -> str:\n n,_,m = map(len, expression.partition(\'+\'))\n solved = \'\'\n res = inf\n for i in range(n):\n for j in range(1, m+1):\n if int(expression[:i] or \'1\')*eval(expression[i:n+j+1])*int(exp...
0
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers. Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis *...
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for th...
Beats 91.27% Runtime
minimize-result-by-adding-parentheses-to-expression
0
1
# Approach\nSplit the expression by `+` to simplify indexing. Left bracket can be placed at `l_idx` from `0` to `l_num - 1`. Right bracket can be placed at `r_idx` from `1` to `r_num`. Edge cases at ends can have the default value as `1` using `or`. Intuitive and straightforward solution.\n\n# Code\n```\nclass Solution...
0
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers. Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis *...
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for th...
Easy Python Solution
minimize-result-by-adding-parentheses-to-expression
0
1
# Code\n```\nclass Solution:\n def minimizeResult(self, expression: str) -> str:\n s=expression.split("+") #s=[\'247\',\'38\']\n left,right=list(s[0]),list(s[1])\n len_left,len_right=len(list(left)),len(list(right))\n res_left,res_right,res=[],[],float(\'inf\')\n for i in range...
0
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers. Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis *...
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for th...
Python solution without using heaps
maximum-product-after-k-increments
0
1
# Intuition\nOnly dictionaries are used in approach to increment the smallest number and calculate the maximum product\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(max(N,K))\n- Space complexity:\nO(N) {Dictionary}\n\n# Code\n```\nclass Solution:\n def ...
2
You are given an array of non-negative integers `nums` and an integer `k`. In one operation, you may choose **any** element from `nums` and **increment** it by `1`. Return _the **maximum** **product** of_ `nums` _after **at most**_ `k` _operations._ Since the answer may be very large, return it **modulo** `109 + 7`. N...
Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6]. Think of a 2-pointer approach to traverse the array and find each longest possible period. Suppose you found the longest possible period with a length of k. How many periods are within that pe...
Python | Min heap | Priority Queue
maximum-product-after-k-increments
0
1
\n def maximumProduct(self, nums: List[int], k: int) -> int:\n heapify(nums)\n for i in range(k):\n heappush(nums, heappop(nums)+1) \n result = 1\n for i in nums:\n result *= i\n result %= 10**9 + 7\n return result
1
You are given an array of non-negative integers `nums` and an integer `k`. In one operation, you may choose **any** element from `nums` and **increment** it by `1`. Return _the **maximum** **product** of_ `nums` _after **at most**_ `k` _operations._ Since the answer may be very large, return it **modulo** `109 + 7`. N...
Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6]. Think of a 2-pointer approach to traverse the array and find each longest possible period. Suppose you found the longest possible period with a length of k. How many periods are within that pe...
[Python3] semi-math greedy solution
maximum-product-after-k-increments
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/af907302ab84ad94ecb97eeeb9b0bfa529041e30) for solutions of weekly 288. \n\n```\nclass Solution:\n def maximumProduct(self, nums: List[int], k: int) -> int:\n mod = 1_000_000_007\n nums.sort()\n for i, x in enumerate(nums): \...
1
You are given an array of non-negative integers `nums` and an integer `k`. In one operation, you may choose **any** element from `nums` and **increment** it by `1`. Return _the **maximum** **product** of_ `nums` _after **at most**_ `k` _operations._ Since the answer may be very large, return it **modulo** `109 + 7`. N...
Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6]. Think of a 2-pointer approach to traverse the array and find each longest possible period. Suppose you found the longest possible period with a length of k. How many periods are within that pe...
[Python 3] Simple interface, Explained — O(NlogN), O(1)
maximum-total-beauty-of-the-gardens
0
1
# Intuition\nWe can forget about gardens that are originally complete, because we can\'t change their state. Let\'s assume that we don\'t have such gardens, then:\n* There are actually only $N+1$ candidates for an answer:\n\n 1 \u2014 $0$ complete gardens and $N$ incomplete gardens (with maximized minimum amount of fl...
1
Alice is a caretaker of `n` gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a **0-indexed** integer array `flowers` of size `n`, where `flowers[i]` is the number of flowers already planted in the `ith` garden. Flowers that are already planted **cannot** be removed....
Can we divide the array into non-overlapping subsequences and simplify the problem? In the final array, arr[i-k] ≤ arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence. Now our problem boils down to performing the minimum oper...
[Python3] 2-pointer
maximum-total-beauty-of-the-gardens
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/af907302ab84ad94ecb97eeeb9b0bfa529041e30) for solutions of weekly 288. \n\n```\nclass Solution:\n def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:\n flowers = sorted(min(target, x)...
1
Alice is a caretaker of `n` gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a **0-indexed** integer array `flowers` of size `n`, where `flowers[i]` is the number of flowers already planted in the `ith` garden. Flowers that are already planted **cannot** be removed....
Can we divide the array into non-overlapping subsequences and simplify the problem? In the final array, arr[i-k] ≤ arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence. Now our problem boils down to performing the minimum oper...
Python3 with comments
maximum-total-beauty-of-the-gardens
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- We will sort the gardens to have the small values in front and big values in the end.\n- We will first remove as many full gardens as possible.\n- We will then spend all the remaining newFlowers to increase the minimum\n- ...
0
Alice is a caretaker of `n` gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a **0-indexed** integer array `flowers` of size `n`, where `flowers[i]` is the number of flowers already planted in the `ith` garden. Flowers that are already planted **cannot** be removed....
Can we divide the array into non-overlapping subsequences and simplify the problem? In the final array, arr[i-k] ≤ arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence. Now our problem boils down to performing the minimum oper...
Python3 fast solution
maximum-total-beauty-of-the-gardens
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 log n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $...
0
Alice is a caretaker of `n` gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a **0-indexed** integer array `flowers` of size `n`, where `flowers[i]` is the number of flowers already planted in the `ith` garden. Flowers that are already planted **cannot** be removed....
Can we divide the array into non-overlapping subsequences and simplify the problem? In the final array, arr[i-k] ≤ arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence. Now our problem boils down to performing the minimum oper...
[Python] Prefix sum with binary search O(NlogN) + intuition explained
maximum-total-beauty-of-the-gardens
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition would be first sort the array, since the position of the garden doesn\'t matter.\n\nThen we consider the following:\n## Do we binary search the maximum score?\n - After some thinking, determine whether a value can be achieved i...
0
Alice is a caretaker of `n` gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a **0-indexed** integer array `flowers` of size `n`, where `flowers[i]` is the number of flowers already planted in the `ith` garden. Flowers that are already planted **cannot** be removed....
Can we divide the array into non-overlapping subsequences and simplify the problem? In the final array, arr[i-k] ≤ arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence. Now our problem boils down to performing the minimum oper...
My most difficult problem that Leedcode has solved 😂😂
add-two-integers
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
Given two integers `num1` and `num2`, return _the **sum** of the two integers_. **Example 1:** **Input:** num1 = 12, num2 = 5 **Output:** 17 **Explanation:** num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. **Example 2:** **Input:** num1 = -10, num2 = 4 **Output:** -6 **Explanation:** num1 + ...
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
Simple Integer Addition using Python
add-two-integers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to calculate and return the sum of two integers, which can be done using the \'+\' operator in Python.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOur approach is simple: we will use the \'+\' operator ...
4
Given two integers `num1` and `num2`, return _the **sum** of the two integers_. **Example 1:** **Input:** num1 = 12, num2 = 5 **Output:** 17 **Explanation:** num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. **Example 2:** **Input:** num1 = -10, num2 = 4 **Output:** -6 **Explanation:** num1 + ...
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
One line solution of add two Integers problem
add-two-integers
0
1
# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n```
1
Given two integers `num1` and `num2`, return _the **sum** of the two integers_. **Example 1:** **Input:** num1 = 12, num2 = 5 **Output:** 17 **Explanation:** num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. **Example 2:** **Input:** num1 = -10, num2 = 4 **Output:** -6 **Explanation:** num1 + ...
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
Python simple solution
add-two-integers
0
1
# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n```
8
Given two integers `num1` and `num2`, return _the **sum** of the two integers_. **Example 1:** **Input:** num1 = 12, num2 = 5 **Output:** 17 **Explanation:** num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. **Example 2:** **Input:** num1 = -10, num2 = 4 **Output:** -6 **Explanation:** num1 + ...
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
Python simple solution
add-two-integers
0
1
**There\u2019s nothing to write on it write a recipe for pancakes**\n\n# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n \n```\n\n**Pancake Ingredients**\nYou likely already have everything you need to make this pancake recipe. If not, here\'s what to add...
12
Given two integers `num1` and `num2`, return _the **sum** of the two integers_. **Example 1:** **Input:** num1 = 12, num2 = 5 **Output:** 17 **Explanation:** num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. **Example 2:** **Input:** num1 = -10, num2 = 4 **Output:** -6 **Explanation:** num1 + ...
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
Python using list
add-two-integers
0
1
\n\n# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return sum([num1, num2])\n```
2
Given two integers `num1` and `num2`, return _the **sum** of the two integers_. **Example 1:** **Input:** num1 = 12, num2 = 5 **Output:** 17 **Explanation:** num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. **Example 2:** **Input:** num1 = -10, num2 = 4 **Output:** -6 **Explanation:** num1 + ...
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
Solutions in Every Language *on leetcode* | One-Liner ✅
add-two-integers
1
1
**1. C++**\n```\nclass Solution {\npublic:\n int sum(int num1, int num2) {\n return num1 + num2;\n }\n};\n```\n**2. Java**\n```\nclass Solution {\n public int sum(int num1, int num2) {\n return num1 + num2;\n }\n}\n```\n**3. Python3**\n```\nclass Solution:\n def sum(self, num1: int, num2: i...
23
Given two integers `num1` and `num2`, return _the **sum** of the two integers_. **Example 1:** **Input:** num1 = 12, num2 = 5 **Output:** 17 **Explanation:** num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. **Example 2:** **Input:** num1 = -10, num2 = 4 **Output:** -6 **Explanation:** num1 + ...
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
Solution
root-equals-sum-of-children
1
1
```C++ []\nclass Solution {\npublic:\n bool checkTree(TreeNode* root) {\n if(root==NULL)\n return false;\n if(root->left->val+root->right->val==root->val)\n return true;\n else\n return false;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def checkTree(self, root: O...
4
You are given the `root` of a **binary tree** that consists of exactly `3` nodes: the root, its left child, and its right child. Return `true` _if the value of the root is equal to the **sum** of the values of its two children, or_ `false` _otherwise_. **Example 1:** **Input:** root = \[10,4,6\] **Output:** true **E...
How can "reversing" a part of the linked list help find the answer? We know that the nodes of the first half are twins of nodes in the second half, so try dividing the linked list in half and reverse the second half. How can two pointers be used to find every twin sum optimally? Use two different pointers pointing to t...
Python || One Line Solution || Easy
root-equals-sum-of-children
0
1
```\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val==root.left.val+root.right.val\n```\n**An upvote will be encouraging**\n
11
You are given the `root` of a **binary tree** that consists of exactly `3` nodes: the root, its left child, and its right child. Return `true` _if the value of the root is equal to the **sum** of the values of its two children, or_ `false` _otherwise_. **Example 1:** **Input:** root = \[10,4,6\] **Output:** true **E...
How can "reversing" a part of the linked list help find the answer? We know that the nodes of the first half are twins of nodes in the second half, so try dividing the linked list in half and reverse the second half. How can two pointers be used to find every twin sum optimally? Use two different pointers pointing to t...
Easy to understand for beginners 🍾🍾💯 Python Easy
root-equals-sum-of-children
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDirect Tree approach ATTACKKKKKKKKK\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# ...
15
You are given the `root` of a **binary tree** that consists of exactly `3` nodes: the root, its left child, and its right child. Return `true` _if the value of the root is equal to the **sum** of the values of its two children, or_ `false` _otherwise_. **Example 1:** **Input:** root = \[10,4,6\] **Output:** true **E...
How can "reversing" a part of the linked list help find the answer? We know that the nodes of the first half are twins of nodes in the second half, so try dividing the linked list in half and reverse the second half. How can two pointers be used to find every twin sum optimally? Use two different pointers pointing to t...
easy python solution
find-closest-number-to-zero
0
1
\nclass Solution:\n def findClosestNumber(self, nums: List[int]) -> int:\n min=1000000\n for i in nums:\n if min>abs(i):\n min=abs(i)\n if min in nums:\n return min\n else:\n return -1*min\n \n \n```
2
Given an integer array `nums` of size `n`, return _the number with the value **closest** to_ `0` _in_ `nums`. If there are multiple answers, return _the number with the **largest** value_. **Example 1:** **Input:** nums = \[-4,-2,1,4,8\] **Output:** 1 **Explanation:** The distance from -4 to 0 is |-4| = 4. The distan...
The constraints are not very large. Can we simulate the execution by starting from each index of s? Before any of the stopping conditions is met, stop the simulation for that index and set the answer for that index.
Self-Explanatory Code!
find-closest-number-to-zero
0
1
\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findClosestNumber(self, nums: List[int]) -> int:\n diff = 99999999\n ans = 999999999...
1
Given an integer array `nums` of size `n`, return _the number with the value **closest** to_ `0` _in_ `nums`. If there are multiple answers, return _the number with the **largest** value_. **Example 1:** **Input:** nums = \[-4,-2,1,4,8\] **Output:** 1 **Explanation:** The distance from -4 to 0 is |-4| = 4. The distan...
The constraints are not very large. Can we simulate the execution by starting from each index of s? Before any of the stopping conditions is met, stop the simulation for that index and set the answer for that index.
Python | Easy Solution✅
find-closest-number-to-zero
0
1
# Code\u2705\n```\nclass Solution:\n def findClosestNumber(self, nums: List[int]) -> int: #// nums = [-4, -2, 1, 4, 8]\n pos, neg = [], []\n for item in nums:\n if item < 0:\n neg.append(item)\n elif item > 0:\n pos.append(item)\n else:\n ...
5
Given an integer array `nums` of size `n`, return _the number with the value **closest** to_ `0` _in_ `nums`. If there are multiple answers, return _the number with the **largest** value_. **Example 1:** **Input:** nums = \[-4,-2,1,4,8\] **Output:** 1 **Explanation:** The distance from -4 to 0 is |-4| = 4. The distan...
The constraints are not very large. Can we simulate the execution by starting from each index of s? Before any of the stopping conditions is met, stop the simulation for that index and set the answer for that index.
🔥100% EASY TO UNDERSTAND/SIMPLE/CLEAN🔥
find-closest-number-to-zero
0
1
```\nclass Solution:\n def findClosestNumber(self, nums: List[int]) -> int:\n smallest = 0\n for i in nums:\n if abs(i) == 0:\n return 0\n elif smallest == 0 or abs(i) < abs(smallest):\n smallest = i\n elif abs(i) == abs(smallest):\n ...
0
Given an integer array `nums` of size `n`, return _the number with the value **closest** to_ `0` _in_ `nums`. If there are multiple answers, return _the number with the **largest** value_. **Example 1:** **Input:** nums = \[-4,-2,1,4,8\] **Output:** 1 **Explanation:** The distance from -4 to 0 is |-4| = 4. The distan...
The constraints are not very large. Can we simulate the execution by starting from each index of s? Before any of the stopping conditions is met, stop the simulation for that index and set the answer for that index.
Python solution using lambda function || easy to understand for begineers
number-of-ways-to-buy-pens-and-pencils
0
1
```\nfrom math import floor\nclass Solution:\n def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:\n ans = 0\n y = lambda x: (total-x*cost1)/cost2\n for i in range(total+1):\n c = floor(y(i))\n if c>=0:\n ans += c+1\n return ans\...
2
You are given an integer `total` indicating the amount of money you have. You are also given two integers `cost1` and `cost2` indicating the price of a pen and pencil respectively. You can spend **part or all** of your money to buy multiple quantities (or none) of each kind of writing utensil. Return _the **number of ...
For each unique value found in the array, store a sorted list of indices of elements that have this value in the array. One way of doing this is to use a HashMap that maps the values to their list of indices. Update this mapping as you iterate through the array. Process each list of indices separately and get the sum o...
Python easy solution faster than 90%
number-of-ways-to-buy-pens-and-pencils
0
1
```\nclass Solution:\n def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:\n if total < cost1 and total < cost2:\n return 1\n ways = 0\n if cost1 > cost2:\n for i in range(0, (total // cost1)+1):\n rem = total - (i * cost1)\n ...
2
You are given an integer `total` indicating the amount of money you have. You are also given two integers `cost1` and `cost2` indicating the price of a pen and pencil respectively. You can spend **part or all** of your money to buy multiple quantities (or none) of each kind of writing utensil. Return _the **number of ...
For each unique value found in the array, store a sorted list of indices of elements that have this value in the array. One way of doing this is to use a HashMap that maps the values to their list of indices. Update this mapping as you iterate through the array. Process each list of indices separately and get the sum o...
Check then withdraw
design-an-atm-machine
0
1
We first try to `take` the amount using available bills. If we can get the exact amount, then we complete the withdraw operation.\n\n**Python 3**\n```python\nclass ATM:\n bank, val = [0] * 5, [20, 50, 100, 200, 500]\n \n def deposit(self, banknotesCount: List[int]) -> None:\n self.bank = [a + b for a, b...
72
There is an ATM machine that stores banknotes of `5` denominations: `20`, `50`, `100`, `200`, and `500` dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of **larger** values. * For example, if you ...
If we fix the value of k, how can we check if an original array exists for the fixed k? The smallest value of nums is obtained by subtracting k from the smallest value of the original array. How can we use this to reduce the search space for finding a valid k? You can compute every possible k by using the smallest valu...
Python3 Very Pythonic and clean Logical process flow
design-an-atm-machine
0
1
It\'s pretty straightforward, once you do it. It\'s the typical sort of thing, the first time you do it, it\'s 5x-10x longer to do then it\'s obvious.\n\n```\nclass ATM:\n def __init__(self):\n self.cash = [0] * 5\n self.values = [20, 50, 100, 200, 500]\n\n def deposit(self, banknotes_count: List[in...
6
There is an ATM machine that stores banknotes of `5` denominations: `20`, `50`, `100`, `200`, and `500` dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of **larger** values. * For example, if you ...
If we fix the value of k, how can we check if an original array exists for the fixed k? The smallest value of nums is obtained by subtracting k from the smallest value of the original array. How can we use this to reduce the search space for finding a valid k? You can compute every possible k by using the smallest valu...
Python Easy O(1)
design-an-atm-machine
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)$$ -->\nAll of the iterations are Range of 5 so, the time complexity is O(1)\n- Spac...
0
There is an ATM machine that stores banknotes of `5` denominations: `20`, `50`, `100`, `200`, and `500` dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of **larger** values. * For example, if you ...
If we fix the value of k, how can we check if an original array exists for the fixed k? The smallest value of nums is obtained by subtracting k from the smallest value of the original array. How can we use this to reduce the search space for finding a valid k? You can compute every possible k by using the smallest valu...
Python list traversal
design-an-atm-machine
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTwo lists in __init__:\n1. self.bank = [0] * 5\n2. self.notes = [20, 50, 100, 200, 500].\n\n# Code\n```\nclass ATM:\n\n def __init__(self):\n self.bank = [0, 0, 0, 0, 0]\n self.notes = [20, 50, 100, 200, 500]\n\n def d...
0
There is an ATM machine that stores banknotes of `5` denominations: `20`, `50`, `100`, `200`, and `500` dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of **larger** values. * For example, if you ...
If we fix the value of k, how can we check if an original array exists for the fixed k? The smallest value of nums is obtained by subtracting k from the smallest value of the original array. How can we use this to reduce the search space for finding a valid k? You can compute every possible k by using the smallest valu...
Python really easy to understand
design-an-atm-machine
0
1
# Approach\nClean solution\n\n# Code\n```\nclass ATM:\n def __init__(self):\n self.money = [0]*5\n self.order = [20, 50, 100, 200, 500]\n\n def deposit(self, banknotesCount: List[int]) -> None:\n for i, amount in enumerate(banknotesCount):\n self.money[i] += amount\n\n def withd...
0
There is an ATM machine that stores banknotes of `5` denominations: `20`, `50`, `100`, `200`, and `500` dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of **larger** values. * For example, if you ...
If we fix the value of k, how can we check if an original array exists for the fixed k? The smallest value of nums is obtained by subtracting k from the smallest value of the original array. How can we use this to reduce the search space for finding a valid k? You can compute every possible k by using the smallest valu...
[Java/Python] Keep 3 Biggest Neighbours
maximum-score-of-a-node-sequence
1
1
# **Intuition**\nWe don\'t need to check all possible sequences,\nbut only some big nodes.\n<br>\n\n# **Explanation**\nFor each edge `(i, j)` in `edges`,\nwe find a neighbour `ii` of node `i`,\nwe find a neighbour `jj` of node `i`,\nIf `ii, i, j,jj` has no duplicate, then that\'s a valid sequence.\n\nAd the intuition m...
126
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
[Python3] Top 3 neighbors in adjacency list using heap
maximum-score-of-a-node-sequence
0
1
The solution here converts the adjacency list into a heap. We just need the top 3 neighbors for any node to solve this problem. Since I am using heap, I can extract the top 3 neighbors in O(3*log(n)). \n\n**Main point**: For every edge, say a---b, we can search for the best neighbor of a (that is not b) and the best ne...
4
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
[Python 3] Hint solution
maximum-score-of-a-node-sequence
0
1
```\n# key is to store top 3 neighbors for each node\n# for each pair of edges (two middle nodes): find the other two nodes with highest score\n# we can\'t store top 1 node (highest node is neighbor in the edge) or 2 nodes (two middle nodes share the same highest adjacent node)\n\n\nclass Solution:\n def maximumScor...
3
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
Python3 O(|E|) solution
maximum-score-of-a-node-sequence
0
1
```\nclass Solution:\n def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:\n \n connection = {}\n \n for source, target in edges:\n if source not in connection: connection[source] = [target]\n else: connection[source].append(target)\n \n if targ...
2
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
Need Help [ Python3 ]
maximum-score-of-a-node-sequence
0
1
# Can anyone explain me, why?\n**scores = [16,21,22,2,24,21,12,17,2,24]\nedges = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,0]]**\n\nwhy this is giving ***83*** , it should be ***61***\n![image](https://assets.leetcode.com/users/images/894f06c9-f5b7-43c9-9b89-a2de2c61ddf6_1650143878.90271.png)\n\n\nand \...
0
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
List of Heaps | Commented and Explained
maximum-score-of-a-node-sequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want the maximum score of a node sequence \nWe know that the nodes are of length 4 \nThis means we have 3 edges \nWe also know that we need them to be such that the middle edge is fixed and other two can swing \nThis tells us we really...
0
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
Short Linear-Time Solution in Python, Faster than 100%
maximum-score-of-a-node-sequence
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe solution is three connected edges that cover four nodes where the sum of the four nodes are maximized. \nFor each edge `(u, v)` we can find two best neighboring edges `(p, u)` and `(v, q)` so that `u, v, p, q` are four distinct nodes and their sum...
0
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
Considering top 3 neighbours || Graphs || Python3
maximum-score-of-a-node-sequence
0
1
# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:\n\n n = len(scores)\n graphs = defaultdict(list)\n\n for a, b in edges:\n graphs[a].append([scores[b], b])\n graphs[b].append([sco...
0
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
Elog(something) solution for u shit
maximum-score-of-a-node-sequence
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom sortedcontainers import SortedList\nclass Solution:\n def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:\n ans,g=-1,defaultdict(SortedList)\n for x,y in edges:\n print(x,y)\n g[x]....
0
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
Python Solution with comments [DFS and Top 3 neighbors with Min Heap]
maximum-score-of-a-node-sequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst solution is intuitive approach using DFS+backtracking, but this approach gets TLE. \n\nSecond solution uses top 3 neighbors, I just implemented this appoach https://leetcode.com/problems/maximum-score-of-a-node-sequence/solutions/19...
0
There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge c...
Is the sum of two even numbers even or odd? How about two odd numbers? One odd number and one even number? If there is an even number of odd numbers, the sum will be even and vice versa. Create an integer array to store all the even numbers in nums and another array to store all the odd numbers in nums. Sort both array...
Python 6line code || 98.60 %Beats || Simple Code
calculate-digit-sum-of-a-string
0
1
**If you got help from this,... Plz Upvote .. it encourage me**\n# Code\nShort Way:\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n new_s = \'\'\n for i in range(0,len(s), k):\n new_s += str(sum(int(d) for d in s[i:i+k]))\n ...
5
You are given a string `s` consisting of digits and an integer `k`. A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: 1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i...
You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer. s should not have any occurrences of “ba” as a substring.
Python Elegant & Short | Pythonic | Iterative + Recursive
calculate-digit-sum-of-a-string
0
1
\tclass Solution:\n\t\tdef digitSum(self, s: str, k: int) -> str:\n\t\t\t"""Iterative version"""\n\t\t\twhile len(s) > k:\n\t\t\t\ts = self.round(s, k)\n\t\t\treturn s\n\t\n\t\tdef digitSum(self, s: str, k: int) -> str:\n\t\t\t"""Recursive version"""\n\t\t\tif len(s) <= k:\n\t\t\t\treturn s\n\t\t\treturn self.digitSum(...
2
You are given a string `s` consisting of digits and an integer `k`. A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: 1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i...
You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer. s should not have any occurrences of “ba” as a substring.
[Python 3] Convert string to list and use brute-force
calculate-digit-sum-of-a-string
0
1
```python3 []\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n s = list(map(int, s))\n while len(s) > k:\n tmp = []\n for i in range(0, len(s), k):\n S = sum(s[i:i+k])\n for d in (str(S)):\n tmp.append(int(d))\n ...
4
You are given a string `s` consisting of digits and an integer `k`. A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: 1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i...
You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer. s should not have any occurrences of “ba” as a substring.
Python3 elegant pythonic clean and easy to understand
calculate-digit-sum-of-a-string
0
1
Simple while loop and slicing to repeat 3 set process and aggregation\n\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n set_3 = [s[i:i+k] for i in range(0, len(s), k)]\n s = \'\'\n for e in set_3:\n val = 0\n ...
14
You are given a string `s` consisting of digits and an integer `k`. A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: 1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i...
You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer. s should not have any occurrences of “ba” as a substring.
Simple Python Solution
calculate-digit-sum-of-a-string
0
1
```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n def divideString(s: str, k: int) -> List[str]: # Utility function to return list of divided groups.\n l, n = [], len(s)\n for i in range(0, n, k):\n l.append(s[i:min(i + k, n)])\n return l\n ...
6
You are given a string `s` consisting of digits and an integer `k`. A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: 1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i...
You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer. s should not have any occurrences of “ba” as a substring.