problem_title
stringlengths
3
77
python_solutions
stringlengths
81
8.45k
post_href
stringlengths
64
213
upvotes
int64
0
1.2k
question
stringlengths
0
3.6k
post_title
stringlengths
2
100
views
int64
1
60.9k
slug
stringlengths
3
77
acceptance
float64
0.14
0.91
user
stringlengths
3
26
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
number
int64
1
2.48k
largest sum of averages
class Solution: def largestSumOfAverages(self, nums: List[int], k: int) -> float: @lru_cache(maxsize=None) def maxAvgSum(index: int, partitions_left: int) -> int: if partitions_left == 1: return sum(nums[index:]) / (len(nums) - index) max_sum: float = 0.0 for i in range(index, len(nums) - (partitions_left - 1)): cur_sum: float = sum(nums[index:i + 1])/(i + 1 - index) cur_sum += maxAvgSum(i + 1, partitions_left - 1) max_sum = max(cur_sum, max_sum) return max_sum return maxAvgSum(0, k)
https://leetcode.com/problems/largest-sum-of-averages/discuss/1633894/Python-3-Solution-Using-Memoization
1
You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums, and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted. Example 1: Input: nums = [9,1,2,3,9], k = 3 Output: 20.00000 Explanation: The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into [9, 1], [2], [3, 9], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. Example 2: Input: nums = [1,2,3,4,5,6,7], k = 4 Output: 20.50000 Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 104 1 <= k <= nums.length
Python 3 Solution Using Memoization
100
largest-sum-of-averages
0.529
mlalma
Medium
13,178
813
binary tree pruning
class Solution(object): def pruneTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root==None: return None _l = self.pruneTree(root.left) _r = self.pruneTree(root.right) if root.val == 0 and _l == None and _r == None: return None else: root.left = _l root.right = _r return root
https://leetcode.com/problems/binary-tree-pruning/discuss/298312/Python-faster-than-98-16-ms
8
Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. A subtree of a node node is node plus every node that is a descendant of node. Example 1: Input: root = [1,null,0,0,1] Output: [1,null,0,null,1] Explanation: Only the red nodes satisfy the property "every subtree not containing a 1". The diagram on the right represents the answer. Example 2: Input: root = [1,0,1,0,0,0,1] Output: [1,null,1,null,1] Example 3: Input: root = [1,1,0,1,1,0,1,0] Output: [1,1,0,1,1,null,1] Constraints: The number of nodes in the tree is in the range [1, 200]. Node.val is either 0 or 1.
Python - faster than 98%, 16 ms
826
binary-tree-pruning
0.726
il_buono
Medium
13,183
814
bus routes
class Solution: def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int: m = defaultdict(set) for i, route in enumerate(routes): for node in route: m[node].add(i) ans = -1 vis = set() queue = deque() queue.append(source) while queue: l = len(queue) ans += 1 for _ in range(l): cur = queue.popleft() if cur == target: return ans for bus in m[cur]: if bus not in vis: vis.add(bus) queue.extend(routes[bus]) return -1
https://leetcode.com/problems/bus-routes/discuss/2275016/Python3-BFS-Approach
1
You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible. Example 1: Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6 Output: 2 Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. Example 2: Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12 Output: -1 Constraints: 1 <= routes.length <= 500. 1 <= routes[i].length <= 105 All the values of routes[i] are unique. sum(routes[i].length) <= 105 0 <= routes[i][j] < 106 0 <= source, target < 106
[Python3] BFS Approach
127
bus-routes
0.457
van_fantasy
Hard
13,218
815
ambiguous coordinates
class Solution: def ambiguousCoordinates(self, s: str) -> List[str]: s = s.strip("(").strip(")") def fn(s): """Return valid numbers from s.""" if len(s) == 1: return [s] if s.startswith("0") and s.endswith("0"): return [] if s.startswith("0"): return [s[:1] + "." + s[1:]] if s.endswith("0"): return [s] return [s[:i] + "." + s[i:] for i in range(1, len(s))] + [s] ans = [] for i in range(1, len(s)): for x in fn(s[:i]): for y in fn(s[i:]): ans.append(f"({x}, {y})") return ans
https://leetcode.com/problems/ambiguous-coordinates/discuss/934654/Python3-valid-numbers
7
We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces and ended up with the string s. For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)". Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like ".1". The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) Example 1: Input: s = "(123)" Output: ["(1, 2.3)","(1, 23)","(1.2, 3)","(12, 3)"] Example 2: Input: s = "(0123)" Output: ["(0, 1.23)","(0, 12.3)","(0, 123)","(0.1, 2.3)","(0.1, 23)","(0.12, 3)"] Explanation: 0.0, 00, 0001 or 00.01 are not allowed. Example 3: Input: s = "(00011)" Output: ["(0, 0.011)","(0.001, 1)"] Constraints: 4 <= s.length <= 12 s[0] == '(' and s[s.length - 1] == ')'. The rest of s are digits.
[Python3] valid numbers
302
ambiguous-coordinates
0.561
ye15
Medium
13,225
816
linked list components
class Solution: def numComponents(self, head: ListNode, G: List[int]) -> int: Gs = set(G) ans = 0 while head: if head.val in Gs and (head.next is None or head.next.val not in Gs): ans += 1 head = head.next return ans
https://leetcode.com/problems/linked-list-components/discuss/933679/Python3-counting-end-of-component
3
You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values. Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list. Example 1: Input: head = [0,1,2,3], nums = [0,1,3] Output: 2 Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components. Example 2: Input: head = [0,1,2,3,4], nums = [0,3,1,4] Output: 2 Explanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components. Constraints: The number of nodes in the linked list is n. 1 <= n <= 104 0 <= Node.val < n All the values Node.val are unique. 1 <= nums.length <= n 0 <= nums[i] < n All the values of nums are unique.
[Python3] counting end of component
180
linked-list-components
0.581
ye15
Medium
13,231
817
race car
class Solution: def racecar(self, target: int) -> int: q = deque() q.append((0,0,1)) while q: m,p,s = q.popleft() if p==target: return m rev = -1 if s>0 else 1 q.append((m+1,p+s,s*2)) if (p+s<target and s<0) or (p+s>target and s>0): # If you are back to the target and speed is reverse or if you are ahead of target and speed is positive then reverse the speed q.append((m+1,p,rev)) return -1
https://leetcode.com/problems/race-car/discuss/1512080/Greedy-Approach-oror-Normal-conditions-oror-94-faster-oror-Well-Coded
9
Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): When you get an instruction 'A', your car does the following: position += speed speed *= 2 When you get an instruction 'R', your car does the following: If your speed is positive then speed = -1 otherwise speed = 1 Your position stays the same. For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1. Given a target position target, return the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0 --> 1 --> 3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6. Constraints: 1 <= target <= 104
📌📌 Greedy Approach || Normal conditions || 94% faster || Well-Coded 🐍
764
race-car
0.435
abhi9Rai
Hard
13,240
818
most common word
class Solution: def getSplit(self, s): result = [] strS = '' for i in s.lower(): if i not in "!?',;. ": strS += i else: if len(strS) > 0: result.append(strS) strS = '' if len(strS) > 0: result.append(strS) return result def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: paragraph = self.getSplit(paragraph) freq = {} for s in paragraph: if s not in banned: if s in freq: freq[s] += 1 else: freq[s] = 1 m = max(freq.values()) for k in freq: if freq[k] == m: return k
https://leetcode.com/problems/most-common-word/discuss/2830994/Python-oror-Long-but-FAST-oror-Memory-beats-82.67!
1
Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique. The words in paragraph are case-insensitive and the answer should be returned in lowercase. Example 1: Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"] Output: "ball" Explanation: "hit" occurs 3 times, but it is a banned word. "ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. Note that words in the paragraph are not case sensitive, that punctuation is ignored (even if adjacent to words, such as "ball,"), and that "hit" isn't the answer even though it occurs more because it is banned. Example 2: Input: paragraph = "a.", banned = [] Output: "a" Constraints: 1 <= paragraph.length <= 1000 paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.". 0 <= banned.length <= 100 1 <= banned[i].length <= 10 banned[i] consists of only lowercase English letters.
Python || Long but FAST || Memory beats 82.67%!
27
most-common-word
0.449
qiy2019
Easy
13,243
819
short encoding of words
class Solution: def minimumLengthEncoding(self, words: List[str]) -> int: words.sort(key=len, reverse=True) res = [] for suffix in words: if not any(word.endswith(suffix) for word in res): # check that this word is not actually a suffix res.append(suffix) return sum(len(word)+1 for word in res) # append hash '#' symbol to each word that is not a suffix
https://leetcode.com/problems/short-encoding-of-words/discuss/2172401/Python-Concise-Brute-Force-and-Trie-Solutions-with-Explanation
23
A valid encoding of an array of words is any reference string s and array of indices indices such that: words.length == indices.length The reference string s ends with the '#' character. For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i]. Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words. Example 1: Input: words = ["time", "me", "bell"] Output: 10 Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5]. words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#" words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#" words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#" Example 2: Input: words = ["t"] Output: 2 Explanation: A valid encoding would be s = "t#" and indices = [0]. Constraints: 1 <= words.length <= 2000 1 <= words[i].length <= 7 words[i] consists of only lowercase letters.
[Python] Concise Brute Force & Trie Solutions with Explanation
1,100
short-encoding-of-words
0.607
zayne-siew
Medium
13,271
820
shortest distance to a character
class Solution: def shortestToChar(self, s: str, c: str) -> List[int]: L = [] for idx, value in enumerate(s): if value == c: L.append(idx) distance = [] i = 0 for idx, value in enumerate(s): if value == c: distance.append(0) i += 1 elif idx < L[0]: distance.append(L[0] - idx) elif idx > L[-1]: distance.append(idx - L[-1]) else: distance.append(min((L[i] - idx), (idx - L[i-1]))) return distance
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1226696/Python3Any-improvement
5
Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s. The distance between two indices i and j is abs(i - j), where abs is the absolute value function. Example 1: Input: s = "loveleetcode", c = "e" Output: [3,2,1,0,1,0,0,1,2,2,1,0] Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed). The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3. The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2. For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1. The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2. Example 2: Input: s = "aaab", c = "b" Output: [3,2,1,0] Constraints: 1 <= s.length <= 104 s[i] and c are lowercase English letters. It is guaranteed that c occurs at least once in s.
【Python3】Any improvement ?
293
shortest-distance-to-a-character
0.714
qiaochow
Easy
13,295
821
card flipping game
class Solution: def flipgame(self, fronts: List[int], backs: List[int]) -> int: """ O(n) time complexity: n is length of fronts O(n) space complexity """ same = {x for i, x in enumerate(fronts) if x == backs[i]} res = 9999 for i in range(len(fronts)): if fronts[i] not in same: res = min(res, fronts[i]) if backs[i] not in same: res = min(res, backs[i]) return res % 9999
https://leetcode.com/problems/card-flipping-game/discuss/530999/Python3-simple-solution-using-a-for()-loop
2
You are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero). After flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card. Return the minimum possible good integer after flipping the cards. If there are no good integers, return 0. Example 1: Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3] Output: 2 Explanation: If we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3]. 2 is the minimum good integer as it appears facing down but not facing up. It can be shown that 2 is the minimum possible good integer obtainable after flipping some cards. Example 2: Input: fronts = [1], backs = [1] Output: 0 Explanation: There are no good integers no matter how we flip the cards, so we return 0. Constraints: n == fronts.length == backs.length 1 <= n <= 1000 1 <= fronts[i], backs[i] <= 2000
Python3 simple solution using a for() loop
254
card-flipping-game
0.456
jb07
Medium
13,330
822
binary trees with factors
class Solution: def numFactoredBinaryTrees(self, arr: List[int]) -> int: total_nums = len(arr) moduler = 1000000007 count_product_dict = {num: 1 for num in arr} arr.sort() for i in range(1, total_nums): for j in range(i): quotient = arr[i] // arr[j] if quotient < 2 or math.sqrt(arr[i]) > arr[i- 1]: break if arr[i] % arr[j] == 0: count_product_dict[arr[i]] += count_product_dict[arr[j]] * count_product_dict.get(quotient, 0) count_product_dict[arr[i]] %= moduler return sum(count_product_dict.values()) % moduler
https://leetcode.com/problems/binary-trees-with-factors/discuss/2402569/Python-oror-Detailed-Explanation-oror-Easily-Understood-oror-DP-oror-O(n-*-sqrt(n))
35
Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7. Example 1: Input: arr = [2,4] Output: 3 Explanation: We can make these trees: [2], [4], [4, 2, 2] Example 2: Input: arr = [2,4,5,10] Output: 7 Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]. Constraints: 1 <= arr.length <= 1000 2 <= arr[i] <= 109 All the values of arr are unique.
🔥 Python || Detailed Explanation ✅ || Easily Understood || DP || O(n * sqrt(n))
1,100
binary-trees-with-factors
0.5
wingskh
Medium
13,333
823
goat latin
class Solution: def toGoatLatin(self, sentence: str) -> str: new = sentence.split() # Breaks up the input into individual sentences count = 1 # Starting at 1 since we only have one "a" to begin with. for x in range(len(new)): if new[x][0].casefold() in 'aeiou': # Checks if the first value of x is a vowel. The casefold, can be replaced with lower, lowers the case. Can also just be removed and have "in 'aeiouAEIOU' new[x] = new[x] + 'ma' + 'a'*count # Brings it together with the count multiplying number of "a"'s as needed. count += 1 elif new[x].casefold() not in 'aeiou': # Same comment as above. new[x] = new[x][1:] + new[x][0] + 'ma' + 'a'*count # Just moves the first value to the end then does the a. count += 1 return " ".join(x for x in new) # Converts the list back into a string.
https://leetcode.com/problems/goat-latin/discuss/1877272/Python-3-Simple-Solution-w-Explanation
4
You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: If a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append "ma" to the end of the word. For example, the word "apple" becomes "applema". If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add "ma". For example, the word "goat" becomes "oatgma". Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1. For example, the first word gets "a" added to the end, the second word gets "aa" added to the end, and so on. Return the final sentence representing the conversion from sentence to Goat Latin. Example 1: Input: sentence = "I speak Goat Latin" Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" Example 2: Input: sentence = "The quick brown fox jumped over the lazy dog" Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" Constraints: 1 <= sentence.length <= 150 sentence consists of English letters and spaces. sentence has no leading or trailing spaces. All the words in sentence are separated by a single space.
[Python 3] - Simple Solution w Explanation
110
goat-latin
0.678
IvanTsukei
Easy
13,358
824
friends of appropriate ages
class Solution: def numFriendRequests(self, ages: List[int]) -> int: ages.sort() # sort the `ages` ans = 0 n = len(ages) for idx, age in enumerate(ages): # for each age lb = age # lower bound ub = (age - 7) * 2 # upper bound i = bisect.bisect_left(ages, lb) # binary search lower bound j = bisect.bisect_left(ages, ub) # binary search upper bound if j - i <= 0: continue ans += j - i # count number of potential friends if lb <= age < ub: # ignore itself ans -= 1 return ans
https://leetcode.com/problems/friends-of-appropriate-ages/discuss/2074946/Python-3-or-Three-Methods-(Binary-Search-CounterHashmap-Math)-or-Explanation
5
There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: age[y] <= 0.5 * age[x] + 7 age[y] > age[x] age[y] > 100 && age[x] < 100 Otherwise, x will send a friend request to y. Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself. Return the total number of friend requests made. Example 1: Input: ages = [16,16] Output: 2 Explanation: 2 people friend request each other. Example 2: Input: ages = [16,17,18] Output: 2 Explanation: Friend requests are made 17 -> 16, 18 -> 17. Example 3: Input: ages = [20,30,100,110,120] Output: 3 Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. Constraints: n == ages.length 1 <= n <= 2 * 104 1 <= ages[i] <= 120
Python 3 | Three Methods (Binary Search, Counter/Hashmap, Math) | Explanation
416
friends-of-appropriate-ages
0.464
idontknoooo
Medium
13,401
825
most profit assigning work
class Solution: #Time-Complexity: O(n + nlogn + n + mlog(n)) -> O((n+m) *logn) #Space-Complexity: O(n) def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: #Approach: First of all, linearly traverse each and every corresponding index #position of first two input arrays: difficulty and profit to group each #item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array #by increasing difficulty of the job! Then, for each worker, perform binary #search and consistently update the max profit the current worker can work and #earn! Add this value to answer variable, which is cumulative for all workers! #this will be the result returned at the end! arr = [] for i in range(len(difficulty)): arr.append([difficulty[i], profit[i]]) #sort by difficulty! arr.sort(key = lambda x: x[0]) #then, I need to update the maximum profit up to each and every item! maximum = float(-inf) for j in range(len(arr)): maximum = max(maximum, arr[j][1]) arr[j][1] = maximum ans = 0 #iterate through each and every worker! for w in worker: bestProfit = 0 #define search space to perform binary search! L, R = 0, len(arr) - 1 #as long as search space has at least one element to consider or one job, #continue iterations of binary search! while L <= R: mid = (L + R) // 2 mid_e = arr[mid] #check if current job has difficulty that is manageable! if(mid_e[0] <= w): bestProfit = max(bestProfit, mid_e[1]) #we still need to search right and try higher difficulty #jobs that might yield higher profit! L = mid + 1 continue else: R = mid - 1 continue #once we break from while loop and end binary search, we should have #found bestProfit for current worker performing task that is manageable! ans += bestProfit return ans
https://leetcode.com/problems/most-profit-assigning-work/discuss/2603913/Python3-or-Solved-Using-Binary-Search-W-Sorting-O((n%2Bm)*logn)-Runtime-Solution!
2
You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). Every worker can be assigned at most one job, but one job can be completed multiple times. For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0. Return the maximum profit we can achieve after assigning the workers to the jobs. Example 1: Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] Output: 100 Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately. Example 2: Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25] Output: 0 Constraints: n == difficulty.length n == profit.length m == worker.length 1 <= n, m <= 104 1 <= difficulty[i], profit[i], worker[i] <= 105
Python3 | Solved Using Binary Search W/ Sorting O((n+m)*logn) Runtime Solution!
134
most-profit-assigning-work
0.446
JOON1234
Medium
13,412
826
making a large island
class Solution: def largestIsland(self, grid: List[List[int]]) -> int: N = len(grid) DIRECTIONS = [(-1, 0), (0, -1), (0, 1), (1, 0)] address = {} def dfs(row, column, island_id): queue = deque([(row, column, island_id)]) visited.add((row, column)) area = 1 while queue: row, column, island_id = queue.pop() address[(row, column)] = island_id for direction in DIRECTIONS: r, c = row + direction[0], column + direction[1] if r in range(N) and c in range(N) and grid[r][c] == 1 and (r, c) not in visited: queue.append((r, c, island_id)) visited.add((r, c)) area += 1 return area visited = set() area = {} island_id = 0 for row in range(N): for column in range(N): if grid[row][column] == 1 and (row, column) not in visited: area[island_id] = dfs(row, column, island_id) island_id += 1 if len(address.keys()) == N**2: return N**2 largest_area = 1 for row in range(N): for column in range(N): if grid[row][column] == 1: continue neighbours = set() large_area = 1 for direction in DIRECTIONS: r, c = row + direction[0], column + direction[1] if r in range(N) and c in range(N) and grid[r][c] == 1 and address[(r, c)] not in neighbours: neighbours.add(address[(r, c)]) large_area += area[address[(r, c)]] largest_area = max(largest_area, large_area) return largest_area
https://leetcode.com/problems/making-a-large-island/discuss/1340782/Python-Clean-DFS
4
You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s. Example 1: Input: grid = [[1,0],[0,1]] Output: 3 Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3. Example 2: Input: grid = [[1,1],[1,0]] Output: 4 Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4. Example 3: Input: grid = [[1,1],[1,1]] Output: 4 Explanation: Can't change any 0 to 1, only one island with area = 4. Constraints: n == grid.length n == grid[i].length 1 <= n <= 500 grid[i][j] is either 0 or 1.
[Python] Clean DFS
1,000
making-a-large-island
0.447
soma28
Hard
13,422
827
count unique characters of all substrings of a given string
class Solution: def uniqueLetterString(self, s: str) -> int: r=0 for i in range(len(s)): for j in range(i, len(s)): ss=s[i:j+1] unique=sum([ 1 for (i,v) in Counter(ss).items() if v == 1 ]) r+=unique return r
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2140546/Python-O(n)-with-intuition-step-by-step-thought-process
6
Let's define a function countUniqueChars(s) that returns the number of unique characters in s. For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5. Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. Example 1: Input: s = "ABC" Output: 10 Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 Example 2: Input: s = "ABA" Output: 8 Explanation: The same as example 1, except countUniqueChars("ABA") = 1. Example 3: Input: s = "LEETCODE" Output: 92 Constraints: 1 <= s.length <= 105 s consists of uppercase English letters only.
Python O(n) with intuition / step-by-step thought process
354
count-unique-characters-of-all-substrings-of-a-given-string
0.517
alskdjfhg123
Hard
13,442
828
consecutive numbers sum
class Solution: def consecutiveNumbersSum(self, n: int) -> int: csum=0 result=0 for i in range(1,n+1): csum+=i-1 if csum>=n: break if (n-csum)%i==0: result+=1 return result
https://leetcode.com/problems/consecutive-numbers-sum/discuss/1466133/8-lines-Python3-code
6
Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers. Example 1: Input: n = 5 Output: 2 Explanation: 5 = 2 + 3 Example 2: Input: n = 9 Output: 3 Explanation: 9 = 4 + 5 = 2 + 3 + 4 Example 3: Input: n = 15 Output: 4 Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 Constraints: 1 <= n <= 109
8 lines Python3 code
705
consecutive-numbers-sum
0.415
tongho
Hard
13,456
829
positions of large groups
class Solution(object): def largeGroupPositions(self, s): s += " " streak, char, out = 0, s[0], [] for i,c in enumerate(s): if c != char: if streak >= 3: out.append([i-streak, i-1]) streak, char = 0, s[i] streak += 1 return out
https://leetcode.com/problems/positions-of-large-groups/discuss/1831860/Python-simple-and-elegant-multiple-solutions-%22Streak%22
1
In a string s of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and "yy". A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, "xxxx" has the interval [3,6]. A group is considered large if it has 3 or more characters. Return the intervals of every large group sorted in increasing order by start index. Example 1: Input: s = "abbxxxxzzy" Output: [[3,6]] Explanation: "xxxx" is the only large group with start index 3 and end index 6. Example 2: Input: s = "abc" Output: [] Explanation: We have groups "a", "b", and "c", none of which are large groups. Example 3: Input: s = "abcdddeeeeaabbbcd" Output: [[3,5],[6,9],[12,14]] Explanation: The large groups are "ddd", "eeee", and "bbb". Constraints: 1 <= s.length <= 1000 s contains lowercase English letters only.
Python - simple and elegant - multiple solutions - "Streak"
83
positions-of-large-groups
0.518
domthedeveloper
Easy
13,465
830
masking personal information
class Solution: def maskPII(self, s: str) -> str: if '@' in s: return f'{s[0].lower()}*****{s[s.index("@")-1].lower()+"".join([x.lower() for x in s[s.index("@"):]])}' s=''.join([x for x in s if x not in '()- +']) return ('' if len(s)<=10 else '+'+'*'*(len(s)-10)+'-')+f'***-***-{s[-4:]}'
https://leetcode.com/problems/masking-personal-information/discuss/1868652/3-Lines-Python-Solution-oror-98-Faster-oror-Memory-less-than-87
1
You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules. Email address: An email address is: A name consisting of uppercase and lowercase English letters, followed by The '@' symbol, followed by The domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character). To mask an email: The uppercase letters in the name and domain must be converted to lowercase letters. The middle letters of the name (i.e., all but the first and last letters) must be replaced by 5 asterisks "*****". Phone number: A phone number is formatted as follows: The phone number contains 10-13 digits. The last 10 digits make up the local number. The remaining 0-3 digits, in the beginning, make up the country code. Separation characters from the set {'+', '-', '(', ')', ' '} separate the above digits in some way. To mask a phone number: Remove all separation characters. The masked phone number should have the form: "***-***-XXXX" if the country code has 0 digits. "+*-***-***-XXXX" if the country code has 1 digit. "+**-***-***-XXXX" if the country code has 2 digits. "+***-***-***-XXXX" if the country code has 3 digits. "XXXX" is the last 4 digits of the local number. Example 1: Input: s = "LeetCode@LeetCode.com" Output: "l*****e@leetcode.com" Explanation: s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Example 2: Input: s = "AB@qq.com" Output: "a*****b@qq.com" Explanation: s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab" is 2 characters, it still must have 5 asterisks in the middle. Example 3: Input: s = "1(234)567-890" Output: "***-***-7890" Explanation: s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "***-***-7890". Constraints: s is either a valid email or a phone number. If s is an email: 8 <= s.length <= 40 s consists of uppercase and lowercase English letters and exactly one '@' symbol and '.' symbol. If s is a phone number: 10 <= s.length <= 20 s consists of digits, spaces, and the symbols '(', ')', '-', and '+'.
3-Lines Python Solution || 98% Faster || Memory less than 87%
94
masking-personal-information
0.47
Taha-C
Medium
13,484
831
flipping an image
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: """ Simple &amp; striaghtforward without using inbuilt functions. In actual the run time is very less as we are iterating only n/2 time for each image list. Time complexity : O(n * n/2) == O(n^2) Space complexity : O(1) """ for im in image: #Iterate through each im list in the image list. i, j = 0, len(im)-1 #Maintain two pointers one at start and one at end. while i <= j: #Iterate while first pointer is less than or equal to second pointer. im[i], im[j] = im[j]^1, im[i]^1 #swap element at both pointer &amp; complement them at the same time. i +=1 #increment first pointer to move forward j -=1 #decrement second pointer to move backward return image # return same list """ Using inbuilt functions """ # for im in range(len(image)): # image[im] = list(map(lambda a : abs(a-1), reversed(image[im]))) # return image """ One liner """ return [[i^1 for i in im[::-1]] for im in image]
https://leetcode.com/problems/flipping-an-image/discuss/1363051/PYTHON-VERY-VERY-EASY-SOLN.-3-solutions-explained-O(n).-With-or-without-inbuilt-functions.
10
Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1,1,0] horizontally results in [0,1,1]. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0,1,1] results in [1,0,0]. Example 1: Input: image = [[1,1,0],[1,0,1],[0,0,0]] Output: [[1,0,0],[0,1,0],[1,1,1]] Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] Example 2: Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] Constraints: n == image.length n == image[i].length 1 <= n <= 20 images[i][j] is either 0 or 1.
[PYTHON] VERY VERY EASY SOLN. 3 solutions explained O(n). With or without inbuilt functions.
663
flipping-an-image
0.805
er1shivam
Easy
13,489
832
find and replace in string
class Solution: def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str: # iterate from the greater index to the smallest for i, src, tg in sorted(list(zip(indices, sources, targets)), reverse=True): # if found the pattern matches with the source, replace with the target accordingly if s[i:i+len(src)] == src: s = s[:i] + tg + s[i+len(src):] return s
https://leetcode.com/problems/find-and-replace-in-string/discuss/1920198/Python-3-or-simple-or-3-lines-of-code-w-explanation
3
You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k. To complete the ith replacement operation: Check if the substring sources[i] occurs at index indices[i] in the original string s. If it does not occur, do nothing. Otherwise if it does occur, replace that substring with targets[i]. For example, if s = "abcd", indices[i] = 0, sources[i] = "ab", and targets[i] = "eee", then the result of this replacement will be "eeecd". All replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap. For example, a testcase with s = "abc", indices = [0, 1], and sources = ["ab","bc"] will not be generated because the "ab" and "bc" replacements overlap. Return the resulting string after performing all replacement operations on s. A substring is a contiguous sequence of characters in a string. Example 1: Input: s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"] Output: "eeebffff" Explanation: "a" occurs at index 0 in s, so we replace it with "eee". "cd" occurs at index 2 in s, so we replace it with "ffff". Example 2: Input: s = "abcd", indices = [0, 2], sources = ["ab","ec"], targets = ["eee","ffff"] Output: "eeecd" Explanation: "ab" occurs at index 0 in s, so we replace it with "eee". "ec" does not occur at index 2 in s, so we do nothing. Constraints: 1 <= s.length <= 1000 k == indices.length == sources.length == targets.length 1 <= k <= 100 0 <= indexes[i] < s.length 1 <= sources[i].length, targets[i].length <= 50 s consists of only lowercase English letters. sources[i] and targets[i] consist of only lowercase English letters.
Python 3 | simple | 3 lines of code w/ explanation
327
find-and-replace-in-string
0.541
Ploypaphat
Medium
13,539
833
sum of distances in tree
class Solution: def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]: graph = {} for u, v in edges: graph.setdefault(u, []).append(v) graph.setdefault(v, []).append(u) size = [0]*n def fn(x, par): """Return size and sum of distances in sub-tree.""" c = s = 0 for xx in graph.get(x, []): if xx != par: cc, ss = fn(xx, x) c, s = c + cc, s + ss + cc size[x] = c + 1 return c + 1, s ans = [0]*n ans[0] = fn(0, -1)[1] stack = [0] while stack: x = stack.pop() for xx in graph.get(x, []): if not ans[xx]: ans[xx] = ans[x] + n - 2*size[xx] stack.append(xx) return ans
https://leetcode.com/problems/sum-of-distances-in-tree/discuss/1311639/Python3-post-order-and-pre-order-dfs
2
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. Example 1: Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] Output: [8,12,6,10,10,10] Explanation: The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer[0] = 8, and so on. Example 2: Input: n = 1, edges = [] Output: [0] Example 3: Input: n = 2, edges = [[1,0]] Output: [1,1] Constraints: 1 <= n <= 3 * 104 edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi The given input represents a valid tree.
[Python3] post-order & pre-order dfs
195
sum-of-distances-in-tree
0.542
ye15
Hard
13,550
834
image overlap
class Solution: def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int: n = len(img1) bestOverlap = 0 def helper(dr, dc): overlap = 0 for r in range(n): for c in range(n): nr, nc = r + dr, c + dc if nr in range(n) and nc in range(n) and img1[nr][nc] == 1 and img2[r][c] == 1: overlap += 1 return overlap for r in range(-n, n): for c in range(-n, n): bestOverlap = max(helper(r, c), bestOverlap) return bestOverlap
https://leetcode.com/problems/image-overlap/discuss/2748733/Python-(Faster-than-82)-or-Brute-force-(Recursive)-and-optimized-using-HashMap
1
You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased. Return the largest possible overlap. Example 1: Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]] Output: 3 Explanation: We translate img1 to right by 1 unit and down by 1 unit. The number of positions that have a 1 in both images is 3 (shown in red). Example 2: Input: img1 = [[1]], img2 = [[1]] Output: 1 Example 3: Input: img1 = [[0]], img2 = [[0]] Output: 0 Constraints: n == img1.length == img1[i].length n == img2.length == img2[i].length 1 <= n <= 30 img1[i][j] is either 0 or 1. img2[i][j] is either 0 or 1.
Python (Faster than 82%) | Brute force (Recursive) and optimized using HashMap
18
image-overlap
0.64
KevinJM17
Medium
13,556
835
rectangle overlap
class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: [A,B,C,D], [E,F,G,H] = rec1, rec2 return F<D and E<C and B<H and A<G - Python 3 - Junaid Mansuri
https://leetcode.com/problems/rectangle-overlap/discuss/342095/Solution-in-Python-3-(beats-100)-(-2-lines-)
2
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false. Example 1: Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] Output: true Example 2: Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] Output: false Example 3: Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3] Output: false Constraints: rec1.length == 4 rec2.length == 4 -109 <= rec1[i], rec2[i] <= 109 rec1 and rec2 represent a valid rectangle with a non-zero area.
Solution in Python 3 (beats 100%) ( 2 lines )
581
rectangle-overlap
0.436
junaidmansuri
Easy
13,572
836
new 21 game
class Solution: def new21Game(self, N: int, K: int, W: int) -> float: @lru_cache(None) def fn(n): """Return prob of of points between K and N given current point n.""" if N < n: return 0 if K <= n: return 1 if n+1 < K: return (1+W)/W*fn(n+1) - 1/W*fn(n+W+1) return 1/W*sum(fn(n+i) for i in range(1, W+1)) return fn(0)
https://leetcode.com/problems/new-21-game/discuss/938221/Python3-top-down-and-bottom-up-dp
4
Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points. Return the probability that Alice has n or fewer points. Answers within 10-5 of the actual answer are considered accepted. Example 1: Input: n = 10, k = 1, maxPts = 10 Output: 1.00000 Explanation: Alice gets a single card, then stops. Example 2: Input: n = 6, k = 1, maxPts = 10 Output: 0.60000 Explanation: Alice gets a single card, then stops. In 6 out of 10 possibilities, she is at or below 6 points. Example 3: Input: n = 21, k = 17, maxPts = 10 Output: 0.73278 Constraints: 0 <= k <= n <= 104 1 <= maxPts <= 104
[Python3] top-down & bottom-up dp
558
new-21-game
0.361
ye15
Medium
13,589
837
push dominoes
class Solution: def pushDominoes(self, dominoes: str) -> str: dominoes = 'L' + dominoes + 'R' res = [] left = 0 for right in range(1, len(dominoes)): if dominoes[right] == '.': continue middle = right - left - 1 if left: res.append(dominoes[left]) if dominoes[left] == dominoes[right]: res.append(dominoes[left] * middle) elif dominoes[left] == 'L' and dominoes[right] == 'R': res.append('.' * middle) else: res.append('R' * (middle // 2) + '.' * (middle % 2) + 'L' * (middle // 2)) left = right return ''.join(res)
https://leetcode.com/problems/push-dominoes/discuss/2629832/Easy-Python-O(n)-solution
3
There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: dominoes[i] = 'L', if the ith domino has been pushed to the left, dominoes[i] = 'R', if the ith domino has been pushed to the right, and dominoes[i] = '.', if the ith domino has not been pushed. Return a string representing the final state. Example 1: Input: dominoes = "RR.L" Output: "RR.L" Explanation: The first domino expends no additional force on the second domino. Example 2: Input: dominoes = ".L.R...LR..L.." Output: "LL.RR.LLRRLL.." Constraints: n == dominoes.length 1 <= n <= 105 dominoes[i] is either 'L', 'R', or '.'.
Easy Python O(n) solution
225
push-dominoes
0.57
namanxk
Medium
13,594
838
similar string groups
class Solution: def numSimilarGroups(self, strs: List[str]) -> int: N = len(strs) parent = [i for i in range(N)] depth = [1 for _ in range(N)] def find(idx): if idx != parent[idx]: return find(parent[idx]) return idx def union(idx1, idx2): p1 = find(idx1) p2 = find(idx2) if p1 == p2: return if depth[p1] < depth[p2]: parent[p1] = p2 elif depth[p2] < depth[p1]: parent[p2] = p1 else: parent[p2] = p1 depth[p1] += 1 def similar(w1, w2): dif_idx = -1 for idx in range(len(w1)): if w1[idx] != w2[idx]: if dif_idx < 0: dif_idx = idx else: if w1[dif_idx] != w2[idx]: return False if w2[dif_idx] != w1[idx]: return False if w1[idx+1:] != w2[idx+1:]: return False return True return True for idx in range(1, N): for pid in range(0, idx): if similar(strs[pid], strs[idx]): union(pid, idx) return len([i for i, p in enumerate(parent) if i==p])
https://leetcode.com/problems/similar-string-groups/discuss/2698654/My-Python-Union-Find-Solution
1
Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X. For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there? Example 1: Input: strs = ["tars","rats","arts","star"] Output: 2 Example 2: Input: strs = ["omv","ovm"] Output: 1 Constraints: 1 <= strs.length <= 300 1 <= strs[i].length <= 300 strs[i] consists of lowercase letters only. All words in strs have the same length and are anagrams of each other.
My Python Union Find Solution
99
similar-string-groups
0.478
MonQiQi
Hard
13,626
839
magic squares in grid
class Solution: def numMagicSquaresInside(self, G: List[List[int]]) -> int: M, N, S, t = len(G)-2, len(G[0])-2, {(8,1,6,3,5,7,4,9,2),(6,1,8,7,5,3,2,9,4),(2,7,6,9,5,1,4,3,8),(6,7,2,1,5,9,8,3,4)}, range(3) return sum((lambda x: x in S or x[::-1] in S)(tuple(sum([G[i+k][j:j+3] for k in t],[]))) for i,j in itertools.product(range(M),range(N)))
https://leetcode.com/problems/magic-squares-in-grid/discuss/381223/Two-Solutions-in-Python-3-(beats-~99)-(two-lines)
1
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous). Example 1: Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]] Output: 1 Explanation: The following subgrid is a 3 x 3 magic square: while this one is not: In total, there is only one magic square inside the given grid. Example 2: Input: grid = [[8]] Output: 0 Constraints: row == grid.length col == grid[i].length 1 <= row, col <= 10 0 <= grid[i][j] <= 15
Two Solutions in Python 3 (beats ~99%) (two lines)
624
magic-squares-in-grid
0.385
junaidmansuri
Medium
13,631
840
keys and rooms
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited_rooms = set() stack = [0] # for rooms that we need to visit and we start from room [0] while stack: room = stack.pop() visited_rooms.add(room) for key in rooms[room]: if key not in visited_rooms: stack.append(key) return len(visited_rooms) == len(rooms)
https://leetcode.com/problems/keys-and-rooms/discuss/1116836/Python3-Soln-greater-Keys-and-Rooms-stack-implementation
12
There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise. Example 1: Input: rooms = [[1],[2],[3],[]] Output: true Explanation: We visit room 0 and pick up key 1. We then visit room 1 and pick up key 2. We then visit room 2 and pick up key 3. We then visit room 3. Since we were able to visit every room, we return true. Example 2: Input: rooms = [[1,3],[3,0,1],[2],[0]] Output: false Explanation: We can not enter room number 2 since the only key that unlocks it is in that room. Constraints: n == rooms.length 2 <= n <= 1000 0 <= rooms[i].length <= 1000 1 <= sum(rooms[i].length) <= 3000 0 <= rooms[i][j] < n All the values of rooms[i] are unique.
[Python3] Soln -> Keys and Rooms [stack implementation]
620
keys-and-rooms
0.702
avEraGeC0der
Medium
13,635
841
split array into fibonacci sequence
class Solution: def splitIntoFibonacci(self, num: str) -> List[int]: def dfs(i): if i>=len(num): return len(ans)>2 n = 0 for j in range(i, len(num)): n = n*10 + int(num[j]) if n>2**31: # if number exceeds the range mentioned return False # if len < 2 we know more elements need to be appended # as size>=3 if size is already greater we check for fibonacci # as last + secondLast == curr if len(ans)<2 or (ans[-1]+ans[-2]==n): ans.append(n) if dfs(j+1): return True ans.pop() if i==j and num[j]=='0': # if trailing 0 is present return False if len(num)<=2: return [] ans = [] if dfs(0): return ans return []
https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/1579510/PYTHON-BACKTRACKING-or-THREE-PROBLEMS-ONE-SOLUTION
1
You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: 0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type), f.length >= 3, and f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2. Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from num, or return [] if it cannot be done. Example 1: Input: num = "1101111" Output: [11,0,11,11] Explanation: The output [110, 1, 111] would also be accepted. Example 2: Input: num = "112358130" Output: [] Explanation: The task is impossible. Example 3: Input: num = "0123" Output: [] Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid. Constraints: 1 <= num.length <= 200 num contains only digits.
PYTHON BACKTRACKING | THREE PROBLEMS ONE SOLUTION
150
split-array-into-fibonacci-sequence
0.383
hX_
Medium
13,680
842
guess the word
class Solution: def findSecretWord(self, words: List[str], master: 'Master') -> None: k = 1 # for tracing the number of loops matches = 0 blacklists = [[] for i in range(6)] while matches != 6: n = len(words) r = random.randint(0, n - 1) matches = master.guess(words[r]) key = words[r] # print(k, n, r, matches, key) words.pop(r) if matches == 0: for i in range(6): blacklists[i].append(key[i]) # print(blacklists) elif matches > 0 and matches < 6: candidates = [] for i in range(n - 1): count = 0 for j in range(6): if words[i][j] not in blacklists[j] and words[i][j] == key[j]: count += 1 if count >= matches: candidates.append(words[i]) words = candidates.copy() # print(words) k += 1
https://leetcode.com/problems/guess-the-word/discuss/2385099/Python-Solution-with-narrowed-candidates-and-blacklist
2
You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word. You are also given the helper object Master. You may call Master.guess(word) where word is a six-letter-long string, and it must be from words. Master.guess(word) returns: -1 if word is not from words, or an integer representing the number of exact matches (value and position) of your guess to the secret word. There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word). For each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get: "Either you took too many guesses, or you did not find the secret word." if you called Master.guess more than allowedGuesses times or if you did not call Master.guess with the secret word, or "You guessed the secret word correctly." if you called Master.guess with the secret word with the number of calls to Master.guess less than or equal to allowedGuesses. The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method). Example 1: Input: secret = "acckzz", words = ["acckzz","ccbazz","eiowzz","abcczz"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist. master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches. master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches. master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches. master.guess("abcczz") returns 4, because "abcczz" has 4 matches. We made 5 calls to master.guess, and one of them was the secret, so we pass the test case. Example 2: Input: secret = "hamada", words = ["hamada","khaled"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: Since there are two words, you can guess both. Constraints: 1 <= words.length <= 100 words[i].length == 6 words[i] consist of lowercase English letters. All the strings of wordlist are unique. secret exists in words. 10 <= allowedGuesses <= 30
[Python] Solution with narrowed candidates and blacklist
203
guess-the-word
0.418
bbshark
Hard
13,687
843
backspace string compare
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: a, A = [collections.deque(), collections.deque()], [S,T] for i in range(2): for j in A[i]: if j != '#': a[i].append(j) elif a[i]: a[i].pop() return a[0] == a[1]
https://leetcode.com/problems/backspace-string-compare/discuss/381659/Three-Solutions-in-Python-3-(With-and-Without-Deque-and-Two-Pointer)
16
Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Input: s = "ab#c", t = "ad#c" Output: true Explanation: Both s and t become "ac". Example 2: Input: s = "ab##", t = "c#d#" Output: true Explanation: Both s and t become "". Example 3: Input: s = "a#c", t = "b" Output: false Explanation: s becomes "c" while t becomes "b". Constraints: 1 <= s.length, t.length <= 200 s and t only contain lowercase letters and '#' characters. Follow up: Can you solve it in O(n) time and O(1) space?
Three Solutions in Python 3 (With and Without Deque and Two-Pointer)
2,600
backspace-string-compare
0.48
junaidmansuri
Easy
13,692
844
longest mountain in array
class Solution: def longestMountain(self, arr: List[int]) -> int: increasing = False increased = False mx = -math.inf curr = -math.inf for i in range(1, len(arr)): if arr[i] > arr[i-1]: if increasing: curr += 1 increased = True else: mx = max(curr, mx) curr = 2 increased = True increasing = True elif arr[i] < arr[i-1]: if increasing: increasing = False curr += 1 else: if increased and not increasing: mx = max(mx, curr) curr = -math.inf increased = False increasing = False if not increasing and increased: mx = max(mx, curr) return 0 if mx == -math.inf else mx
https://leetcode.com/problems/longest-mountain-in-array/discuss/1837098/Python3%3A-One-pass-O(1)-Auxiliary-Space
2
You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray. Example 1: Input: arr = [2,1,4,7,3,2,5] Output: 5 Explanation: The largest mountain is [1,4,7,3,2] which has length 5. Example 2: Input: arr = [2,2,2] Output: 0 Explanation: There is no mountain. Constraints: 1 <= arr.length <= 104 0 <= arr[i] <= 104 Follow up: Can you solve it using only one pass? Can you solve it in O(1) space?
Python3: One pass, O(1) Auxiliary Space
51
longest-mountain-in-array
0.402
DheerajGadwala
Medium
13,750
845
hand of straights
class Solution: def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: counter = Counter(hand) while counter: n = groupSize start = min(counter.keys()) while n: if start not in counter: return False counter[start] -= 1 if not counter[start]: del counter[start] start += 1 n -= 1 return True
https://leetcode.com/problems/hand-of-straights/discuss/1938042/Python3-oror-Hashmap-oror-15-line-easy-to-understand
3
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise. Example 1: Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 Output: true Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8] Example 2: Input: hand = [1,2,3,4,5], groupSize = 4 Output: false Explanation: Alice's hand can not be rearranged into groups of 4. Constraints: 1 <= hand.length <= 104 0 <= hand[i] <= 109 1 <= groupSize <= hand.length Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
Python3 || Hashmap || 15-line easy to understand
227
hand-of-straights
0.564
gulugulugulugulu
Medium
13,763
846
shortest path visiting all nodes
class Solution: def shortestPathLength(self, graph: List[List[int]]) -> int: length = len(graph) result = 0 visited_node = [] queue = [] for i in range(length): visited_node.append(set([1<<i])) queue.append([i,1<<i]) while queue: result = result + 1 new_queue = [] for node, value in queue: for neigbour_node in graph[node]: mid_node = (1<<neigbour_node)|value if mid_node not in visited_node[neigbour_node]: if mid_node+1 == 1<<length: return result visited_node[neigbour_node].add(mid_node) new_queue.append([neigbour_node, mid_node]) queue = new_queue return 0
https://leetcode.com/problems/shortest-path-visiting-all-nodes/discuss/1800062/Python-Simple-Python-Solution-Using-Breadth-First-Search
6
You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. Example 1: Input: graph = [[1,2,3],[0],[0],[0]] Output: 4 Explanation: One possible path is [1,0,2,0,3] Example 2: Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]] Output: 4 Explanation: One possible path is [0,1,4,2,3] Constraints: n == graph.length 1 <= n <= 12 0 <= graph[i].length < n graph[i] does not contain i. If graph[a] contains b, then graph[b] contains a. The input graph is always connected.
[ Python ] ✔✔ Simple Python Solution Using Breadth-First-Search 🔥✌
914
shortest-path-visiting-all-nodes
0.613
ASHOK_KUMAR_MEGHVANSHI
Hard
13,778
847
shifting letters
class Solution: def shiftingLetters(self, S: str, shifts: List[int]) -> str: final_shift = list(accumulate(shifts[::-1]))[::-1] s_list = list(S) for x in range(len(s_list)): midval = ord(s_list[x]) + final_shift[x]%26 if midval > 122: midval = midval - 26 s_list[x] = chr(midval) return ''.join(s_list)
https://leetcode.com/problems/shifting-letters/discuss/1088920/PythonPython3-Shifting-Letter-or-2-Solutions-or-One-liner
4
You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'. Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. Return the final string after all such shifts to s are applied. Example 1: Input: s = "abc", shifts = [3,5,9] Output: "rpl" Explanation: We start with "abc". After shifting the first 1 letters of s by 3, we have "dbc". After shifting the first 2 letters of s by 5, we have "igc". After shifting the first 3 letters of s by 9, we have "rpl", the answer. Example 2: Input: s = "aaa", shifts = [1,2,3] Output: "gfd" Constraints: 1 <= s.length <= 105 s consists of lowercase English letters. shifts.length == s.length 0 <= shifts[i] <= 109
[Python/Python3] Shifting Letter | 2 Solutions | One-liner
761
shifting-letters
0.454
newborncoder
Medium
13,782
848
maximize distance to closest person
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: #initialization, starting index is 0, result is res left,res,index = -1,0,0 while index != len(seats): # only right is 1 if left == -1 and seats[index] == 1: res = max(res,index) left = index index+=1 continue # only left is 1 if index == len(seats)-1 and seats[index] == 0: res = max(res,index-left) index+=1 continue # left and right both 1, sitting in the middle if seats[index] == 1: res = max(res,(index-left)//2) left = index index+=1 return res
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2706156/python%3A-easy-to-understand-3-situations
2
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed). There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return that maximum distance to the closest person. Example 1: Input: seats = [1,0,0,0,1,0,1] Output: 2 Explanation: If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. Example 2: Input: seats = [1,0,0,0] Output: 3 Explanation: If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. Example 3: Input: seats = [0,1] Output: 1 Constraints: 2 <= seats.length <= 2 * 104 seats[i] is 0 or 1. At least one seat is empty. At least one seat is occupied.
python: easy to understand, 3 situations
95
maximize-distance-to-closest-person
0.476
zoey513
Medium
13,804
849
rectangle area ii
class Solution: def rectangleArea(self, rectangles: List[List[int]]) -> int: line = [] for x1, y1, x2, y2 in rectangles: line.append((y1, x1, x2, 1)) line.append((y2, x1, x2, 0)) ans = yy = val = 0 seg = [] for y, x1, x2, tf in sorted(line): ans += val * (y - yy) yy = y if tf: insort(seg, (x1, x2)) else: seg.remove((x1, x2)) val = 0 prev = -inf for x1, x2 in seg: val += max(0, x2 - max(x1, prev)) prev = max(prev, x2) return ans % 1_000_000_007
https://leetcode.com/problems/rectangle-area-ii/discuss/1398210/Python3-sweeping
1
You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner. Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once. Return the total area. Since the answer may be too large, return it modulo 109 + 7. Example 1: Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]] Output: 6 Explanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture. From (1,1) to (2,2), the green and red rectangles overlap. From (1,0) to (2,3), all three rectangles overlap. Example 2: Input: rectangles = [[0,0,1000000000,1000000000]] Output: 49 Explanation: The answer is 1018 modulo (109 + 7), which is 49. Constraints: 1 <= rectangles.length <= 200 rectanges[i].length == 4 0 <= xi1, yi1, xi2, yi2 <= 109 xi1 <= xi2 yi1 <= yi2
[Python3] sweeping
212
rectangle-area-ii
0.537
ye15
Hard
13,840
850
loud and rich
class Solution: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: richer_count = [0 for _ in range(len(quiet))] graph = defaultdict(list) answer = [idx for idx in range(len(quiet))] ## create the graph so that we go from the richer to the poorer for rich, poor in richer: graph[rich].append(poor) richer_count[poor] += 1 ## we include the richest ones. queue = collections.deque([]) for person, rich_count in enumerate(richer_count): if not rich_count: queue.append(person) while queue: person = queue.popleft() ## pointer to the quietest person quieter_person = answer[person] for poorer in graph[person]: ## pointer to the quietest person richer than me quieter_richer = answer[poorer] ## on the answer we are storing the pointer to the quietest one. so for the next poorer we are going to store the pointer which contains the quietest answer[poorer] = min(quieter_person, quieter_richer, key = lambda prsn : quiet[prsn]) richer_count[poorer] -= 1 if not richer_count[poorer]: queue.append(poorer) return answer
https://leetcode.com/problems/loud-and-rich/discuss/2714041/Python-Pure-topological-sort
1
There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x. Example 1: Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0] Output: [5,5,2,5,4,5,6,7] Explanation: answer[0] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0. answer[7] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7. The other answers can be filled out with similar reasoning. Example 2: Input: richer = [], quiet = [0] Output: [0] Constraints: n == quiet.length 1 <= n <= 500 0 <= quiet[i] < n All the values of quiet are unique. 0 <= richer.length <= n * (n - 1) / 2 0 <= ai, bi < n ai != bi All the pairs of richer are unique. The observations in richer are all logically consistent.
Python Pure topological sort
77
loud-and-rich
0.582
Henok2011
Medium
13,841
851
peak index in a mountain array
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return (arr.index(max(arr)))
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2068528/Simple-Python-one-liner
3
An array arr is a mountain if the following properties hold: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. You must solve it in O(log(arr.length)) time complexity. Example 1: Input: arr = [0,1,0] Output: 1 Example 2: Input: arr = [0,2,1,0] Output: 1 Example 3: Input: arr = [0,10,5,2] Output: 1 Constraints: 3 <= arr.length <= 105 0 <= arr[i] <= 106 arr is guaranteed to be a mountain array.
Simple Python one-liner
144
peak-index-in-a-mountain-array
0.694
tusharkhanna575
Medium
13,845
852
car fleet
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: ans = prev = 0 for pp, ss in sorted(zip(position, speed), reverse=True): tt = (target - pp)/ss # time to arrive at target if prev < tt: ans += 1 prev = tt return ans
https://leetcode.com/problems/car-fleet/discuss/939525/Python3-greedy-O(NlogN)
17
There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination. Example 1: Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] Output: 3 Explanation: The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. Example 2: Input: target = 10, position = [3], speed = [3] Output: 1 Explanation: There is only one car, hence there is only one fleet. Example 3: Input: target = 100, position = [0,2,4], speed = [4,2,1] Output: 1 Explanation: The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Constraints: n == position.length == speed.length 1 <= n <= 105 0 < target <= 106 0 <= position[i] < target All the values of position are unique. 0 < speed[i] <= 106
[Python3] greedy O(NlogN)
1,200
car-fleet
0.501
ye15
Medium
13,892
853
k similar strings
class Solution: # DFS def kSimilarity(self, A: str, B: str) -> int: N = len(A) def dfs(A, B, pos): if A == B: return 0 while A[pos] == B[pos]: pos += 1 minCnt = float('inf') for i in range(pos + 1, N): if B[i] == A[pos] and B[i] != A[i]: B[i], B[pos] = B[pos], B[i] tmp = dfs(A, B, pos + 1) + 1 minCnt = min(tmp, minCnt) B[i], B[pos] = B[pos], B[i] return minCnt return dfs(list(A), list(B), 0) # DFS with memorization def kSimilarity1(self, A: str, B: str) -> int: N = len(A) def dfs(A, B, pos): sB = ''.join(B) if sB in map: return map[sB] if A == B: return 0 while A[pos] == B[pos]: pos += 1 minCnt = float('inf') for i in range(pos + 1, N): if B[i] == A[pos] and B[i] != A[i]: B[i], B[pos] = B[pos], B[i] tmp = dfs(A, B, pos + 1) + 1 minCnt = min(tmp, minCnt) B[i], B[pos] = B[pos], B[i] map[sB] = minCnt return minCnt map = collections.defaultdict() return dfs(list(A), list(B), 0) # BFS def kSimilarity2(self, A: str, B: str) -> int: N = len(B) q = collections.deque([B]) visited = set(B) cnt = 0 pos = 0 while q: qSize = len(q) for _ in range(qSize): cur = q.popleft() if cur == A: return cnt pos = 0 while cur[pos] == A[pos]: pos += 1 lCur = list(cur) for i in range(pos + 1, N): if lCur[i] == A[pos] and lCur[i] != A[i]: lCur[i], lCur[pos] = lCur[pos], lCur[i] sCur = ''.join(lCur) if sCur not in visited: q.append(sCur) visited.add(sCur) lCur[i], lCur[pos] = lCur[pos], lCur[i] cnt += 1 return cnt
https://leetcode.com/problems/k-similar-strings/discuss/321201/three-solutions-of-this-problem-good-for-understanding-DFS-DFS-with-memo-and-BFS
21
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2. Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar. Example 1: Input: s1 = "ab", s2 = "ba" Output: 1 Explanation: The two string are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba". Example 2: Input: s1 = "abc", s2 = "bca" Output: 2 Explanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca". Constraints: 1 <= s1.length <= 20 s2.length == s1.length s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}. s2 is an anagram of s1.
three solutions of this problem, good for understanding DFS, DFS with memo and BFS
2,900
k-similar-strings
0.401
shchshhappy
Hard
13,909
854
score of parentheses
class Solution: def scoreOfParentheses(self, s: str) -> int: stk = [0] # temp value to help us for char in s: if char == '(': stk.append(0) # new parent: current sum = 0 else: # An expression will be closed # Find its value: either 1 for empty () or 2 * its sub-expressions # we can calc both with a simple max() value = max(2 * stk.pop(), 1) # Add the expression sum to its parent current sum # Assume we have expression E that is (CHD) # where C, H, D are valid-subexpressions with values 5, 10, 4 # then E is (5+10+4) = (19) = 38 # Every time we finish an expression, we add its value to its parent # get the parent and update its sum with a finished sub-expression stk[-1] += value return stk.pop() ```
https://leetcode.com/problems/score-of-parentheses/discuss/2299821/Python-or-faster-than-83-or-easy-understanding-or-explaining-with-comments
3
Given a balanced parentheses string s, return the score of the string. The score of a balanced parentheses string is based on the following rule: "()" has score 1. AB has score A + B, where A and B are balanced parentheses strings. (A) has score 2 * A, where A is a balanced parentheses string. Example 1: Input: s = "()" Output: 1 Example 2: Input: s = "(())" Output: 2 Example 3: Input: s = "()()" Output: 2 Constraints: 2 <= s.length <= 50 s consists of only '(' and ')'. s is a balanced parentheses string.
Python | faster than 83% | easy-understanding | explaining with comments
130
score-of-parentheses
0.65
Saiko15
Medium
13,915
856
minimum cost to hire k workers
class Solution: def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float: ans, rsm = inf, 0 pq = [] # max-heap for q, w in sorted(zip(quality, wage), key=lambda x: x[1]/x[0]): rsm += q heappush(pq, -q) if len(pq) > k: rsm += heappop(pq) if len(pq) == k: ans = min(ans, rsm * w/q) return ans
https://leetcode.com/problems/minimum-cost-to-hire-k-workers/discuss/1265778/Python3-greedy-(priority-queue)
1
There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker. We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules: Every worker in the paid group must be paid at least their minimum wage expectation. In the group, each worker's pay must be directly proportional to their quality. This means if a worker’s quality is double that of another worker in the group, then they must be paid twice as much as the other worker. Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: quality = [10,20,5], wage = [70,50,30], k = 2 Output: 105.00000 Explanation: We pay 70 to 0th worker and 35 to 2nd worker. Example 2: Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3 Output: 30.66667 Explanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. Constraints: n == quality.length == wage.length 1 <= k <= n <= 104 1 <= quality[i], wage[i] <= 104
[Python3] greedy (priority queue)
83
minimum-cost-to-hire-k-workers
0.521
ye15
Hard
13,939
857
mirror reflection
class Solution: def mirrorReflection(self, p: int, q: int) -> int: L = lcm(p,q) if (L//q)%2 == 0: return 2 return (L//p)%2
https://leetcode.com/problems/mirror-reflection/discuss/2376355/Python3-oror-4-lines-geometry-w-explanation-oror-TM%3A-9281
73
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. Given the two integers p and q, return the number of the receptor that the ray meets first. The test cases are guaranteed so that the ray will meet a receptor eventually. Example 1: Input: p = 2, q = 1 Output: 2 Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall. Example 2: Input: p = 3, q = 1 Output: 1 Constraints: 1 <= q <= p <= 1000
Python3 || 4 lines, geometry, w/ explanation || T/M: 92%/81%
3,400
mirror-reflection
0.633
warrenruud
Medium
13,943
858
buddy strings
class Solution: def buddyStrings(self, s: str, goal: str) -> bool: freq1=[0]*26 freq2=[0]*26 diff =0 if(len(s)!=len(goal)): return False for i in range(len(s)): if(s[i]!=goal[i]): diff+=1 freq1[ord(s[i])-ord('a')]+=1 freq2[ord(goal[i])-ord('a')]+=1 unique= True for idx in range(len(freq1)): if(freq1[idx]!=freq2[idx]): return False if(freq1[idx]>1): unique = False if(diff==2 or (unique==False and diff==0)): return True
https://leetcode.com/problems/buddy-strings/discuss/2790774/Python-oror-Beginner-Friendly-oror-98-faster-oror-O(n)
1
Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad". Example 1: Input: s = "ab", goal = "ba" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal. Example 2: Input: s = "ab", goal = "ab" Output: false Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal. Example 3: Input: s = "aa", goal = "aa" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal. Constraints: 1 <= s.length, goal.length <= 2 * 104 s and goal consist of lowercase letters.
Python || Beginner Friendly || 98% faster || O(n)
176
buddy-strings
0.291
hasan2599
Easy
13,964
859
lemonade change
class Solution: def lemonadeChange(self, bills: List[int]) -> bool: change5=0 change10=0 change20=0 for i in range(len(bills)): if bills[i]==5: change5+=1 elif bills[i]==10: change10+=1 change5-=1 elif bills[i]==20: if change10>0 : change5-=1 change10-=1 else: change5-=3 change20+=1 if change5<0 or change10<0 or change20<0: return False return True
https://leetcode.com/problems/lemonade-change/discuss/1260496/Python-3-Easy-to-understand-Better-than-95
4
At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5. Note that you do not have any change in hand at first. Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise. Example 1: Input: bills = [5,5,5,10,20] Output: true Explanation: From the first 3 customers, we collect three $5 bills in order. From the fourth customer, we collect a $10 bill and give back a $5. From the fifth customer, we give a $10 bill and a $5 bill. Since all customers got correct change, we output true. Example 2: Input: bills = [5,5,10,10,20] Output: false Explanation: From the first two customers in order, we collect two $5 bills. For the next two customers in order, we collect a $10 bill and give back a $5 bill. For the last customer, we can not give the change of $15 back because we only have two $10 bills. Since not every customer received the correct change, the answer is false. Constraints: 1 <= bills.length <= 105 bills[i] is either 5, 10, or 20.
Python 3 Easy-to-understand Better than 95%
447
lemonade-change
0.528
mk_mohtashim
Easy
13,985
860
score after flipping matrix
class Solution: def matrixScore(self, A: List[List[int]]) -> int: m, n = len(A), len(A[0]) for i in range(m): if A[i][0] == 0: for j in range(n): A[i][j] ^= 1 for j in range(n): cnt = sum(A[i][j] for i in range(m)) if cnt < m - cnt: for i in range(m): A[i][j] ^= 1 return sum(int("".join(map(str, A[i])), 2) for i in range(m))
https://leetcode.com/problems/score-after-flipping-matrix/discuss/940701/Python3-Greedy-O(MN)
14
You are given an m x n binary matrix grid. A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's). Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. Return the highest possible score after making any number of moves (including zero moves). Example 1: Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]] Output: 39 Explanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39 Example 2: Input: grid = [[0]] Output: 1 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 20 grid[i][j] is either 0 or 1.
[Python3] Greedy O(MN)
385
score-after-flipping-matrix
0.751
ye15
Medium
14,001
861
shortest subarray with sum at least k
class Solution: def shortestSubarray(self, nums: List[int], k: int) -> int: loc = {0: -1} stack = [0] # increasing stack ans, prefix = inf, 0 for i, x in enumerate(nums): prefix += x ii = bisect_right(stack, prefix - k) if ii: ans = min(ans, i - loc[stack[ii-1]]) loc[prefix] = i while stack and stack[-1] >= prefix: stack.pop() stack.append(prefix) return ans if ans < inf else -1
https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/1515369/Python3-binary-search
4
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1. A subarray is a contiguous part of an array. Example 1: Input: nums = [1], k = 1 Output: 1 Example 2: Input: nums = [1,2], k = 4 Output: -1 Example 3: Input: nums = [2,-1,2], k = 3 Output: 3 Constraints: 1 <= nums.length <= 105 -105 <= nums[i] <= 105 1 <= k <= 109
[Python3] binary search
350
shortest-subarray-with-sum-at-least-k
0.261
ye15
Hard
14,015
862
all nodes distance k in binary tree
class Solution: def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: graph=defaultdict(list) #create undirected graph stack=[root] while stack: node=stack.pop() if node==target: targetVal=node.val if node.left: graph[node.val].append(node.left.val) graph[node.left.val].append(node.val) stack.append(node.left) if node.right: graph[node.val].append(node.right.val) graph[node.right.val].append(node.val) stack.append(node.right) #start BFS q=deque([(targetVal,0)]) #startNode distance=0 seen=set() seen.add(targetVal) res=[] while q: node,depth=q.popleft() if depth==k: res.append(node) if depth>k: break #no need to continue for neigh in graph[node]: if neigh not in seen: q.append((neigh,depth+1)) seen.add(neigh) return res
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1606006/Easy-to-understand-Python-graph-solution
6
Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order. Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2 Output: [7,4,1] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. Example 2: Input: root = [1], target = 1, k = 3 Output: [] Constraints: The number of nodes in the tree is in the range [1, 500]. 0 <= Node.val <= 500 All the values Node.val are unique. target is the value of one of the nodes in the tree. 0 <= k <= 1000
Easy to understand Python 🐍 graph solution
439
all-nodes-distance-k-in-binary-tree
0.621
InjySarhan
Medium
14,020
863
shortest path to get all keys
class Solution: def shortestPathAllKeys(self, grid: List[str]) -> int: m, n = len(grid), len(grid[0]) ii = jj = total = 0 for i in range(m): for j in range(n): if grid[i][j] == "@": ii, jj = i, j elif grid[i][j].islower(): total += 1 ans = 0 seen = {(ii, jj, 0)} queue = [(ii, jj, 0)] while queue: newq = [] for i, j, keys in queue: if keys == (1 << total) - 1: return ans for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] != "#": kk = keys if grid[ii][jj].islower(): kk |= 1 << ord(grid[ii][jj]) - 97 if (ii, jj, kk) in seen or grid[ii][jj].isupper() and not kk &amp; (1 << ord(grid[ii][jj])-65): continue newq.append((ii, jj, kk)) seen.add((ii, jj, kk)) ans += 1 queue = newq return -1
https://leetcode.com/problems/shortest-path-to-get-all-keys/discuss/1516812/Python3-bfs
4
You are given an m x n grid grid where: '.' is an empty cell. '#' is a wall. '@' is the starting point. Lowercase letters represent keys. Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys. If it is impossible, return -1. Example 1: Input: grid = ["@.a..","###.#","b.A.B"] Output: 8 Explanation: Note that the goal is to obtain all the keys not to open all the locks. Example 2: Input: grid = ["@..aA","..B#.","....b"] Output: 6 Example 3: Input: grid = ["@Aa"] Output: -1 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 30 grid[i][j] is either an English letter, '.', '#', or '@'. There is exactly one '@' in the grid. The number of keys in the grid is in the range [1, 6]. Each key in the grid is unique. Each key in the grid has a matching lock.
[Python3] bfs
222
shortest-path-to-get-all-keys
0.455
ye15
Hard
14,034
864
smallest subtree with all the deepest nodes
class Solution: def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: @lru_cache(None) def fn(node): """Return height of tree rooted at node.""" if not node: return 0 return 1 + max(fn(node.left), fn(node.right)) node = root while node: left, right = fn(node.left), fn(node.right) if left == right: return node elif left > right: node = node.left else: node = node.right
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/940618/Python3-dfs-O(N)
5
Given the root of a binary tree, the depth of each node is the shortest distance to the root. Return the smallest subtree such that it contains all the deepest nodes in the original tree. A node is called the deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node. Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest nodes of the tree. Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it. Example 2: Input: root = [1] Output: [1] Explanation: The root is the deepest node in the tree. Example 3: Input: root = [0,1,3,null,2] Output: [2] Explanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest. Constraints: The number of nodes in the tree will be in the range [1, 500]. 0 <= Node.val <= 500 The values of the nodes in the tree are unique. Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
[Python3] dfs O(N)
140
smallest-subtree-with-all-the-deepest-nodes
0.686
ye15
Medium
14,037
865
prime palindrome
class Solution: def primePalindrome(self, N: int) -> int: def isPrime(N): return N > 1 and all(N % d for d in range(2, int(N**0.5)+1)) # N must be a palindrome with odd number of digits. # The return value will have odd number of digits too. def nextPalindrome(N): if N in [999, 99999, 9999999]: return (N + 1) * 10 + 1 n = str(N // 10 ** (len(str(N))//2) + 1) return int(n + n[-2::-1]) if N <= 11: while not isPrime(N): N += 1 return N if (digits := len(str(N))) % 2 == 0: N = 10 ** digits + 1 else: n = str(N // 10 ** (len(str(N))//2)) if (p := int(n + n[-2::-1])) >= N: N = p else: N = nextPalindrome(p) while not isPrime(N): N = nextPalindrome(N) return N
https://leetcode.com/problems/prime-palindrome/discuss/707393/Python3-check-next-palindrome-Prime-Palindrome
1
Given an integer n, return the smallest prime palindrome greater than or equal to n. An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number. For example, 2, 3, 5, 7, 11, and 13 are all primes. An integer is a palindrome if it reads the same from left to right as it does from right to left. For example, 101 and 12321 are palindromes. The test cases are generated so that the answer always exists and is in the range [2, 2 * 108]. Example 1: Input: n = 6 Output: 7 Example 2: Input: n = 8 Output: 11 Example 3: Input: n = 13 Output: 101 Constraints: 1 <= n <= 108
Python3 check next palindrome - Prime Palindrome
484
prime-palindrome
0.258
r0bertz
Medium
14,053
866
transpose matrix
class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: m,n=len(matrix),len(matrix[0]) ans = [[None] * m for _ in range(n)] for i in range(m): for j in range(n): ans[j][i]=matrix[i][j] return ans
https://leetcode.com/problems/transpose-matrix/discuss/2100098/Python-Easy-2-Approaches-one-liner
18
Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: matrix = [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]] Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 1000 1 <= m * n <= 105 -109 <= matrix[i][j] <= 109
Python Easy - 2 Approaches - one liner
2,600
transpose-matrix
0.635
constantine786
Easy
14,060
867
binary gap
class Solution: def binaryGap(self, n: int) -> int: if(bin(n).count('1'))==1: return 0 c=0 x=bin(n)[2:] for i in range(len(x)): if(x[i]=='1'): j=i+1 while j<len(x): if(x[j]=='1'): c=max(j-i,c) break j+=1 return c
https://leetcode.com/problems/binary-gap/discuss/1306246/Easy-Python-Solution(100)
2
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3. Example 1: Input: n = 22 Output: 2 Explanation: 22 in binary is "10110". The first adjacent pair of 1's is "10110" with a distance of 2. The second adjacent pair of 1's is "10110" with a distance of 1. The answer is the largest of these two distances, which is 2. Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined. Example 2: Input: n = 8 Output: 0 Explanation: 8 in binary is "1000". There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0. Example 3: Input: n = 5 Output: 2 Explanation: 5 in binary is "101". Constraints: 1 <= n <= 109
Easy Python Solution(100%)
204
binary-gap
0.619
Sneh17029
Easy
14,111
868
reordered power of 2
class Solution: def reorderedPowerOf2(self, n: int) -> bool: for i in range(32): if Counter(str(n))==Counter(str(2**i)): return True return False
https://leetcode.com/problems/reordered-power-of-2/discuss/2485025/python-short-and-precise-answer
3
You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return true if and only if we can do this so that the resulting number is a power of two. Example 1: Input: n = 1 Output: true Example 2: Input: n = 10 Output: false Constraints: 1 <= n <= 109
python short and precise answer
90
reordered-power-of-2
0.639
benon
Medium
14,131
869
advantage shuffle
class Solution: def advantageCount(self, A: List[int], B: List[int]) -> List[int]: sorted_a = sorted(A, reverse=True) # descending order sorted_b = sorted(enumerate(B), key=lambda x: (x[1], x[0]), reverse=True) # descending order with original index n, j = len(B), 0 ans = [-1] * n for i, (ori_idx, val) in enumerate(sorted_b): # A greedily tries to cover value in B as large as possible if sorted_a[j] > val: ans[ori_idx], j = sorted_a[j], j+1 for i in range(n): # assign rest value in A to ans if ans[i] == -1: ans[i], j = sorted_a[j], j+1 return ans
https://leetcode.com/problems/advantage-shuffle/discuss/843628/Python-3-or-Greedy-Two-Pointers-or-Explanations
3
You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. Return any permutation of nums1 that maximizes its advantage with respect to nums2. Example 1: Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11] Output: [2,11,7,15] Example 2: Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11] Output: [24,32,8,12] Constraints: 1 <= nums1.length <= 105 nums2.length == nums1.length 0 <= nums1[i], nums2[i] <= 109
Python 3 | Greedy, Two Pointers | Explanations
322
advantage-shuffle
0.517
idontknoooo
Medium
14,165
870
minimum number of refueling stops
class Solution: # Here's the plan: # # 1) We only need to be concerned with two quantities: the dist traveled (pos) # and the fuel acquired (fuel). We have to refuel before pos > fuel. # # 2) Because we have an infinite capacity tank, we only have to plan where to acquire # fuel before pos > fuel, and common sense says to stop at the station within range # with the most fuel. # # 3) And that's a job for a heap. we heappush the stations that are within range of present # fuel, and heappop the best choice if and when we need fuel. # # 4) We are finished when a) we have acquired sufficient fuel such that fuel >= target # (return # of fuelings), or b) fuel < target and the heap is empty (return -1). def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int: fuel, heap, count = startFuel, [], 0 # <-- initialize some stuff stations.append([target, 0]) # <-- this handles the "stations = []" test while stations: if fuel >= target: return count # <-- 4) while stations and stations[0][0] <= fuel: # <-- 3) _, liters = stations.pop(0) heappush(heap,-liters) if not heap: return -1 # <-- 4) fuel-= heappop(heap) count+= 1
https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2454099/Python3-oror-10-lines-heap-wexplanation-oror-TM%3A-90-98
3
A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1. Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived. Example 1: Input: target = 1, startFuel = 1, stations = [] Output: 0 Explanation: We can reach the target without refueling. Example 2: Input: target = 100, startFuel = 1, stations = [[10,100]] Output: -1 Explanation: We can not reach the target (or even the first gas station). Example 3: Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]] Output: 2 Explanation: We start with 10 liters of fuel. We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas. Then, we drive from position 10 to position 60 (expending 50 liters of fuel), and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target. We made 2 refueling stops along the way, so we return 2. Constraints: 1 <= target, startFuel <= 109 0 <= stations.length <= 500 1 <= positioni < positioni+1 < target 1 <= fueli < 109
Python3 || 10 lines, heap, w/explanation || T/M: 90%/ 98%
140
minimum-number-of-refueling-stops
0.398
warrenruud
Hard
14,170
871
leaf similar trees
class Solution: def __init__(self): self.n = [] def dfs(self, root): if root: # checking if the node is leaf if not root.left and not root.right: # appends the leaf nodes to the list - self.n self.n.append(root.val) self.dfs(root.left) self.dfs(root.right) def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: self.dfs(root1) a = self.n self.n = [] self.dfs(root2) if a == self.n: return True else: return False
https://leetcode.com/problems/leaf-similar-trees/discuss/1564699/Easy-Python-Solution-or-Faster-than-98-(24ms)
4
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. Example 1: Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8] Output: true Example 2: Input: root1 = [1,2,3], root2 = [1,3,2] Output: false Constraints: The number of nodes in each tree will be in the range [1, 200]. Both of the given trees will have values in the range [0, 200].
Easy Python Solution | Faster than 98% (24ms)
174
leaf-similar-trees
0.652
the_sky_high
Easy
14,183
872
length of longest fibonacci subsequence
class Solution: def lenLongestFibSubseq(self, arr: List[int]) -> int: arrset=set(arr) res=0 for i in range(len(arr)): for j in range(i+1,len(arr)): a,b,l=arr[i],arr[j],2 while(a+b in arrset): a,b,l=b,a+b,l+1 res=max(res,l) return res if res>=3 else 0
https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/2732493/python-simple-solution-faster
0
A sequence x1, x2, ..., xn is Fibonacci-like if: n >= 3 xi + xi+1 == xi+2 for all i + 2 <= n Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0. A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8]. Example 1: Input: arr = [1,2,3,4,5,6,7,8] Output: 5 Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8]. Example 2: Input: arr = [1,3,7,11,12,14,18] Output: 3 Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18]. Constraints: 3 <= arr.length <= 1000 1 <= arr[i] < arr[i + 1] <= 109
python simple solution faster
8
length-of-longest-fibonacci-subsequence
0.486
Raghunath_Reddy
Medium
14,195
873
walking robot simulation
class Solution: def robotSim(self, c: List[int], b: List[List[int]]) -> int: x, y, d, b, M = 0, 0, 0, set([tuple(i) for i in b]), 0 for i in c: if i < 0: d = (d + 2*i + 3)%4 else: if d in [1,3]: for x in range(x, x+(i+1)*(2-d), 2-d): if (x+(2-d), y) in b: break else: for y in range(y, y+(i+1)*(1-d), 1-d): if (x, y+(1-d)) in b: break M = max(M, x**2 + y**2) return M - Junaid Mansuri (LeetCode ID)@hotmail.com
https://leetcode.com/problems/walking-robot-simulation/discuss/381840/Solution-in-Python-3
3
A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands: -2: Turn left 90 degrees. -1: Turn right 90 degrees. 1 <= k <= 9: Move forward k units, one unit at a time. Some of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command. Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25). Note: North means +Y direction. East means +X direction. South means -Y direction. West means -X direction. There can be obstacle in [0,0]. Example 1: Input: commands = [4,-1,3], obstacles = [] Output: 25 Explanation: The robot starts at (0, 0): 1. Move north 4 units to (0, 4). 2. Turn right. 3. Move east 3 units to (3, 4). The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away. Example 2: Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]] Output: 65 Explanation: The robot starts at (0, 0): 1. Move north 4 units to (0, 4). 2. Turn right. 3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4). 4. Turn left. 5. Move north 4 units to (1, 8). The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away. Example 3: Input: commands = [6,-1,-1,6], obstacles = [] Output: 36 Explanation: The robot starts at (0, 0): 1. Move north 6 units to (0, 6). 2. Turn right. 3. Turn right. 4. Move south 6 units to (0, 0). The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away. Constraints: 1 <= commands.length <= 104 commands[i] is either -2, -1, or an integer in the range [1, 9]. 0 <= obstacles.length <= 104 -3 * 104 <= xi, yi <= 3 * 104 The answer is guaranteed to be less than 231.
Solution in Python 3
513
walking-robot-simulation
0.384
junaidmansuri
Medium
14,202
874
koko eating bananas
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: k = 1 while True: total_time = 0 for i in piles: total_time += ceil(i / k) if total_time > h: k += 1 else: return k
https://leetcode.com/problems/koko-eating-bananas/discuss/1705145/Python-BinarySearch-%2B-Optimizations-or-Explained
20
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours. Example 1: Input: piles = [3,6,7,11], h = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], h = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], h = 6 Output: 23 Constraints: 1 <= piles.length <= 104 piles.length <= h <= 109 1 <= piles[i] <= 109
[Python] BinarySearch + Optimizations | Explained
814
koko-eating-bananas
0.521
anCoderr
Medium
14,210
875
middle of the linked list
class Solution: def middleNode(self, head: ListNode) -> ListNode: slow, fast = head, head while fast: fast = fast.next if fast: fast = fast.next else: # fast has reached the end of linked list # slow is on the middle point now break slow = slow.next return slow
https://leetcode.com/problems/middle-of-the-linked-list/discuss/526372/PythonJSJavaGoC%2B%2B-O(n)-by-two-pointers-90%2B-w-Diagram
45
Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node. Example 1: Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3. Example 2: Input: head = [1,2,3,4,5,6] Output: [4,5,6] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. Constraints: The number of nodes in the list is in the range [1, 100]. 1 <= Node.val <= 100
Python/JS/Java/Go/C++ O(n) by two-pointers 90%+ [w/ Diagram]
2,800
middle-of-the-linked-list
0.739
brianchiang_tw
Easy
14,233
876
stone game
class Solution: def stoneGame(self, piles: List[int]) -> bool: # Alex always win finally, no matter which step he takes first. return True
https://leetcode.com/problems/stone-game/discuss/643412/Python-O(-n2-)-by-top-down-DP-w-Comment
4
Alice and Bob play a game with piles of stones. There are an even 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. The total number of stones across all the piles is odd, so there are no ties. Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins. Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins. Example 1: Input: piles = [5,3,4,5] Output: true Explanation: Alice starts first, and can only take the first 5 or the last 5. Say she takes the first 5, so that the row becomes [3, 4, 5]. If Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points. If Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points. This demonstrated that taking the first 5 was a winning move for Alice, so we return true. Example 2: Input: piles = [3,7,2,3] Output: true Constraints: 2 <= piles.length <= 500 piles.length is even. 1 <= piles[i] <= 500 sum(piles[i]) is odd.
Python O( n^2 ) by top-down DP [w/ Comment]
642
stone-game
0.697
brianchiang_tw
Medium
14,263
877
nth magical number
class Solution: def nthMagicalNumber(self, n: int, a: int, b: int) -> int: # inclusion-exclusion principle ab = lcm(a,b) lo, hi = 0, n*min(a, b) while lo < hi: mid = lo + hi >> 1 if mid//a + mid//b - mid//ab < n: lo = mid + 1 else: hi = mid return lo % 1_000_000_007
https://leetcode.com/problems/nth-magical-number/discuss/1545825/Python3-binary-search
1
A positive integer is magical if it is divisible by either a or b. Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7. Example 1: Input: n = 1, a = 2, b = 3 Output: 2 Example 2: Input: n = 4, a = 2, b = 3 Output: 6 Constraints: 1 <= n <= 109 2 <= a, b <= 4 * 104
[Python3] binary search
106
nth-magical-number
0.357
ye15
Hard
14,280
878
profitable schemes
class Solution: def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int: # A[i][j][k] = # schemes using subset of first i crimes, using <= j people, with total profit >= k A = [[[0 for k in range(minProfit + 1)] for j in range(n + 1)] for i in range(len(profit) + 1)] # if using first 0 crimes, only one way, and that if minProfit <= 0 for j in range(n + 1): A[0][j][0] = 1 for i in range(1, len(profit) + 1): for j in range(n + 1): for k in range(minProfit + 1): # we are here calculating A[j][j][k] # two cases, either we use i'th crime or not. # but if i'th crime requires more than j people, we con't use it if group[i-1] > j: A[i][j][k] = A[i-1][j][k] else: # if i'th crime gets profit greater than k, then we have no restriction # on the rest of the groups if profit[i-1] > k: A[i][j][k] = (A[i-1][j][k] + A[i-1][j-group[i-1]][0]) % (10**9 + 7) else: A[i][j][k] = (A[i-1][j][k] + A[i-1][j-group[i-1]][k-profit[i-1]]) % (10**9 + 7) return A[len(profit)][n][minProfit]
https://leetcode.com/problems/profitable-schemes/discuss/2661178/Python3-DP
0
There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n. Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7. Example 1: Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3] Output: 2 Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1. In total, there are 2 schemes. Example 2: Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8] Output: 7 Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one. There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). Constraints: 1 <= n <= 100 0 <= minProfit <= 100 1 <= group.length <= 100 1 <= group[i] <= 100 profit.length == group.length 0 <= profit[i] <= 100
Python3 DP
11
profitable-schemes
0.404
jbradleyglenn
Hard
14,282
879
decoded string at index
class Solution: def decodeAtIndex(self, s: str, k: int) -> str: lens = [0] for c in s: if c.isalpha(): lens.append(lens[-1] + 1) else: lens.append(lens[-1] * int(c)) for idx in range(len(s), 0, -1): k %= lens[idx] if k == 0 and s[idx - 1].isalpha(): return s[idx - 1] return
https://leetcode.com/problems/decoded-string-at-index/discuss/1585059/Python3-Solution-with-using-stack
2
You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: If the character read is a letter, that letter is written onto the tape. If the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total. Given an integer k, return the kth letter (1-indexed) in the decoded string. Example 1: Input: s = "leet2code3", k = 10 Output: "o" Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode". The 10th letter in the string is "o". Example 2: Input: s = "ha22", k = 5 Output: "h" Explanation: The decoded string is "hahahaha". The 5th letter is "h". Example 3: Input: s = "a2345678999999999999999", k = 1 Output: "a" Explanation: The decoded string is "a" repeated 8301530446056247680 times. The 1st letter is "a". Constraints: 2 <= s.length <= 100 s consists of lowercase English letters and digits 2 through 9. s starts with a letter. 1 <= k <= 109 It is guaranteed that k is less than or equal to the length of the decoded string. The decoded string is guaranteed to have less than 263 letters.
[Python3] Solution with using stack
217
decoded-string-at-index
0.283
maosipov11
Medium
14,286
880
boats to save people
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() lo = 0 hi = len(people)-1 boats = 0 while lo <= hi: if people[lo] + people[hi] <= limit: lo += 1 hi -= 1 else: hi -= 1 boats += 1 return boats
https://leetcode.com/problems/boats-to-save-people/discuss/1878155/Explained-Python-2-Pointers-Solution
26
You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person. Example 1: Input: people = [1,2], limit = 3 Output: 1 Explanation: 1 boat (1, 2) Example 2: Input: people = [3,2,2,1], limit = 3 Output: 3 Explanation: 3 boats (1, 2), (2) and (3) Example 3: Input: people = [3,5,3,4], limit = 5 Output: 4 Explanation: 4 boats (3), (3), (4), (5) Constraints: 1 <= people.length <= 5 * 104 1 <= people[i] <= limit <= 3 * 104
⭐Explained Python 2 Pointers Solution
3,400
boats-to-save-people
0.527
anCoderr
Medium
14,290
881
reachable nodes in subdivided graph
class Solution: def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int: graph = collections.defaultdict(dict) for s, e, n in edges: # n: subnodes in edge graph[s][e] = n graph[e][s] = n seen = set() # (start, end, step) q = collections.deque() for n in graph[0]: q.append((0, n, 0)) res = 1 move = maxMoves while q: for _ in range(len(q)): start, end, step = q.popleft() seen.add((start, end, step)) seen.add((end, start, graph[end][start]-step+1)) if step == graph[start][end] + 1: #check if reached next node for n in graph[end]: if (end, n, 1) not in seen: q.append((end, n, 1)) res += 1 else: if (start, end, step+1) not in seen and (end, start, graph[end][start]-step) not in seen: q.append((start, end, step+1)) res += 1 move -= 1 if move == 0: break return res
https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/discuss/2568608/BFS-intuitive
0
You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge. To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi]. In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less. Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph. Example 1: Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3 Output: 13 Explanation: The edge subdivisions are shown in the image above. The nodes that are reachable are highlighted in yellow. Example 2: Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4 Output: 23 Example 3: Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5 Output: 1 Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable. Constraints: 0 <= edges.length <= min(n * (n - 1) / 2, 104) edges[i].length == 3 0 <= ui < vi < n There are no multiple edges in the graph. 0 <= cnti <= 104 0 <= maxMoves <= 109 1 <= n <= 3000
BFS intuitive
15
reachable-nodes-in-subdivided-graph
0.503
scr112
Hard
14,319
882
projection area of 3d shapes
class Solution: def projectionArea(self, grid: List[List[int]]) -> int: p = len(grid) x, y, c = [], [0]*p, 0 for i in range(p): x.append(0) for j in range(p): n = grid[i][j] if n > 0: c += 1 if x[i] < n: x[i] = n if y[j] < n: y[j] = n return (sum(x)+sum(y)+c)
https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/1357263/Python3-dollarolution
1
You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j). We view the projection of these cubes onto the xy, yz, and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections. Example 1: Input: grid = [[1,2],[3,4]] Output: 17 Explanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane. Example 2: Input: grid = [[2]] Output: 5 Example 3: Input: grid = [[1,0],[0,2]] Output: 8 Constraints: n == grid.length == grid[i].length 1 <= n <= 50 0 <= grid[i][j] <= 50
Python3 $olution
105
projection-area-of-3d-shapes
0.708
AakRay
Easy
14,322
883
uncommon words from two sentences
class Solution: def uncommonFromSentences(self, A: str, B: str) -> List[str]: uncommon = [] def find_uncommon(s , t): ans = [] for i in s: if(s.count(i) == 1 and i not in t): ans.append(i) return ans return find_uncommon(A.split() , B.split()) + find_uncommon(B.split() , A.split())
https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1219754/Python3-99-Faster-Solution
3
A sentence is a string of single-space separated words where each word consists only of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order. Example 1: Input: s1 = "this apple is sweet", s2 = "this apple is sour" Output: ["sweet","sour"] Example 2: Input: s1 = "apple apple", s2 = "banana" Output: ["banana"] Constraints: 1 <= s1.length, s2.length <= 200 s1 and s2 consist of lowercase English letters and spaces. s1 and s2 do not have leading or trailing spaces. All the words in s1 and s2 are separated by a single space.
[Python3] 99% Faster Solution
188
uncommon-words-from-two-sentences
0.66
VoidCupboard
Easy
14,333
884
spiral matrix iii
class Solution: def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]: ans = [] left, right = cStart, cStart+1 top, bottom = rStart, rStart+1 current = 1 move = 0 while current <= rows*cols: # fill top for i in range(left+move, right+1): if self.inbound(top, i, rows, cols): ans.append([top, i]) current += 1 left -= 1 # fill right for i in range(top+1, bottom+1): if self.inbound(i, right, rows, cols): ans.append([i, right]) current += 1 top -= 1 # fill bottom for i in range(right-1, left-1, -1): if self.inbound(bottom, i, rows, cols): ans.append([bottom, i]) current += 1 right += 1 # fill left for i in range(bottom-1, top-1, -1): if self.inbound(i, left, rows, cols): ans.append([i, left]) current += 1 bottom += 1 move = 1 return ans def inbound(self, r, c, rows, cols): return 0<=r<rows and 0<=c<cols
https://leetcode.com/problems/spiral-matrix-iii/discuss/2718364/Easy-Python-Solution-Based-on-Spiral-Matrix-I-and-II
3
You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them. Example 1: Input: rows = 1, cols = 4, rStart = 0, cStart = 0 Output: [[0,0],[0,1],[0,2],[0,3]] Example 2: Input: rows = 5, cols = 6, rStart = 1, cStart = 4 Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]] Constraints: 1 <= rows, cols <= 100 0 <= rStart < rows 0 <= cStart < cols
Easy Python Solution Based on Spiral Matrix I and II
77
spiral-matrix-iii
0.732
Naboni
Medium
14,360
885
possible bipartition
class Solution: def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: dislike = [[] for _ in range(n)] for a, b in dislikes: dislike[a-1].append(b-1) dislike[b-1].append(a-1) groups = [0] * n for p in range(n): if groups[p] == 0: groups[p] = 1 q = deque([p]) while q: # bfs a = q.pop() for b in dislike[a]: if groups[b] == 0: groups[b] = 1 if groups[a] == 2 else 2 q.appendleft(b) elif groups[a] == groups[b]: return False return True
https://leetcode.com/problems/possible-bipartition/discuss/2593419/Clean-Python3-or-Bipartite-Graph-w-BFS-or-Faster-Than-99
2
We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way. Example 1: Input: n = 4, dislikes = [[1,2],[1,3],[2,4]] Output: true Explanation: The first group has [1,4], and the second group has [2,3]. Example 2: Input: n = 3, dislikes = [[1,2],[1,3],[2,3]] Output: false Explanation: We need at least 3 groups to divide them. We cannot put them in two groups. Constraints: 1 <= n <= 2000 0 <= dislikes.length <= 104 dislikes[i].length == 2 1 <= ai < bi <= n All the pairs of dislikes are unique.
Clean Python3 | Bipartite Graph w/ BFS | Faster Than 99%
148
possible-bipartition
0.485
ryangrayson
Medium
14,370
886
super egg drop
class Solution: def superEggDrop(self, k: int, n: int) -> int: @cache def fn(n, k): """Return min moves given n floors and k eggs.""" if k == 1: return n if n == 0: return 0 lo, hi = 1, n + 1 while lo < hi: mid = lo + hi >> 1 if fn(mid-1, k-1) < fn(n-mid, k): lo = mid + 1 else: hi = mid return 1 + max(fn(lo-1, k-1), fn(n-lo, k)) return fn(n, k)
https://leetcode.com/problems/super-egg-drop/discuss/1468875/Python3-a-few-solutions
4
You are given k identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. Example 1: Input: k = 1, n = 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know that f = 0. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. If it does not break, then we know f = 2. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. Example 2: Input: k = 2, n = 6 Output: 3 Example 3: Input: k = 3, n = 14 Output: 4 Constraints: 1 <= k <= 100 1 <= n <= 104
[Python3] a few solutions
210
super-egg-drop
0.272
ye15
Hard
14,384
887
fair candy swap
class Solution: def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]: difference = (sum(A) - sum(B)) / 2 A = set(A) for candy in set(B): if difference + candy in A: return [difference + candy, candy]
https://leetcode.com/problems/fair-candy-swap/discuss/1088075/Python.-Super-simple-solution.
9
Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists. Example 1: Input: aliceSizes = [1,1], bobSizes = [2,2] Output: [1,2] Example 2: Input: aliceSizes = [1,2], bobSizes = [2,3] Output: [1,2] Example 3: Input: aliceSizes = [2], bobSizes = [1,3] Output: [2,3] Constraints: 1 <= aliceSizes.length, bobSizes.length <= 104 1 <= aliceSizes[i], bobSizes[j] <= 105 Alice and Bob have a different total number of candies. There will be at least one valid answer for the given input.
Python. Super simple solution.
1,000
fair-candy-swap
0.605
m-d-f
Easy
14,388
888
construct binary tree from preorder and postorder traversal
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: mp = {x: i for i, x in enumerate(inorder)} # relative position root = None stack = [] for x in preorder: if not root: root = node = TreeNode(x) elif mp[x] < mp[stack[-1].val]: stack[-1].left = node = TreeNode(x) else: while stack and mp[stack[-1].val] < mp[x]: node = stack.pop() # retrace node.right = node = TreeNode(x) stack.append(node) return root
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/946726/Python3-consistent-soln-for-105-106-and-889
3
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree. If there exist multiple answers, you can return any of them. Example 1: Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1] Output: [1,2,3,4,5,6,7] Example 2: Input: preorder = [1], postorder = [1] Output: [1] Constraints: 1 <= preorder.length <= 30 1 <= preorder[i] <= preorder.length All the values of preorder are unique. postorder.length == preorder.length 1 <= postorder[i] <= postorder.length All the values of postorder are unique. It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.
[Python3] consistent soln for 105, 106 and 889
128
construct-binary-tree-from-preorder-and-postorder-traversal
0.708
ye15
Medium
14,402
889
find and replace pattern
class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: def helper( s ): # dictionary # key : character # value : serial number in string type char_index_dict = dict() # given each unique character a serial number for character in s: if character not in char_index_dict: char_index_dict[character] = str( len(char_index_dict) ) # gererate corresponding pattern string return ''.join( map(char_index_dict.get, s) ) #-------------------------------------------------------- pattern_string = helper(pattern) return [ word for word in words if helper(word) == pattern_string ]
https://leetcode.com/problems/find-and-replace-pattern/discuss/500786/Python-O(-nk-)-sol.-by-pattern-matching.-80%2B-With-explanation
9
Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order. A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. Example 1: Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" Output: ["mee","aqq"] Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. Example 2: Input: words = ["a","b","c"], pattern = "a" Output: ["a","b","c"] Constraints: 1 <= pattern.length <= 20 1 <= words.length <= 50 words[i].length == pattern.length pattern and words[i] are lowercase English letters.
Python O( nk ) sol. by pattern matching. 80%+ [ With explanation ]
835
find-and-replace-pattern
0.779
brianchiang_tw
Medium
14,412
890
sum of subsequence widths
class Solution: def sumSubseqWidths(self, nums: List[int]) -> int: MOD = 10**9 + 7 n = len(nums) nums.sort() dp = [0] * n p = 2 temp = nums[0] for i in range(1, n): dp[i] = ((dp[i-1] + ((p-1)*nums[i])%MOD)%MOD - temp)%MOD p = (2*p)%MOD temp = ((2*temp)%MOD + nums[i])%MOD return dp[n-1]
https://leetcode.com/problems/sum-of-subsequence-widths/discuss/2839381/MATH-%2B-DP
0
The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. Example 1: Input: nums = [2,1,3] Output: 6 Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. Example 2: Input: nums = [2] Output: 0 Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105
MATH + DP
2
sum-of-subsequence-widths
0.365
roboto7o32oo3
Hard
14,458
891
surface area of 3d shapes
class Solution: def surfaceArea(self, grid: List[List[int]]) -> int: l = len(grid) area=0 for row in range(l): for col in range(l): if grid[row][col]: area += (grid[row][col]*4) +2 #surface area of each block if blocks werent connected if row: #row>0 area -= min(grid[row][col],grid[row-1][col])*2 #subtracting as area is common among two blocks if col: #col>0 area -= min(grid[row][col],grid[row][col-1])*2 #subtracting as area is common among two blocks return area
https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/2329304/Simple-Python-explained
3
You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j). After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return the total surface area of the resulting shapes. Note: The bottom face of each shape counts toward its surface area. Example 1: Input: grid = [[1,2],[3,4]] Output: 34 Example 2: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 32 Example 3: Input: grid = [[2,2,2],[2,1,2],[2,2,2]] Output: 46 Constraints: n == grid.length == grid[i].length 1 <= n <= 50 0 <= grid[i][j] <= 50
Simple Python explained
153
surface-area-of-3d-shapes
0.633
sunakshi132
Easy
14,462
892
groups of special equivalent strings
class Solution: def numSpecialEquivGroups(self, A: List[str]) -> int: signature = set() # Use pair of sorted even substring and odd substring as unique key for idx, s in enumerate(A): signature.add( ''.join( sorted( s[::2] ) ) + ''.join( sorted( s[1::2] ) ) ) return len( signature )
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/536199/Python-O(n-*-k-lg-k)-sol.-by-signature.-90%2B-w-Hint
8
You are given an array of strings of the same length words. In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i]. Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j]. For example, words[i] = "zzxy" and words[j] = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz". A group of special-equivalent strings from words is a non-empty subset of words such that: Every pair of strings in the group are special equivalent, and The group is the largest size possible (i.e., there is not a string words[i] not in the group such that words[i] is special-equivalent to every string in the group). Return the number of groups of special-equivalent strings from words. Example 1: Input: words = ["abcd","cdab","cbad","xyzz","zzxy","zzyx"] Output: 3 Explanation: One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. Note that in particular, "zzxy" is not special equivalent to "zzyx". Example 2: Input: words = ["abc","acb","bac","bca","cab","cba"] Output: 3 Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 20 words[i] consist of lowercase English letters. All the strings are of the same length.
Python O(n * k lg k) sol. by signature. 90%+ [w/ Hint]
512
groups-of-special-equivalent-strings
0.709
brianchiang_tw
Medium
14,470
893
all possible full binary trees
class Solution: def allPossibleFBT(self, N: int) -> List[TreeNode]: # Any full binary trees should contain odd number of nodes # therefore, if N is even, return 0 if N % 2 == 0: return [] # for all odd n that are less than N, store all FBTs trees_all = collections.defaultdict(list) #when there is one node, only one tree is available trees_all[1] = [TreeNode(0)] for n in range(3, N+1, 2): for k in range(1, n, 2): # trees with k nodes on the left # trees with n - k - 1 nodes on the right # consider all potential pairs for tree1, tree2 in itertools.product(trees_all[k], trees_all[n-k-1]): tree = TreeNode(0) tree.left = tree1 tree.right = tree2 trees_all[n].append(tree) return trees_all[N]
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/339611/Python-solution-without-recursion-beets-100-speed
8
Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order. A full binary tree is a binary tree where each node has exactly 0 or 2 children. Example 1: Input: n = 7 Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]] Example 2: Input: n = 3 Output: [[0,0,0]] Constraints: 1 <= n <= 20
Python solution without recursion, beets 100% speed
825
all-possible-full-binary-trees
0.8
KateMelnykova
Medium
14,479
894
monotonic array
class Solution: def isMonotonic(self, A: List[int]) -> bool: if A[-1] < A[0]: A = A[::-1] for i in range(1, len(A)): if A[i] < A[i-1]: return False return True
https://leetcode.com/problems/monotonic-array/discuss/501946/Python-and-Java-Solution-beat-96-and-100
17
An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j]. Given an integer array nums, return true if the given array is monotonic, or false otherwise. Example 1: Input: nums = [1,2,2,3] Output: true Example 2: Input: nums = [6,5,4,4] Output: true Example 3: Input: nums = [1,3,2] Output: false Constraints: 1 <= nums.length <= 105 -105 <= nums[i] <= 105
Python and Java Solution beat 96% and 100%
1,800
monotonic-array
0.583
justin801514
Easy
14,494
896
increasing order search tree
class Solution: def increasingBST(self, root: TreeNode) -> TreeNode: prev_node = None def helper( node: TreeNode): if node.right: helper( node.right ) # prev_novde always points to next larger element for current node nonlocal prev_node # update right link points to next larger element node.right = prev_node # break the left link of next larger element if prev_node: prev_node.left = None # update previous node as current node prev_node = node if node.left: helper( node.left) # --------------------------------------- helper( root ) return prev_node
https://leetcode.com/problems/increasing-order-search-tree/discuss/526258/Python-O(n)-sol-by-DFS-90%2B-w-Diagram
4
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. Example 1: Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] Example 2: Input: root = [5,1,7] Output: [1,null,5,null,7] Constraints: The number of nodes in the given tree will be in the range [1, 100]. 0 <= Node.val <= 1000
Python O(n) sol by DFS 90%+ [w/ Diagram ]
690
increasing-order-search-tree
0.785
brianchiang_tw
Easy
14,537
897
bitwise ors of subarrays
class Solution: def subarrayBitwiseORs(self, arr: List[int]) -> int: ans=set(arr) # each element is a subarry one = set() # to get the ans for the subarray of size >1 # starting from 0th element to the ending element one.add(arr[0]) for i in range(1,len(arr)): two=set() for j in one: two.add(j | arr[i]) # subarray from the element in one set to the current ele(i th one) ans.add(j| arr[i]) two.add(arr[i]) # adding curr element to set two so that from next iteration we can take sub array starting from curr element one = two return len(ans)
https://leetcode.com/problems/bitwise-ors-of-subarrays/discuss/1240982/python-code-with-comment-might-help-to-understand-or
3
Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: arr = [0] Output: 1 Explanation: There is only one possible result: 0. Example 2: Input: arr = [1,1,2] Output: 3 Explanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2]. These yield the results 1, 1, 2, 1, 3, 3. There are 3 unique values, so the answer is 3. Example 3: Input: arr = [1,2,4] Output: 6 Explanation: The possible results are 1, 2, 3, 4, 6, and 7. Constraints: 1 <= arr.length <= 5 * 104 0 <= arr[i] <= 109
python code with comment , might help to understand |
423
bitwise-ors-of-subarrays
0.369
chikushen99
Medium
14,572
898
orderly queue
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k > 1: return "".join(sorted(s)) res = s for i in range(0,len(s)): s = s[1:] + s[0] res = min(res,s) return res
https://leetcode.com/problems/orderly-queue/discuss/2783233/Python-Simple-and-Easy-Way-to-Solve-with-Explanation-or-99-Faster
12
You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string. Return the lexicographically smallest string you could have after applying the mentioned step any number of moves. Example 1: Input: s = "cba", k = 1 Output: "acb" Explanation: In the first move, we move the 1st character 'c' to the end, obtaining the string "bac". In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb". Example 2: Input: s = "baaca", k = 3 Output: "aaabc" Explanation: In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc". Constraints: 1 <= k <= s.length <= 1000 s consist of lowercase English letters.
✔️ Python Simple and Easy Way to Solve with Explanation | 99% Faster 🔥
577
orderly-queue
0.665
pniraj657
Hard
14,574
899
numbers at most n given digit set
class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: digits = set(int(d) for d in digits) dLen = len(digits) nStr = str(n) nLen = len(nStr) res = sum(dLen**i for i in range(1, nLen)) # lower dimensions def helper(firstDigit, slots): if slots == 1: return sum(d <= firstDigit for d in digits) return sum(d < firstDigit for d in digits) * dLen**(slots - 1) for i in range(nLen): curDigit = int(nStr[i]) res += helper(curDigit, nLen - i) if not curDigit in digits: # makes no sense to continue break return res
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1633530/Python3-NOT-BEGINNER-FRIENDLY-Explained
8
Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n. Example 1: Input: digits = ["1","3","5","7"], n = 100 Output: 20 Explanation: The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. Example 2: Input: digits = ["1","4","9"], n = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. Example 3: Input: digits = ["7"], n = 8 Output: 1 Constraints: 1 <= digits.length <= 9 digits[i].length == 1 digits[i] is a digit from '1' to '9'. All the values in digits are unique. digits is sorted in non-decreasing order. 1 <= n <= 109
✔️ [Python3] NOT BEGINNER FRIENDLY, Explained
364
numbers-at-most-n-given-digit-set
0.414
artod
Hard
14,620
902
valid permutations for di sequence
class Solution: def numPermsDISequence(self, s: str) -> int: @cache def fn(i, x): """Return number of valid permutation given x numbers smaller than previous one.""" if i == len(s): return 1 if s[i] == "D": if x == 0: return 0 # cannot decrease return fn(i, x-1) + fn(i+1, x-1) else: if x == len(s)-i: return 0 # cannot increase return fn(i, x+1) + fn(i+1, x) return sum(fn(0, x) for x in range(len(s)+1)) % 1_000_000_007
https://leetcode.com/problems/valid-permutations-for-di-sequence/discuss/1261833/Python3-top-down-dp
1
You are given a string s of length n where s[i] is either: 'D' means decreasing, or 'I' means increasing. A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i: If s[i] == 'D', then perm[i] > perm[i + 1], and If s[i] == 'I', then perm[i] < perm[i + 1]. Return the number of valid permutations perm. Since the answer may be large, return it modulo 109 + 7. Example 1: Input: s = "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) Example 2: Input: s = "D" Output: 1 Constraints: n == s.length 1 <= n <= 200 s[i] is either 'I' or 'D'.
[Python3] top-down dp
350
valid-permutations-for-di-sequence
0.577
ye15
Hard
14,629
903
fruit into baskets
class Solution: def totalFruit(self, fruits: List[int]) -> int: fruit_types = Counter() distinct = 0 max_fruits = 0 left = right = 0 while right < len(fruits): # check if it is a new fruit, and update the counter if fruit_types[fruits[right]] == 0: distinct += 1 fruit_types[fruits[right]] += 1 # too many different fruits, so start shrinking window while distinct > 2: fruit_types[fruits[left]] -= 1 if fruit_types[fruits[left]] == 0: distinct -= 1 left += 1 # set max_fruits to the max window size max_fruits = max(max_fruits, right-left+1) right += 1 return max_fruits
https://leetcode.com/problems/fruit-into-baskets/discuss/1414545/Python-clean-%2B-easy-to-understand-or-Sliding-Window-O(N)
26
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold. Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array fruits, return the maximum number of fruits you can pick. Example 1: Input: fruits = [1,2,1] Output: 3 Explanation: We can pick from all 3 trees. Example 2: Input: fruits = [0,1,2,2] Output: 3 Explanation: We can pick from trees [1,2,2]. If we had started at the first tree, we would only pick from trees [0,1]. Example 3: Input: fruits = [1,2,3,2,2] Output: 4 Explanation: We can pick from trees [2,3,2,2]. If we had started at the first tree, we would only pick from trees [1,2]. Constraints: 1 <= fruits.length <= 105 0 <= fruits[i] < fruits.length
Python - clean + easy to understand | Sliding Window O(N)
1,900
fruit-into-baskets
0.426
afm2
Medium
14,632
904
sort array by parity
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: i, j = 0, len(A) - 1 while i < j: if A[i] % 2 == 1 and A[j] % 2 == 0: A[i], A[j] = A[j], A[i] i, j = i + 1 - A[i] % 2, j - A[j] % 2 return A
https://leetcode.com/problems/sort-array-by-parity/discuss/356271/Solution-in-Python-3-(beats-~96)-(short)-(-O(1)-space-)-(-O(n)-speed-)
21
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. Example 1: Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. Example 2: Input: nums = [0] Output: [0] Constraints: 1 <= nums.length <= 5000 0 <= nums[i] <= 5000
Solution in Python 3 (beats ~96%) (short) ( O(1) space ) ( O(n) speed )
2,300
sort-array-by-parity
0.757
junaidmansuri
Easy
14,657
905
super palindromes
class Solution: nums = [] for i in range(1, 10**5): odd = int(str(i)+str(i)[:-1][::-1])**2 even = int(str(i)+str(i)[::-1])**2 if str(odd) == str(odd)[::-1]: nums.append(odd) if str(even) == str(even)[::-1]: nums.append(even) nums = sorted(list(set(nums))) def superpalindromesInRange(self, left: str, right: str) -> int: output = [] for n in self.nums: if int(left) <= n <= int(right): output.append(n) return len(output)
https://leetcode.com/problems/super-palindromes/discuss/1198991/Runtime%3A-Faster-than-94.87-of-Python3-Memory-Usage-less-than-100
1
Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right]. Example 1: Input: left = "4", right = "1000" Output: 4 Explanation: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome. Example 2: Input: left = "1", right = "2" Output: 1 Constraints: 1 <= left.length, right.length <= 18 left and right consist of only digits. left and right cannot have leading zeros. left and right represent integers in the range [1, 1018 - 1]. left is less than or equal to right.
Runtime: Faster than 94.87% of Python3 Memory Usage less than 100%
102
super-palindromes
0.392
pranshusharma712
Hard
14,705
906
sum of subarray minimums
class Solution: def sumSubarrayMins(self, arr: List[int]) -> int: M = 10 ** 9 + 7 # right bound for current number as minimum q = [] n = len(arr) right = [n-1] * n for i in range(n): # must put the equal sign to one of the bound (left or right) for duplicate nums (e.g. [71, 55, 82, 55]) while q and arr[i] <= arr[q[-1]]: right[q.pop()] = i - 1 q.append(i) # left bound for current number as minimum q = [] left = [0] * n for i in reversed(range(n)): while q and arr[i] < arr[q[-1]]: left[q.pop()] = i + 1 q.append(i) # calculate sum for each number ans = 0 for i in range(n): l, r = abs(i - left[i]), abs(i - right[i]) # for example: xx1xxx # left take 0, 1, 2 numbers (3 combs) and right take 0, 1, 2, 3 numbers (4 combs) covered = (l + 1) * (r + 1) ans = (ans + arr[i] * covered) % M return ans
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2846444/Python-3Monotonic-stack-boundry
10
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7. Example 1: Input: arr = [3,1,2,4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. Example 2: Input: arr = [11,81,94,43,3] Output: 444 Constraints: 1 <= arr.length <= 3 * 104 1 <= arr[i] <= 3 * 104
[Python 3]Monotonic stack boundry
475
sum-of-subarray-minimums
0.346
chestnut890123
Medium
14,712
907
smallest range i
class Solution: def smallestRangeI(self, A: List[int], K: int) -> int: M, m = max(A), min(A) diff, extension = M - m, 2*K if diff <= extension: return 0 else: return diff - extension
https://leetcode.com/problems/smallest-range-i/discuss/535164/Python-O(n)-by-min-and-Max.-85%2B-w-Visualization
17
You are given an integer array nums and an integer k. In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after applying the mentioned operation at most once for each index in it. Example 1: Input: nums = [1], k = 0 Output: 0 Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. Example 2: Input: nums = [0,10], k = 2 Output: 6 Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. Example 3: Input: nums = [1,3,6], k = 3 Output: 0 Explanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0. Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 104 0 <= k <= 104
Python O(n) by min & Max. 85%+ [w/ Visualization ]
872
smallest-range-i
0.678
brianchiang_tw
Easy
14,741
908
snakes and ladders
class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: # creating a borad map to loop-up the square value board_map = {} i = 1 b_rev = board[::-1] for d, r in enumerate(b_rev): # reverse for even rows - here d is taken as direction if d%2 != 0: r = r[::-1] for s in r: board_map[i] = s i += 1 # BFS Algorithm q = [(1, 0)] # (curr, moves) v = set() goal = len(board) * len(board) # end square while q: curr, moves = q.pop(0) # win situation if curr == goal: return moves # BFS on next 6 places (rolling a die) for i in range(1, 7): # skip square outside board if curr+i > goal: continue # get value from mapping next_pos = curr+i if board_map[curr+i] == -1 else board_map[curr+i] if next_pos not in v: v.add(next_pos) q.append((next_pos, moves+1)) return -1
https://leetcode.com/problems/snakes-and-ladders/discuss/2491448/Python-3-oror-BFS-Solution-Using-board-mapping
1
You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row. You start on square 1 of the board. In each move, starting from square curr, do the following: Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)]. This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board. If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next. The game ends when you reach the square n2. A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4. Return the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1. Example 1: Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] Output: 4 Explanation: In the beginning, you start at square 1 (at row 5, column 0). You decide to move to square 2 and must take the ladder to square 15. You then decide to move to square 17 and must take the snake to square 13. You then decide to move to square 14 and must take the ladder to square 35. You then decide to move to square 36, ending the game. This is the lowest possible number of moves to reach the last square, so return 4. Example 2: Input: board = [[-1,-1],[-1,3]] Output: 1 Constraints: n == board.length == board[i].length 2 <= n <= 20 board[i][j] is either -1 or in the range [1, n2]. The squares labeled 1 and n2 do not have any ladders or snakes.
Python 3 || BFS Solution - Using board mapping
161
snakes-and-ladders
0.409
kevintoms
Medium
14,756
909
smallest range ii
class Solution: def smallestRangeII(self, A: List[int], K: int) -> int: A.sort() res = A[-1] - A[0] for indx in range(0, len(A) - 1): # assuming that A[indx] is the max val min_val = min(A[0] + K, A[indx + 1] - K) max_val = max(A[indx] + K, A[-1] - K) res = min(res, max_val - min_val) return res
https://leetcode.com/problems/smallest-range-ii/discuss/980784/Python-3-Solution-Explained-(video-%2B-code)
3
You are given an integer array nums and an integer k. For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after changing the values at each index. Example 1: Input: nums = [1], k = 0 Output: 0 Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. Example 2: Input: nums = [0,10], k = 2 Output: 6 Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. Example 3: Input: nums = [1,3,6], k = 3 Output: 3 Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3. Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 104 0 <= k <= 104
[Python 3] Solution Explained (video + code)
361
smallest-range-ii
0.346
spec_he123
Medium
14,760
910
sort an array
class Solution: def sortArray(self, N: List[int]) -> List[int]: L = len(N) return [N.pop(min(range(L-i), key = lambda x: N[x])) for i in range(L)]
https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation)
125
Given an array of integers nums, sort the array in ascending order and return it. You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible. Example 1: Input: nums = [5,2,3,1] Output: [1,2,3,5] Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). Example 2: Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5] Explanation: Note that the values of nums are not necessairly unique. Constraints: 1 <= nums.length <= 5 * 104 -5 * 104 <= nums[i] <= 5 * 104
Python 3 (Eight Sorting Algorithms) (With Explanation)
9,200
sort-an-array
0.594
junaidmansuri
Medium
14,763
912
cat and mouse
class Solution: def catMouseGame(self, graph: List[List[int]]) -> int: n = len(graph) @cache def fn(i, m, c): """Return """ if i == 2*n: return 0 # tie if m == 0: return 1 # mouse wins if m == c: return 2 # cat wins if i&amp;1: # cat's turn tie = 0 for cc in graph[c]: if cc != 0: x = fn(i+1, m, cc) if x == 2: return 2 if x == 0: tie = 1 if tie: return 0 return 1 else: # mouse's turn tie = 0 for mm in graph[m]: x = fn(i+1, mm, c) if x == 1: return 1 if x == 0: tie = 1 if tie: return 0 return 2 return fn(0, 1, 2)
https://leetcode.com/problems/cat-and-mouse/discuss/1563154/Python3-dp-minimax
0
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0. During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1]. Additionally, it is not allowed for the Cat to travel to the Hole (node 0). Then, the game can end in three ways: If ever the Cat occupies the same node as the Mouse, the Cat wins. If ever the Mouse reaches the Hole, the Mouse wins. If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a graph, and assuming both players play optimally, return 1 if the mouse wins the game, 2 if the cat wins the game, or 0 if the game is a draw. Example 1: Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]] Output: 0 Example 2: Input: graph = [[1,3],[0],[3],[0,2]] Output: 1 Constraints: 3 <= graph.length <= 50 1 <= graph[i].length < graph.length 0 <= graph[i][j] < graph.length graph[i][j] != i graph[i] is unique. The mouse and the cat can always move.
[Python3] dp - minimax
212
cat-and-mouse
0.351
ye15
Hard
14,803
913
x of a kind in a deck of cards
class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool: x = Counter(deck).values() return reduce(gcd, x) > 1
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/2821961/Did-you-known-about-'gcd'-function-%3AD
0
You are given an integer array deck where deck[i] represents the number written on the ith card. Partition the cards into one or more groups such that: Each group has exactly x cards where x > 1, and All the cards in one group have the same integer written on them. Return true if such partition is possible, or false otherwise. Example 1: Input: deck = [1,2,3,4,4,3,2,1] Output: true Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]. Example 2: Input: deck = [1,1,1,2,2,2,3,3] Output: false Explanation: No possible partition. Constraints: 1 <= deck.length <= 104 0 <= deck[i] < 104
Did you known about 'gcd' function? :D
3
x-of-a-kind-in-a-deck-of-cards
0.32
almazgimaev
Easy
14,804
914
partition array into disjoint intervals
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: """ Intuition(logic) is to find two maximums. One maximum is for left array and other maximum is for right array. But the condition is that, the right maximum should be such that, no element after that right maximum should be less than the left maximum. If there is any element after right maximum which is less than left maximum, that means there is another right maximum possible and therefore in that case assign left maximum to right maximum and keep searching the array for correct right maximum till the end. """ #start with both left maximum and right maximum with first element. left_max = right_max = nums[0] # our current index partition_ind = 0 # Iterate from 1 to end of the array for i in range(1,len(nums)): #update right_max always after comparing with each nums #in order to find our correct right maximum right_max = max(nums[i], right_max) """ if current element is less than left maximum, that means this element must belong to the left subarray. * so our partition index will be updated to current index * and left maximum will be updated to right maximum. Why left maximum updated to right maximum ? Because when we find any element less than left_maximum, that means the right maximum which we had till now is not valid and we have to find the valid right maximum again while iterating through the end of the loop. """ if nums[i] < left_max: left_max = right_max partition_ind = i return partition_ind+1
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1359686/PYTHON-Best-solution-yet!-EXPLAINED-with-comments-to-make-life-easier.-O(n)-and-O(1)
7
Given an integer array nums, partition it into two (contiguous) subarrays left and right so that: Every element in left is less than or equal to every element in right. left and right are non-empty. left has the smallest possible size. Return the length of left after such a partitioning. Test cases are generated such that partitioning exists. Example 1: Input: nums = [5,0,3,8,6] Output: 3 Explanation: left = [5,0,3], right = [8,6] Example 2: Input: nums = [1,1,1,0,6,12] Output: 4 Explanation: left = [1,1,1,0], right = [6,12] Constraints: 2 <= nums.length <= 105 0 <= nums[i] <= 106 There is at least one valid answer for the given input.
[PYTHON] Best solution yet! EXPLAINED with comments to make life easier. O(n) & O(1)
352
partition-array-into-disjoint-intervals
0.486
er1shivam
Medium
14,812
915
word subsets
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: result = [] tempDict = Counter() for w in words2: tempDict |= Counter(w) print(tempDict) for w in words1: if not tempDict - Counter(w): result.append(w) return result
https://leetcode.com/problems/word-subsets/discuss/2353565/Solution-Using-Counter-in-Python
26
You are given two string arrays words1 and words2. A string b is a subset of string a if every letter in b occurs in a including multiplicity. For example, "wrr" is a subset of "warrior" but is not a subset of "world". A string a from words1 is universal if for every string b in words2, b is a subset of a. Return an array of all the universal strings in words1. You may return the answer in any order. Example 1: Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"] Output: ["facebook","google","leetcode"] Example 2: Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"] Output: ["apple","google","leetcode"] Constraints: 1 <= words1.length, words2.length <= 104 1 <= words1[i].length, words2[i].length <= 10 words1[i] and words2[i] consist only of lowercase English letters. All the strings of words1 are unique.
Solution Using Counter in Python
1,200
word-subsets
0.54
AY_
Medium
14,831
916
reverse only letters
class Solution: def reverseOnlyLetters(self, S: str) -> str: S = list(S) c = [c for c in S if c.isalpha()] for i in range(-1,-len(S)-1,-1): if S[i].isalpha(): S[i] = c.pop(0) return "".join(S) - Python 3 - Junaid Mansuri
https://leetcode.com/problems/reverse-only-letters/discuss/337853/Solution-in-Python-3
9
Given a string s, reverse the string according to the following rules: All the characters that are not English letters remain in the same position. All the English letters (lowercase or uppercase) should be reversed. Return s after reversing it. Example 1: Input: s = "ab-cd" Output: "dc-ba" Example 2: Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Example 3: Input: s = "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!" Constraints: 1 <= s.length <= 100 s consists of characters with ASCII values in the range [33, 122]. s does not contain '\"' or '\\'.
Solution in Python 3
1,100
reverse-only-letters
0.615
junaidmansuri
Easy
14,860
917