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
count array pairs divisible by k
class Solution: def coutPairs(self, nums: List[int], k: int) -> int: factors = [] for x in range(1, int(sqrt(k))+1): if k % x == 0: factors.append(x) ans = 0 freq = Counter() for x in nums: x = gcd(x, k) ans += freq[k//x] for f in factors: if x % f == 0 and f <= x//f: freq[f] += 1 if f < x//f: freq[x//f] += 1 return ans
https://leetcode.com/problems/count-array-pairs-divisible-by-k/discuss/1784801/Python3-factors
6
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that: 0 <= i < j <= n - 1 and nums[i] * nums[j] is divisible by k. Example 1: Input: nums = [1,2,3,4,5], k = 2 Output: 7 Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are (0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4). Their products are 2, 4, 6, 8, 10, 12, and 20 respectively. Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 5 Output: 0 Explanation: There does not exist any pair of indices whose corresponding product is divisible by 5. Constraints: 1 <= nums.length <= 105 1 <= nums[i], k <= 105
[Python3] factors
661
count-array-pairs-divisible-by-k
0.287
ye15
Hard
30,301
2,183
counting words with a given prefix
class Solution: def prefixCount(self, words: List[str], pref: str) -> int: return sum(word.find(pref) == 0 for word in words)
https://leetcode.com/problems/counting-words-with-a-given-prefix/discuss/1803163/Python-1-Liner-Solution
3
You are given an array of strings words and a string pref. Return the number of strings in words that contain pref as a prefix. A prefix of a string s is any leading contiguous substring of s. Example 1: Input: words = ["pay","attention","practice","attend"], pref = "at" Output: 2 Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend". Example 2: Input: words = ["leetcode","win","loops","success"], pref = "code" Output: 0 Explanation: There are no strings that contain "code" as a prefix. Constraints: 1 <= words.length <= 100 1 <= words[i].length, pref.length <= 100 words[i] and pref consist of lowercase English letters.
Python 1 Liner Solution
210
counting-words-with-a-given-prefix
0.771
anCoderr
Easy
30,305
2,185
minimum number of steps to make two strings anagram ii
class Solution: def minSteps(self, s: str, t: str) -> int: fs, ft = Counter(s), Counter(t) return sum((fs-ft).values()) + sum((ft-fs).values())
https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/discuss/1802652/Python3-freq-table
6
You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering. Example 1: Input: s = "leetcode", t = "coats" Output: 7 Explanation: - In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas". - In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coatsleede". "leetcodeas" and "coatsleede" are now anagrams of each other. We used a total of 2 + 5 = 7 steps. It can be shown that there is no way to make them anagrams of each other with less than 7 steps. Example 2: Input: s = "night", t = "thing" Output: 0 Explanation: The given strings are already anagrams of each other. Thus, we do not need any further steps. Constraints: 1 <= s.length, t.length <= 2 * 105 s and t consist of lowercase English letters.
[Python3] freq table
307
minimum-number-of-steps-to-make-two-strings-anagram-ii
0.719
ye15
Medium
30,354
2,186
minimum time to complete trips
class Solution: def minimumTime(self, time: List[int], totalTrips: int) -> int: r = min(time) * totalTrips + 1 # This is the worst case answer possible for any case. Could use big values like 10^15 as well but they might slow the time down for smaller cases. l = 0 ans = 0 def check_status(expected_time: int) -> int: nonlocal ans count = 0 for i in time: count += expected_time // i # Total trips with time expected_time should be integer part of expected_time // i if count < totalTrips: return 1 # Since number of trips are less then required, left moves to mid elif count >= totalTrips: ans = expected_time # stores the latest result. This is guaranteed to be the minimum possible answer. return -1 # Since number of trips are greater/equal to required, right moves to mid while l < r-1: # Till Binary Search can continue. mid = (l + r) // 2 # mid is the current expected time. status = check_status(mid) # The return values 1/-1 in check_status function determines which pointer to move. if status == 1: l = mid else: r = mid return ans
https://leetcode.com/problems/minimum-time-to-complete-trips/discuss/1802433/Python-Solution-oror-Detailed-Article-on-Binary-Search-on-Answer
12
You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip. Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips. Example 1: Input: time = [1,2,3], totalTrips = 5 Output: 3 Explanation: - At time t = 1, the number of trips completed by each bus are [1,0,0]. The total number of trips completed is 1 + 0 + 0 = 1. - At time t = 2, the number of trips completed by each bus are [2,1,0]. The total number of trips completed is 2 + 1 + 0 = 3. - At time t = 3, the number of trips completed by each bus are [3,1,1]. The total number of trips completed is 3 + 1 + 1 = 5. So the minimum time needed for all buses to complete at least 5 trips is 3. Example 2: Input: time = [2], totalTrips = 1 Output: 2 Explanation: There is only one bus, and it will complete its first trip at t = 2. So the minimum time needed to complete 1 trip is 2. Constraints: 1 <= time.length <= 105 1 <= time[i], totalTrips <= 107
✅ Python Solution || Detailed Article on Binary Search on Answer
694
minimum-time-to-complete-trips
0.32
anCoderr
Medium
30,378
2,187
minimum time to finish the race
class Solution: def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int: tires.sort() newTires = [] minTime = [changeTime*(i-1) + tires[0][0]*i for i in range(numLaps+1)] minTime[0] = 0 maxi = 0 for f,r in tires: if not newTires or f>newTires[-1][0] and r<newTires[-1][1]: newTires.append([f,r]) t = f i = 1 while i<numLaps and t*(r-1)<changeTime: t = t*r + f i += 1 if minTime[i]>t: minTime[i]=t maxi = max(i,maxi) for lap in range(numLaps+1): for run in range(min(lap,maxi+1)): minTime[lap] = min(minTime[lap],minTime[lap-run]+changeTime+minTime[run]) return minTime[numLaps]
https://leetcode.com/problems/minimum-time-to-finish-the-race/discuss/1803014/Python-DP-with-pre-treatment-to-reduce-time-complexity
3
You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds. For example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds, its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, etc. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race. Example 1: Input: tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4 Output: 21 Explanation: Lap 1: Start with tire 0 and finish the lap in 2 seconds. Lap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds. Lap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds. Lap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds. Total time = 2 + 6 + 5 + 2 + 6 = 21 seconds. The minimum time to complete the race is 21 seconds. Example 2: Input: tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5 Output: 25 Explanation: Lap 1: Start with tire 1 and finish the lap in 2 seconds. Lap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds. Lap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds. Lap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds. Lap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second. Total time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds. The minimum time to complete the race is 25 seconds. Constraints: 1 <= tires.length <= 105 tires[i].length == 2 1 <= fi, changeTime <= 105 2 <= ri <= 105 1 <= numLaps <= 1000
[Python] DP with pre-treatment to reduce time complexity
226
minimum-time-to-finish-the-race
0.419
wssx349
Hard
30,404
2,188
most frequent number following key in an array
class Solution: def mostFrequent(self, nums, key): counts = {} for i in range(1,len(nums)): if nums[i-1]==key: if nums[i] not in counts: counts[nums[i]] = 1 else: counts[nums[i]] += 1 return max(counts, key=counts.get)
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1924231/Python-Multiple-Solutions-%2B-One-Liners-or-Clean-and-Simple
4
You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: 0 <= i <= nums.length - 2, nums[i] == key and, nums[i + 1] == target. Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique. Example 1: Input: nums = [1,100,200,1,100], key = 1 Output: 100 Explanation: For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key. No other integers follow an occurrence of key, so we return 100. Example 2: Input: nums = [2,2,2,2,3], key = 2 Output: 2 Explanation: For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key. For target = 3, there is only one occurrence at index 4 which follows an occurrence of key. target = 2 has the maximum number of occurrences following an occurrence of key, so we return 2. Constraints: 2 <= nums.length <= 1000 1 <= nums[i] <= 1000 The test cases will be generated such that the answer is unique.
Python - Multiple Solutions + One-Liners | Clean and Simple
214
most-frequent-number-following-key-in-an-array
0.605
domthedeveloper
Easy
30,408
2,190
sort the jumbled numbers
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: @cache def convert(i: int): res, pow10 = 0, 1 while i: res += pow10 * mapping[i % 10] i //= 10 pow10 *= 10 return res return sorted(nums, key=lambda i: mapping[i] if i < 10 else convert(i))
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1822244/Sorted-Lambda
8
You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system. The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for all 0 <= i <= 9. You are also given another integer array nums. Return the array nums sorted in non-decreasing order based on the mapped values of its elements. Notes: Elements with the same mapped values should appear in the same relative order as in the input. The elements of nums should only be sorted based on their mapped values and not be replaced by them. Example 1: Input: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38] Output: [338,38,991] Explanation: Map the number 991 as follows: 1. mapping[9] = 6, so all occurrences of the digit 9 will become 6. 2. mapping[1] = 9, so all occurrences of the digit 1 will become 9. Therefore, the mapped value of 991 is 669. 338 maps to 007, or 7 after removing the leading zeros. 38 maps to 07, which is also 7 after removing leading zeros. Since 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38. Thus, the sorted array is [338,38,991]. Example 2: Input: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123] Output: [123,456,789] Explanation: 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789]. Constraints: mapping.length == 10 0 <= mapping[i] <= 9 All the values of mapping[i] are unique. 1 <= nums.length <= 3 * 104 0 <= nums[i] < 109
Sorted Lambda
869
sort-the-jumbled-numbers
0.453
votrubac
Medium
30,436
2,191
all ancestors of a node in a directed acyclic graph
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: #Use Kahn's algorithm of toposort using a queue and bfs! graph = [[] for _ in range(n)] indegrees = [0] * n #Time: O(n^2) #Space: O(n^2 + n + n) -> O(n^2) #1st step: build adjacency list grpah and update the initial indegrees of every node! for edge in edges: src, dest = edge[0], edge[1] graph[src].append(dest) indegrees[dest] += 1 queue = deque() ans = [set() for _ in range(n)] #2nd step: go through the indegrees array and add to queue for any node that has no ancestor! for i in range(len(indegrees)): if(indegrees[i] == 0): queue.append(i) #Kahn's algorithm initiation! #while loop will run for each and every node in graph! #in worst case, adjacency list for one particular node may contain all other vertices! while queue: cur = queue.pop() #for each neighbor for neighbor in graph[cur]: #current node is ancestor to each and every neighboring node! ans[neighbor].add(cur) #every ancestor of current node is also an ancestor to the neighboring node! ans[neighbor].update(ans[cur]) indegrees[neighbor] -= 1 if(indegrees[neighbor] == 0): queue.append(neighbor) #at the end, we should have set of ancestors for each and every node! #in worst case, set s for ith node could have all other vertices be ancestor to node i ! ans = [(sorted(list(s))) for s in ans] return ans
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/2333862/Python3-or-Solved-using-Topo-Sort(Kahn-Algo)-with-Queue(BFS)
4
You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph. Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order. A node u is an ancestor of another node v if u can reach v via a set of edges. Example 1: Input: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]] Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]] Explanation: The above diagram represents the input graph. - Nodes 0, 1, and 2 do not have any ancestors. - Node 3 has two ancestors 0 and 1. - Node 4 has two ancestors 0 and 2. - Node 5 has three ancestors 0, 1, and 3. - Node 6 has five ancestors 0, 1, 2, 3, and 4. - Node 7 has four ancestors 0, 1, 2, and 3. Example 2: Input: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]] Explanation: The above diagram represents the input graph. - Node 0 does not have any ancestor. - Node 1 has one ancestor 0. - Node 2 has two ancestors 0 and 1. - Node 3 has three ancestors 0, 1, and 2. - Node 4 has four ancestors 0, 1, 2, and 3. Constraints: 1 <= n <= 1000 0 <= edges.length <= min(2000, n * (n - 1) / 2) edges[i].length == 2 0 <= fromi, toi <= n - 1 fromi != toi There are no duplicate edges. The graph is directed and acyclic.
Python3 | Solved using Topo Sort(Kahn Algo) with Queue(BFS)
169
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0.503
JOON1234
Medium
30,448
2,192
minimum number of moves to make palindrome
class Solution: def minMovesToMakePalindrome(self, s: str) -> int: ans = 0 while len(s) > 2: lo = s.find(s[-1]) hi = s.rfind(s[0]) if lo < len(s)-hi-1: ans += lo s = s[:lo] + s[lo+1:-1] else: ans += len(s)-hi-1 s = s[1:hi] + s[hi+1:] return ans
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/2152484/Python3-peel-the-string
1
You are given a string s consisting only of lowercase English letters. In one move, you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome. Note that the input will be generated such that s can always be converted to a palindrome. Example 1: Input: s = "aabb" Output: 2 Explanation: We can obtain two palindromes from s, "abba" and "baab". - We can obtain "abba" from s in 2 moves: "aabb" -> "abab" -> "abba". - We can obtain "baab" from s in 2 moves: "aabb" -> "abab" -> "baab". Thus, the minimum number of moves needed to make s a palindrome is 2. Example 2: Input: s = "letelt" Output: 2 Explanation: One of the palindromes we can obtain from s in 2 moves is "lettel". One of the ways we can obtain it is "letelt" -> "letetl" -> "lettel". Other palindromes such as "tleelt" can also be obtained in 2 moves. It can be shown that it is not possible to obtain a palindrome in less than 2 moves. Constraints: 1 <= s.length <= 2000 s consists only of lowercase English letters. s can be converted to a palindrome using a finite number of moves.
[Python3] peel the string
614
minimum-number-of-moves-to-make-palindrome
0.514
ye15
Hard
30,460
2,193
cells in a range on an excel sheet
class Solution: def cellsInRange(self, s: str) -> List[str]: return [chr(c)+str(r) for c in range(ord(s[0]), ord(s[3])+1) for r in range(int(s[1]), int(s[4])+1)]
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1823607/Python3-1-line
7
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: <col> denotes the column number c of the cell. It is represented by alphabetical letters. For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on. <row> is the row number r of the cell. The rth row is represented by the integer r. You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows. Example 1: Input: s = "K1:L2" Output: ["K1","K2","L1","L2"] Explanation: The above diagram shows the cells which should be present in the list. The red arrows denote the order in which the cells should be presented. Example 2: Input: s = "A1:F1" Output: ["A1","B1","C1","D1","E1","F1"] Explanation: The above diagram shows the cells which should be present in the list. The red arrow denotes the order in which the cells should be presented. Constraints: s.length == 5 'A' <= s[0] <= s[3] <= 'Z' '1' <= s[1] <= s[4] <= '9' s consists of uppercase English letters, digits and ':'.
[Python3] 1-line
368
cells-in-a-range-on-an-excel-sheet
0.856
ye15
Easy
30,466
2,194
append k integers with minimal sum
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: ans = k*(k+1)//2 prev = -inf for x in sorted(nums): if prev < x: if x <= k: k += 1 ans += k - x else: break prev = x return ans
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1823628/Python3-swap
10
You are given an integer array nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum. Return the sum of the k integers appended to nums. Example 1: Input: nums = [1,4,25,10,25], k = 2 Output: 5 Explanation: The two unique positive integers that do not appear in nums which we append are 2 and 3. The resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum. The sum of the two integers appended is 2 + 3 = 5, so we return 5. Example 2: Input: nums = [5,6], k = 6 Output: 25 Explanation: The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8. The resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. The sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 1 <= k <= 108
[Python3] swap
495
append-k-integers-with-minimal-sum
0.25
ye15
Medium
30,497
2,195
create binary tree from descriptions
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: mp = {} seen = set() for p, c, left in descriptions: if p not in mp: mp[p] = TreeNode(p) if c not in mp: mp[c] = TreeNode(c) if left: mp[p].left = mp[c] else: mp[p].right = mp[c] seen.add(c) for p, _, _ in descriptions: if p not in seen: return mp[p]
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1823644/Python3-simulation
8
You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, If isLefti == 1, then childi is the left child of parenti. If isLefti == 0, then childi is the right child of parenti. Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. Example 1: Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]] Output: [50,20,80,15,17,19] Explanation: The root node is the node with value 50 since it has no parent. The resulting binary tree is shown in the diagram. Example 2: Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]] Output: [1,2,null,null,3,4] Explanation: The root node is the node with value 1 since it has no parent. The resulting binary tree is shown in the diagram. Constraints: 1 <= descriptions.length <= 104 descriptions[i].length == 3 1 <= parenti, childi <= 105 0 <= isLefti <= 1 The binary tree described by descriptions is valid.
[Python3] simulation
191
create-binary-tree-from-descriptions
0.722
ye15
Medium
30,515
2,196
replace non coprime numbers in array
class Solution: def replaceNonCoprimes(self, nums: List[int]) -> List[int]: stack = nums[:1] for j in range(1, len(nums)): cur = nums[j] while stack and math.gcd(stack[-1], cur) > 1: prev = stack.pop() cur = math.lcm(prev, cur) stack.append(cur) return stack
https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/1825538/Python-3-Stack-solution
2
You are given an array of integers nums. Perform the following steps: Find any two adjacent numbers in nums that are non-coprime. If no such numbers are found, stop the process. Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple). Repeat this process as long as you keep finding two adjacent non-coprime numbers. Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. Example 1: Input: nums = [6,4,3,2,7,6,2] Output: [12,7,6] Explanation: - (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2]. - (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2]. - (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2]. - (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [12,7,6]. Note that there are other ways to obtain the same resultant array. Example 2: Input: nums = [2,2,1,1,3,3,3] Output: [2,1,1,3] Explanation: - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3]. - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3]. - (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [2,1,1,3]. Note that there are other ways to obtain the same resultant array. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105 The test cases are generated such that the values in the final array are less than or equal to 108.
[Python 3] Stack solution
125
replace-non-coprime-numbers-in-array
0.387
chestnut890123
Hard
30,531
2,197
find all k distant indices in an array
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: ind_j = [] for ind, elem in enumerate(nums): if elem == key: ind_j.append(ind) res = [] for i in range(len(nums)): for j in ind_j: if abs(i - j) <= k: res.append(i) break return sorted(res)
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/2171271/Python-easy-to-understand-oror-Beginner-friendly
4
You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. Example 1: Input: nums = [3,4,9,1,3,9,5], key = 9, k = 1 Output: [1,2,3,4,5,6] Explanation: Here, nums[2] == key and nums[5] == key. - For index 0, |0 - 2| > k and |0 - 5| > k, so there is no j where |0 - j| <= k and nums[j] == key. Thus, 0 is not a k-distant index. - For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index. - For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index. - For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index. - For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index. - For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index. - For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index. Thus, we return [1,2,3,4,5,6] which is sorted in increasing order. Example 2: Input: nums = [2,2,2,2,2], key = 2, k = 2 Output: [0,1,2,3,4] Explanation: For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index. Hence, we return [0,1,2,3,4]. Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 1000 key is an integer from the array nums. 1 <= k <= nums.length
✅Python easy to understand || Beginner friendly
147
find-all-k-distant-indices-in-an-array
0.646
Shivam_Raj_Sharma
Easy
30,538
2,200
count artifacts that can be extracted
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: # Time: O(max(artifacts, dig)) which is O(N^2) as every position in the grid can be in dig # Space: O(dig) which is O(N^2) result, dig_pos = 0, set(tuple(pos) for pos in dig) for pos in artifacts: if all((x, y) in dig_pos for x in range(pos[0], pos[2] + 1) for y in range(pos[1], pos[3] + 1)): result += 1 return result
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1844361/Python-elegant-short-and-simple-to-understand-with-explanations
6
There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular artifacts where artifacts[i] = [r1i, c1i, r2i, c2i] denotes that the ith artifact is buried in the subgrid where: (r1i, c1i) is the coordinate of the top-left cell of the ith artifact and (r2i, c2i) is the coordinate of the bottom-right cell of the ith artifact. You will excavate some cells of the grid and remove all the mud from them. If the cell has a part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact are uncovered, you can extract it. Given a 0-indexed 2D integer array dig where dig[i] = [ri, ci] indicates that you will excavate the cell (ri, ci), return the number of artifacts that you can extract. The test cases are generated such that: No two artifacts overlap. Each artifact only covers at most 4 cells. The entries of dig are unique. Example 1: Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1]] Output: 1 Explanation: The different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid. There is 1 artifact that can be extracted, namely the red artifact. The blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it. Thus, we return 1. Example 2: Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1],[1,1]] Output: 2 Explanation: Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2. Constraints: 1 <= n <= 1000 1 <= artifacts.length, dig.length <= min(n2, 105) artifacts[i].length == 4 dig[i].length == 2 0 <= r1i, c1i, r2i, c2i, ri, ci <= n - 1 r1i <= r2i c1i <= c2i No two artifacts will overlap. The number of cells covered by an artifact is at most 4. The entries of dig are unique.
💯 Python elegant, short and simple to understand with explanations
352
count-artifacts-that-can-be-extracted
0.551
yangshun
Medium
30,559
2,201
maximize the topmost element after k moves
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: if len(nums) == 1: if k%2 != 0: return -1 return nums[0] if k == 0: return nums[0] if k == len(nums): return max(nums[:-1]) if k > len(nums): return max(nums) if k == 1: return nums[1] m = max(nums[:k-1]) m = max(m, nums[k]) return m
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1844186/Python-3-Find-Maximum-of-first-k-1-elements-or-(k%2B1)th-element-or-Beats-100
9
You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0] is the topmost element of the pile. In one move, you can perform either of the following: If the pile is not empty, remove the topmost element of the pile. If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element. You are also given an integer k, which denotes the total number of moves to be made. Return the maximum value of the topmost element of the pile possible after exactly k moves. In case it is not possible to obtain a non-empty pile after k moves, return -1. Example 1: Input: nums = [5,2,2,4,0,6], k = 4 Output: 5 Explanation: One of the ways we can end with 5 at the top of the pile after 4 moves is as follows: - Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6]. - Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6]. - Step 3: Remove the topmost element = 2. The pile becomes [4,0,6]. - Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6]. Note that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves. Example 2: Input: nums = [2], k = 1 Output: -1 Explanation: In the first move, our only option is to pop the topmost element of the pile. Since it is not possible to obtain a non-empty pile after one move, we return -1. Constraints: 1 <= nums.length <= 105 0 <= nums[i], k <= 109
[Python 3] Find Maximum of first k-1 elements or (k+1)th element | Beats 100%
369
maximize-the-topmost-element-after-k-moves
0.228
hari19041
Medium
30,568
2,202
minimum weighted subgraph with the required paths
class Solution: def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int: forward, backward = dict(), dict() for start, end, weight in edges: if start in forward: if end in forward[start]: forward[start][end] = min(weight, forward[start][end]) else: forward[start][end] = weight else: forward[start] = {end: weight} if end in backward: if start in backward[end]: backward[end][start] = min(weight, backward[end][start]) else: backward[end][start] = weight else: backward[end] = {start: weight} def travel(origin: int, relations: dict, costs: list) -> None: level = {origin} costs[origin] = 0 while level: new_level = set() for node in level: if node in relations: for next_node, w in relations[node].items(): if w + costs[node] < costs[next_node]: new_level.add(next_node) costs[next_node] = w + costs[node] level = new_level from_src1 = [inf] * n from_src2 = [inf] * n from_dest = [inf] * n travel(src1, forward, from_src1) travel(src2, forward, from_src2) travel(dest, backward, from_dest) combined_cost = min(sum(tpl) for tpl in zip(from_src1, from_src2, from_dest)) return combined_cost if combined_cost < inf else -1
https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/discuss/1867689/Three-min-costs-to-every-node-97-speed
1
You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. Example 1: Input: n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5 Output: 9 Explanation: The above figure represents the input graph. The blue edges represent one of the subgraphs that yield the optimal answer. Note that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints. Example 2: Input: n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2 Output: -1 Explanation: The above figure represents the input graph. It can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints. Constraints: 3 <= n <= 105 0 <= edges.length <= 105 edges[i].length == 3 0 <= fromi, toi, src1, src2, dest <= n - 1 fromi != toi src1, src2, and dest are pairwise distinct. 1 <= weight[i] <= 105
Three min costs to every node, 97% speed
144
minimum-weighted-subgraph-with-the-required-paths
0.357
EvgenySH
Hard
30,577
2,203
divide array into equal pairs
class Solution: def divideArray(self, nums: List[int]) -> bool: lena = len(nums) count = sum(num//2 for num in Counter(nums).values()) return (lena/2 == count)
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1864079/Python-Solution-Using-Counter-oror-Beats-99-oror-O(n)
6
You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Each element belongs to exactly one pair. The elements present in a pair are equal. Return true if nums can be divided into n pairs, otherwise return false. Example 1: Input: nums = [3,2,3,2,2,2] Output: true Explanation: There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs. If nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions. Example 2: Input: nums = [1,2,3,4] Output: false Explanation: There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition. Constraints: nums.length == 2 * n 1 <= n <= 500 1 <= nums[i] <= 500
Python Solution Using Counter || Beats 99% || O(n)
698
divide-array-into-equal-pairs
0.746
IvanTsukei
Easy
30,581
2,206
maximize number of subsequences in a string
class Solution: def maximumSubsequenceCount(self, string: str, pattern: str) -> int: text = pattern[0]+string text1 = string + pattern[1] cnt,cnt1 = 0,0 ans,ans1 = 0,0 for i in range(len(text)): if text[i] == pattern[0]: cnt+=1 elif text[i] == pattern[1]: ans+= cnt if pattern[0] == pattern[1]: ans = ((cnt)*(cnt-1))//2 # appending at the last for i in range(len(text1)): if text1[i] == pattern[0]: cnt1+=1 elif text1[i] == pattern[1]: ans1+= cnt1 if pattern[0] == pattern[1]: ans1 = ((cnt1)*(cnt1-1))//2 return max(ans1,ans)
https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/2501496/Python-Easy-Solution
0
You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Example 1: Input: text = "abdcdbc", pattern = "ac" Output: 4 Explanation: If we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4. Some other strings which have 4 subsequences "ac" after adding a character to text are "aabdcdbc" and "abdacdbc". However, strings such as "abdcadbc", "abdccdbc", and "abdcdbcc", although obtainable, have only 3 subsequences "ac" and are thus suboptimal. It can be shown that it is not possible to get more than 4 subsequences "ac" by adding only one character. Example 2: Input: text = "aabb", pattern = "ab" Output: 6 Explanation: Some of the strings which can be obtained from text and have 6 subsequences "ab" are "aaabb", "aaabb", and "aabbb". Constraints: 1 <= text.length <= 105 pattern.length == 2 text and pattern consist only of lowercase English letters.
Python Easy Solution
26
maximize-number-of-subsequences-in-a-string
0.328
Abhi_009
Medium
30,624
2,207
minimum operations to halve array sum
class Solution: def halveArray(self, nums: List[int]) -> int: s = sum(nums) goal = s / 2 res = 0 for i, num in enumerate(nums): nums[i] = -num heapq.heapify(nums) while s > goal: halfLargest = -heapq.heappop(nums) / 2 s -= halfLargest heapq.heappush(nums, -halfLargest) res += 1 return res
https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/1984994/python-3-oror-priority-queue
2
You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. Example 1: Input: nums = [5,19,8,1] Output: 3 Explanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33. The following is one of the ways to reduce the sum by at least half: Pick the number 19 and reduce it to 9.5. Pick the number 9.5 and reduce it to 4.75. Pick the number 8 and reduce it to 4. The final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. The sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5. Overall, 3 operations were used so we return 3. It can be shown that we cannot reduce the sum by at least half in less than 3 operations. Example 2: Input: nums = [3,8,20] Output: 3 Explanation: The initial sum of nums is equal to 3 + 8 + 20 = 31. The following is one of the ways to reduce the sum by at least half: Pick the number 20 and reduce it to 10. Pick the number 10 and reduce it to 5. Pick the number 3 and reduce it to 1.5. The final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. The sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5. Overall, 3 operations were used so we return 3. It can be shown that we cannot reduce the sum by at least half in less than 3 operations. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 107
python 3 || priority queue
79
minimum-operations-to-halve-array-sum
0.452
dereky4
Medium
30,630
2,208
minimum white tiles after covering with carpets
class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: @cache def fn(i, n): """Return min while tiles at k with n carpets left.""" if n < 0: return inf if i >= len(floor): return 0 if floor[i] == '1': return min(fn(i+carpetLen, n-1), 1 + fn(i+1, n)) return fn(i+1, n) return fn(0, numCarpets)
https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1874969/Python3-dp
2
You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: floor[i] = '0' denotes that the ith tile of the floor is colored black. On the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white. You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. Example 1: Input: floor = "10110101", numCarpets = 2, carpetLen = 2 Output: 2 Explanation: The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible. No other way of covering the tiles with the carpets can leave less than 2 white tiles visible. Example 2: Input: floor = "11111", numCarpets = 2, carpetLen = 3 Output: 0 Explanation: The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible. Note that the carpets are able to overlap one another. Constraints: 1 <= carpetLen <= floor.length <= 1000 floor[i] is either '0' or '1'. 1 <= numCarpets <= 1000
[Python3] dp
51
minimum-white-tiles-after-covering-with-carpets
0.338
ye15
Hard
30,637
2,209
count hills and valleys in an array
class Solution: def countHillValley(self, nums: List[int]) -> int: #cnt: An integer to store total hills and valleys #left: Highest point of hill or lowest point of valley left of the current index cnt, left = 0, nums[0] for i in range(1, len(nums)-1): if (left<nums[i] and nums[i]>nums[i+1]) or (left>nums[i] and nums[i]<nums[i+1]): cnt+=1 left=nums[i] return cnt
https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1866869/Python3-One-pass-oror-O(1)-space
3
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. Example 1: Input: nums = [2,4,1,1,6,5] Output: 3 Explanation: At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley. At index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. At index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley. At index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2. At index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill. At index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. There are 3 hills and valleys so we return 3. Example 2: Input: nums = [6,6,5,5,4,1] Output: 0 Explanation: At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley. At index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley. At index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley. At index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley. At index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley. At index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley. There are 0 hills and valleys so we return 0. Constraints: 3 <= nums.length <= 100 1 <= nums[i] <= 100
[Python3] One pass || O(1) space
82
count-hills-and-valleys-in-an-array
0.581
__PiYush__
Easy
30,644
2,210
count collisions on a road
class Solution: def countCollisions(self, directions: str) -> int: return sum(d!='S' for d in directions.lstrip('L').rstrip('R'))
https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865694/One-liner-in-Python
65
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: When two cars moving in opposite directions collide with each other, the number of collisions increases by 2. When a moving car collides with a stationary car, the number of collisions increases by 1. After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. Example 1: Input: directions = "RLRSLL" Output: 5 Explanation: The collisions that will happen on the road are: - Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2. - Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3. - Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4. - Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5. Thus, the total number of collisions that will happen on the road is 5. Example 2: Input: directions = "LLRR" Output: 0 Explanation: No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0. Constraints: 1 <= directions.length <= 105 directions[i] is either 'L', 'R', or 'S'.
One-liner in Python
1,200
count-collisions-on-a-road
0.419
LuckyBoy88
Medium
30,666
2,211
maximum points in an archery competition
class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: # Initialization with round 1 (round 0 is skipped) dp = {(0, 0): (0, numArrows), (0, aliceArrows[1] + 1): (1, numArrows - (aliceArrows[1] + 1))} # Loop from round 2 for i in range(2, 12): prev = dp dp = {} # Consider two possible strategies for each state from last round: to bid and not to bid for key in prev: # Base case: not to bid in this round. Score and arrows left do not change. # Simply append 0 at the end to the key. newkey1 = list(key) newkey1.append(0) score, arrowleft = prev[key] newval1 = (score, arrowleft) dp[tuple(newkey1)] = newval1 # If we still have enough arrows, we can bid in this round if arrowleft >= aliceArrows[i] + 1: newkey2 = list(key) newkey2.append(aliceArrows[i] + 1) newval2 = (score + i, arrowleft - (aliceArrows[i] + 1)) dp[tuple(newkey2)] = newval2 # Select the bidding history with max score maxscore, res = 0, None for key in dp: score, _ = dp[key] if score > maxscore: maxscore = score res = list(key) # Taking care of the corner case, where too many arrows are given if sum(res) < numArrows: res[0] = numArrows - sum(res) return res
https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1866042/Python3-DP-100-with-Detailed-Explanation
1
Alice and Bob are opponents in an archery competition. The competition has set the following rules: Alice first shoots numArrows arrows and then Bob shoots numArrows arrows. The points are then calculated as follows: The target has integer scoring sections ranging from 0 to 11 inclusive. For each section of the target with score k (in between 0 to 11), say Alice and Bob have shot ak and bk arrows on that section respectively. If ak >= bk, then Alice takes k points. If ak < bk, then Bob takes k points. However, if ak == bk == 0, then nobody takes k points. For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. Example 1: Input: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0] Output: [0,0,0,0,1,1,0,0,1,2,3,1] Explanation: The table above shows how the competition is scored. Bob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47. It can be shown that Bob cannot obtain a score higher than 47 points. Example 2: Input: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2] Output: [0,0,0,0,0,0,0,0,1,1,1,0] Explanation: The table above shows how the competition is scored. Bob earns a total point of 8 + 9 + 10 = 27. It can be shown that Bob cannot obtain a score higher than 27 points. Constraints: 1 <= numArrows <= 105 aliceArrows.length == bobArrows.length == 12 0 <= aliceArrows[i], bobArrows[i] <= numArrows sum(aliceArrows[i]) == numArrows
[Python3] DP 100% with Detailed Explanation
68
maximum-points-in-an-archery-competition
0.489
hsjiang
Medium
30,682
2,212
find the difference of two arrays
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: set_1 = list_to_set(nums1) set_2 = list_to_set(nums2) return remove_same_elements(set_1, set_2) # Convert the lists into sets via helper method. def list_to_set(arr: List[int]): s = set() for i in arr: s.add(i) return s # Now when the two lists are sets, use the difference attribute to filter common elements of the two sets. def remove_same_elements(x, y): x, y = list(x - y), list(y - x) return [x, y] # Runtime: 185 ms, faster than 95.96% of Python3 online submissions for Find the Difference of Two Arrays. # Memory Usage: 14.3 MB, less than 51.66% of Python3 online submissions for Find the Difference of Two Arrays. # If you like my work, then I'll appreciate a like. Thanks!
https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2668224/Python-solution.-Clean-code-with-full-comments.-95.96-speed.
3
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: answer[0] is a list of all distinct integers in nums1 which are not present in nums2. answer[1] is a list of all distinct integers in nums2 which are not present in nums1. Note that the integers in the lists may be returned in any order. Example 1: Input: nums1 = [1,2,3], nums2 = [2,4,6] Output: [[1,3],[4,6]] Explanation: For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3]. For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6]. Example 2: Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2] Output: [[3],[]] Explanation: For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3]. Every integer in nums2 is present in nums1. Therefore, answer[1] = []. Constraints: 1 <= nums1.length, nums2.length <= 1000 -1000 <= nums1[i], nums2[i] <= 1000
Python solution. Clean code with full comments. 95.96% speed.
159
find-the-difference-of-two-arrays
0.693
375d
Easy
30,692
2,215
minimum deletions to make array beautiful
class Solution: def minDeletion(self, nums: List[int]) -> int: # Greedy ! # we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0 # at the begining, we consider the num on the even index # when we delete a num, we need consider the num on the odd index # then repeat this process # at the end we check the requirement 1: nums.length is even or not n = len(nums) count = 0 # flag is true then check the even index # flag is false then check the odd index flag = True for i in range(n): # check the even index if flag: if i % 2 == 0 and i != n -1 and nums[i] == nums[i + 1]: count += 1 flag = False # check the odd index elif not flag: if i % 2 == 1 and i != n -1 and nums[i] == nums[i + 1]: count += 1 flag = True curLength = n - count return count if curLength % 2 == 0 else count + 1
https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/discuss/1886918/Python-or-Greedy
10
You are given a 0-indexed integer array nums. The array nums is beautiful if: nums.length is even. nums[i] != nums[i + 1] for all i % 2 == 0. Note that an empty array is considered beautiful. You can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged. Return the minimum number of elements to delete from nums to make it beautiful. Example 1: Input: nums = [1,1,2,3,5] Output: 1 Explanation: You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful. Example 2: Input: nums = [1,1,2,2,3,3] Output: 2 Explanation: You can delete nums[0] and nums[5] to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful. Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 105
Python | Greedy
397
minimum-deletions-to-make-array-beautiful
0.463
Mikey98
Medium
30,733
2,216
find palindrome with fixed length
class Solution: def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]: # think the palindromes in half # e.g. len = 4 we only consider the first 2 digits # half: 10, 11, 12, 13, 14, ..., 19, 20, # full: 1001, 1111, 1221, 1331, ... # e.g. len = 5 we consider the first 3 digits # half: 100, 101, 102, ... # full: 10001, 10101, 10201, ... result = [] for i in queries: result.append(self.generatePalindrome(intLength, i)) return result def generatePalindrome(self, length, num): # index start from 0 # e.g. num =1 means we want to find the most smallest palindrome, then its index is 0 # e.g. num =2 means we want to find the second most smallest palindrome, then its index is 1 index = num -1 # if the length is even # we only think about the fisrt half of digits if length % 2 == 0: cur = int('1' + '0' * (length // 2 -1)) maxLength = len(str(cur)) cur += index if len(str(cur)) > maxLength: return -1 else: cur = str(cur) cur = cur + cur[::-1] cur = int(cur) return cur # if the length is odd # we consider first (length // 2 + 1) digits else: cur = int('1' + '0' * (length // 2)) maxLength = len(str(cur)) cur += index if len(str(cur)) > maxLength: return -1 else: cur = str(cur) temp = str(cur)[:-1] cur = cur + temp[::-1] cur = int(cur) return cur
https://leetcode.com/problems/find-palindrome-with-fixed-length/discuss/1886956/Python-or-simple-and-straightforward
6
Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists. A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros. Example 1: Input: queries = [1,2,3,4,5,90], intLength = 3 Output: [101,111,121,131,141,999] Explanation: The first few palindromes of length 3 are: 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ... The 90th palindrome of length 3 is 999. Example 2: Input: queries = [2,4,6], intLength = 4 Output: [1111,1331,1551] Explanation: The first six palindromes of length 4 are: 1001, 1111, 1221, 1331, 1441, and 1551. Constraints: 1 <= queries.length <= 5 * 104 1 <= queries[i] <= 109 1 <= intLength <= 15
Python | simple and straightforward
474
find-palindrome-with-fixed-length
0.343
Mikey98
Medium
30,750
2,217
maximum value of k coins from piles
class Solution: def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: n, m = len(piles), 0 prefixSum = [] for i in range(n): temp = [0] for j in range(len(piles[i])): temp.append(temp[-1] + piles[i][j]) m += 1 prefixSum.append(temp) if m == k: return sum(temp[-1] for temp in prefixSum) dp = [[0] * (k + 1) for _ in range(n)] for j in range(1, k + 1): if j < len(prefixSum[0]): dp[0][j] = prefixSum[0][j] for i in range(1, n): for j in range(1, k + 1): for l in range(len(prefixSum[i])): if l > j: break dp[i][j] = max(dp[i][j], prefixSum[i][l] + dp[i - 1][j - l]) return dp[n - 1][k]
https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/discuss/1889647/Python-Bottom-up-DP-solution
9
There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally. Example 1: Input: piles = [[1,100,3],[7,8,9]], k = 2 Output: 101 Explanation: The above diagram shows the different ways we can choose k coins. The maximum total we can obtain is 101. Example 2: Input: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7 Output: 706 Explanation: The maximum total can be obtained if we choose all coins from the last pile. Constraints: n == piles.length 1 <= n <= 1000 1 <= piles[i][j] <= 105 1 <= k <= sum(piles[i].length) <= 2000
[Python] Bottom-up DP solution
407
maximum-value-of-k-coins-from-piles
0.48
xil899
Hard
30,764
2,218
minimum bit flips to convert number
class Solution: def minBitFlips(self, s: int, g: int) -> int: count = 0 while s or g: if s%2 != g%2: count+=1 s, g = s//2, g//2 return count
https://leetcode.com/problems/minimum-bit-flips-to-convert-number/discuss/2775126/Python-Solution-without-XOR
4
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. Example 1: Input: start = 10, goal = 7 Output: 3 Explanation: The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps: - Flip the first bit from the right: 1010 -> 1011. - Flip the third bit from the right: 1011 -> 1111. - Flip the fourth bit from the right: 1111 -> 0111. It can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3. Example 2: Input: start = 3, goal = 4 Output: 3 Explanation: The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps: - Flip the first bit from the right: 011 -> 010. - Flip the second bit from the right: 010 -> 000. - Flip the third bit from the right: 000 -> 100. It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3. Constraints: 0 <= start, goal <= 109
Python Solution without XOR
134
minimum-bit-flips-to-convert-number
0.821
keioon
Easy
30,769
2,220
find triangular sum of an array
class Solution: def triangularSum(self, nums: List[int]) -> int: return sum(n * comb(len(nums) - 1, i) for i, n in enumerate(nums)) % 10
https://leetcode.com/problems/find-triangular-sum-of-an-array/discuss/1909302/Pascal-Triangle
28
You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1. For each index i, where 0 <= i < n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator. Replace the array nums with newNums. Repeat the entire process starting from step 1. Return the triangular sum of nums. Example 1: Input: nums = [1,2,3,4,5] Output: 8 Explanation: The above diagram depicts the process from which we obtain the triangular sum of the array. Example 2: Input: nums = [5] Output: 5 Explanation: Since there is only one element in nums, the triangular sum is the value of that element itself. Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 9
Pascal Triangle
3,800
find-triangular-sum-of-an-array
0.79
votrubac
Medium
30,798
2,221
number of ways to select buildings
class Solution: def numberOfWays(self, s: str) -> int: zeros = s.count('0') ones = len(s) - zeros zeroPrefix = onePrefix = res = 0 for c in s: if c == '0': res += onePrefix * (ones - onePrefix) zeroPrefix += 1 else: res += zeroPrefix * (zeros - zeroPrefix) onePrefix += 1 return res
https://leetcode.com/problems/number-of-ways-to-select-buildings/discuss/1979756/python-3-oror-short-and-simple-oror-O(n)O(1)
5
You are given a 0-indexed binary string s which represents the types of buildings along a street where: s[i] = '0' denotes that the ith building is an office and s[i] = '1' denotes that the ith building is a restaurant. As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. For example, given s = "001101", we cannot select the 1st, 3rd, and 5th buildings as that would form "011" which is not allowed due to having two consecutive buildings of the same type. Return the number of valid ways to select 3 buildings. Example 1: Input: s = "001101" Output: 6 Explanation: The following sets of indices selected are valid: - [0,2,4] from "001101" forms "010" - [0,3,4] from "001101" forms "010" - [1,2,4] from "001101" forms "010" - [1,3,4] from "001101" forms "010" - [2,4,5] from "001101" forms "101" - [3,4,5] from "001101" forms "101" No other selection is valid. Thus, there are 6 total ways. Example 2: Input: s = "11100" Output: 0 Explanation: It can be shown that there are no valid selections. Constraints: 3 <= s.length <= 105 s[i] is either '0' or '1'.
python 3 || short and simple || O(n)/O(1)
304
number-of-ways-to-select-buildings
0.512
dereky4
Medium
30,844
2,222
sum of scores of built strings
class Solution: def sumScores(self, s: str) -> int: mod = 119_218_851_371 hs = 0 vals = [0] for i, ch in enumerate(s): hs = (hs * 26 + ord(ch) - 97) % mod vals.append(hs) p26 = [1] for _ in range(len(s)): p26.append(p26[-1] * 26 % mod) ans = 0 for i in range(len(s)): if s[0] == s[i]: lo, hi = i, len(s) while lo < hi: mid = lo + hi + 1 >> 1 hs = (vals[mid] - vals[i]*p26[mid-i]) % mod if hs == vals[mid-i]: lo = mid else: hi = mid - 1 ans += lo - i return ans
https://leetcode.com/problems/sum-of-scores-of-built-strings/discuss/2256814/Python3-rolling-hash-and-z-algorithm
1
You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. For example, for s = "abaca", s1 == "a", s2 == "ca", s3 == "aca", etc. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s, return the sum of the score of every si. Example 1: Input: s = "babab" Output: 9 Explanation: For s1 == "b", the longest common prefix is "b" which has a score of 1. For s2 == "ab", there is no common prefix so the score is 0. For s3 == "bab", the longest common prefix is "bab" which has a score of 3. For s4 == "abab", there is no common prefix so the score is 0. For s5 == "babab", the longest common prefix is "babab" which has a score of 5. The sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9. Example 2: Input: s = "azbazbzaz" Output: 14 Explanation: For s2 == "az", the longest common prefix is "az" which has a score of 2. For s6 == "azbzaz", the longest common prefix is "azb" which has a score of 3. For s9 == "azbazbzaz", the longest common prefix is "azbazbzaz" which has a score of 9. For all other si, the score is 0. The sum of the scores is 2 + 3 + 9 = 14, so we return 14. Constraints: 1 <= s.length <= 105 s consists of lowercase English letters.
[Python3] rolling hash & z-algorithm
82
sum-of-scores-of-built-strings
0.37
ye15
Hard
30,852
2,223
minimum number of operations to convert time
class Solution: def convertTime(self, current: str, correct: str) -> int: current_time = 60 * int(current[0:2]) + int(current[3:5]) # Current time in minutes target_time = 60 * int(correct[0:2]) + int(correct[3:5]) # Target time in minutes diff = target_time - current_time # Difference b/w current and target times in minutes count = 0 # Required number of operations # Use GREEDY APPROACH to calculate number of operations for i in [60, 15, 5, 1]: count += diff // i # add number of operations needed with i to count diff %= i # Diff becomes modulo of diff with i return count
https://leetcode.com/problems/minimum-number-of-operations-to-convert-time/discuss/1908786/Easy-Python-Solution-or-Convert-time-to-minutes
30
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct. Example 1: Input: current = "02:30", correct = "04:35" Output: 3 Explanation: We can convert current to correct in 3 operations as follows: - Add 60 minutes to current. current becomes "03:30". - Add 60 minutes to current. current becomes "04:30". - Add 5 minutes to current. current becomes "04:35". It can be proven that it is not possible to convert current to correct in fewer than 3 operations. Example 2: Input: current = "11:00", correct = "11:01" Output: 1 Explanation: We only have to add one minute to current, so the minimum number of operations needed is 1. Constraints: current and correct are in the format "HH:MM" current <= correct
⭐Easy Python Solution | Convert time to minutes
1,200
minimum-number-of-operations-to-convert-time
0.655
anCoderr
Easy
30,856
2,224
find players with zero or one losses
class Solution: def findWinners(self, matches: List[List[int]]) -> List[List[int]]: winners, losers, table = [], [], {} for winner, loser in matches: # map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented. # map.get(key, 0) returns map[key] if key exists and 0 if it does not. table[winner] = table.get(winner, 0) # Winner table[loser] = table.get(loser, 0) + 1 for k, v in table.items(): # Player k with losses v if v == 0: winners.append(k) # If player k has no loss ie v == 0 if v == 1: losers.append(k) # If player k has one loss ie v == 1 return [sorted(winners), sorted(losers)] # Problem asked to return sorted arrays.
https://leetcode.com/problems/find-players-with-zero-or-one-losses/discuss/1908760/Python-Solution-with-Hashmap
22
You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match. Return a list answer of size 2 where: answer[0] is a list of all players that have not lost any matches. answer[1] is a list of all players that have lost exactly one match. The values in the two lists should be returned in increasing order. Note: You should only consider the players that have played at least one match. The testcases will be generated such that no two matches will have the same outcome. Example 1: Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]] Output: [[1,2,10],[4,5,7,8]] Explanation: Players 1, 2, and 10 have not lost any matches. Players 4, 5, 7, and 8 each have lost one match. Players 3, 6, and 9 each have lost two matches. Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8]. Example 2: Input: matches = [[2,3],[1,3],[5,4],[6,4]] Output: [[1,2,5,6],[]] Explanation: Players 1, 2, 5, and 6 have not lost any matches. Players 3 and 4 each have lost two matches. Thus, answer[0] = [1,2,5,6] and answer[1] = []. Constraints: 1 <= matches.length <= 105 matches[i].length == 2 1 <= winneri, loseri <= 105 winneri != loseri All matches[i] are unique.
⭐Python Solution with Hashmap
1,200
find-players-with-zero-or-one-losses
0.686
anCoderr
Medium
30,877
2,225
maximum candies allocated to k children
class Solution: def maximumCandies(self, candies, k): n = len(candies) left = 1 # the least number of candy in each stack we can give to each student is one right = max(candies) # the max number of candy in each stack that we can give to each student is the maximum number in the candies array ans = 0 # ans here is used to store the maximum amount in each stack that we can give to each children. # If we don't have enough to distribute, we will return 0 at the end so we initialize it to be 0 now. while left <= right: # binary search numberOfPiles = 0 mid = (left) + (right - left) // 2 # the number of candies we require to form a stack for i in range(n): # loop through the array to find the numbers of stack we can form numberOfPiles += candies[i] // mid # we add to the numberOfPiles whenever we find that this current stack (candies[i]) can be split into mid (the number of candies we require to form a stack) if numberOfPiles >= k: # if our number of piles is greater or equal than the students we have, so we have enough to distribute ans = max(ans, mid) # we first store the max no. of candies in each stack that we can give to each student left = mid + 1 # we will try to increase the number of candies in each stack that we can give to each student else: right = mid - 1 # we will try to reduce the number of candies in each stack that we can give to each student return ans
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1912213/Easy-To-Understand-Python-Solution-(Binary-Search)
2
You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get. Example 1: Input: candies = [5,8,6], k = 3 Output: 5 Explanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies. Example 2: Input: candies = [2,5], k = 11 Output: 0 Explanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0. Constraints: 1 <= candies.length <= 105 1 <= candies[i] <= 107 1 <= k <= 1012
Easy To Understand Python Solution (Binary Search)
87
maximum-candies-allocated-to-k-children
0.361
danielkua
Medium
30,899
2,226
largest number after digit swaps by parity
class Solution: def largestInteger(self, num: int): n = len(str(num)) arr = [int(i) for i in str(num)] odd, even = [], [] for i in arr: if i % 2 == 0: even.append(i) else: odd.append(i) odd.sort() even.sort() res = 0 for i in range(n): if arr[i] % 2 == 0: res = res*10 + even.pop() else: res = res*10 + odd.pop() return res
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1931017/Python-Solution-using-Sorting
17
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. Example 1: Input: num = 1234 Output: 3412 Explanation: Swap the digit 3 with the digit 1, this results in the number 3214. Swap the digit 2 with the digit 4, this results in the number 3412. Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number. Also note that we may not swap the digit 4 with the digit 1 since they are of different parities. Example 2: Input: num = 65875 Output: 87655 Explanation: Swap the digit 8 with the digit 6, this results in the number 85675. Swap the first digit 5 with the digit 7, this results in the number 87655. Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number. Constraints: 1 <= num <= 109
Python Solution using Sorting
1,500
largest-number-after-digit-swaps-by-parity
0.605
anCoderr
Easy
30,913
2,231
minimize result by adding parentheses to expression
class Solution: def minimizeResult(self, expression: str) -> str: plus_index, n, ans = expression.find('+'), len(expression), [float(inf),expression] def evaluate(exps: str): return eval(exps.replace('(','*(').replace(')', ')*').lstrip('*').rstrip('*')) for l in range(plus_index): for r in range(plus_index+1, n): exps = f'{expression[:l]}({expression[l:plus_index]}+{expression[plus_index+1:r+1]}){expression[r+1:n]}' res = evaluate(exps) if ans[0] > res: ans[0], ans[1] = res, exps return ans[1]
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1931004/Python-Solution-using-2-Pointers-Brute-Force
12
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer. Example 1: Input: expression = "247+38" Output: "2(47+38)" Explanation: The expression evaluates to 2 * (47 + 38) = 2 * 85 = 170. Note that "2(4)7+38" is invalid because the right parenthesis must be to the right of the '+'. It can be shown that 170 is the smallest possible value. Example 2: Input: expression = "12+34" Output: "1(2+3)4" Explanation: The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20. Example 3: Input: expression = "999+999" Output: "(999+999)" Explanation: The expression evaluates to 999 + 999 = 1998. Constraints: 3 <= expression.length <= 10 expression consists of digits from '1' to '9' and '+'. expression starts and ends with digits. expression contains exactly one '+'. The original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
Python Solution using 2 Pointers Brute Force
1,500
minimize-result-by-adding-parentheses-to-expression
0.651
anCoderr
Medium
30,930
2,232
maximum product after k increments
class Solution: def maximumProduct(self, nums: List[int], k: int) -> int: heap = nums.copy() heapify(heap) for i in range(k): t = heappop(heap) heappush(heap, t + 1) ans = 1 mod = 1000000007 for i in heap: ans = (ans*i) % mod return ans
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1930986/Python-Solution-using-Min-Heap
2
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo. Example 1: Input: nums = [0,4], k = 5 Output: 20 Explanation: Increment the first number 5 times. Now nums = [5, 4], with a product of 5 * 4 = 20. It can be shown that 20 is maximum product possible, so we return 20. Note that there may be other ways to increment nums to have the maximum product. Example 2: Input: nums = [6,3,3,2], k = 2 Output: 216 Explanation: Increment the second number 1 time and increment the fourth number 1 time. Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216. It can be shown that 216 is maximum product possible, so we return 216. Note that there may be other ways to increment nums to have the maximum product. Constraints: 1 <= nums.length, k <= 105 0 <= nums[i] <= 106
➡️Python Solution using Min Heap
150
maximum-product-after-k-increments
0.413
anCoderr
Medium
30,947
2,233
maximum total beauty of the gardens
class Solution: def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int: flowers = sorted(min(target, x) for x in flowers) prefix = [0] ii = -1 for i in range(len(flowers)): if flowers[i] < target: ii = i if i: prefix.append(prefix[-1] + (flowers[i]-flowers[i-1])*i) ans = 0 for k in range(len(flowers)+1): if k: newFlowers -= target - flowers[-k] if newFlowers >= 0: while 0 <= ii and (ii+k >= len(flowers) or prefix[ii] > newFlowers): ii -= 1 if 0 <= ii: kk = min(target-1, flowers[ii] + (newFlowers - prefix[ii])//(ii+1)) else: kk = 0 ans = max(ans, k*full + kk*partial) return ans
https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/discuss/2313576/Python3-2-pointer
1
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: The number of complete gardens multiplied by full. The minimum number of flowers in any of the incomplete gardens multiplied by partial. If there are no incomplete gardens, then this value will be 0. Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers. Example 1: Input: flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1 Output: 14 Explanation: Alice can plant - 2 flowers in the 0th garden - 3 flowers in the 1st garden - 1 flower in the 2nd garden - 1 flower in the 3rd garden The gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers. There is 1 garden that is complete. The minimum number of flowers in the incomplete gardens is 2. Thus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14. No other way of planting flowers can obtain a total beauty higher than 14. Example 2: Input: flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6 Output: 30 Explanation: Alice can plant - 3 flowers in the 0th garden - 0 flowers in the 1st garden - 0 flowers in the 2nd garden - 2 flowers in the 3rd garden The gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers. There are 3 gardens that are complete. The minimum number of flowers in the incomplete gardens is 4. Thus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30. No other way of planting flowers can obtain a total beauty higher than 30. Note that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty. Constraints: 1 <= flowers.length <= 105 1 <= flowers[i], target <= 105 1 <= newFlowers <= 1010 1 <= full, partial <= 105
[Python3] 2-pointer
61
maximum-total-beauty-of-the-gardens
0.283
ye15
Hard
30,958
2,234
add two integers
class Solution: def sum(self, num1: int, num2: int) -> int: return num1 + num2
https://leetcode.com/problems/add-two-integers/discuss/2670517/Solutions-in-Every-Language-*on-leetcode*-or-One-Liner
5
Given two integers num1 and num2, return the sum of the two integers. Example 1: Input: num1 = 12, num2 = 5 Output: 17 Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. Example 2: Input: num1 = -10, num2 = 4 Output: -6 Explanation: num1 + num2 = -6, so -6 is returned. Constraints: -100 <= num1, num2 <= 100
Solutions in Every Language *on leetcode* | One-Liner ✅
465
add-two-integers
0.894
qing306037
Easy
30,961
2,235
root equals sum of children
class Solution: def checkTree(self, root: Optional[TreeNode]) -> bool: return root.left.val+root.right.val == root.val
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2178260/Python-oneliner
5
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise. Example 1: Input: root = [10,4,6] Output: true Explanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively. 10 is equal to 4 + 6, so we return true. Example 2: Input: root = [5,3,1] Output: false Explanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively. 5 is not equal to 3 + 1, so we return false. Constraints: The tree consists only of the root, its left child, and its right child. -100 <= Node.val <= 100
Python oneliner
322
root-equals-sum-of-children
0.869
StikS32
Easy
30,983
2,236
find closest number to zero
class Solution: def findClosestNumber(self, nums: List[int]) -> int: m = 10 ** 6 for i in nums: x = abs(i-0) if x < m: m = x val = i elif x == m and val < i: val = i return val
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1959624/Python-dollarolution
2
Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value. Example 1: Input: nums = [-4,-2,1,4,8] Output: 1 Explanation: The distance from -4 to 0 is |-4| = 4. The distance from -2 to 0 is |-2| = 2. The distance from 1 to 0 is |1| = 1. The distance from 4 to 0 is |4| = 4. The distance from 8 to 0 is |8| = 8. Thus, the closest number to 0 in the array is 1. Example 2: Input: nums = [2,-1,1] Output: 1 Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned. Constraints: 1 <= n <= 1000 -105 <= nums[i] <= 105
Python $olution
180
find-closest-number-to-zero
0.458
AakRay
Easy
30,998
2,239
number of ways to buy pens and pencils
class Solution: def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int: if total < cost1 and total < cost2: return 1 ways = 0 if cost1 > cost2: for i in range(0, (total // cost1)+1): rem = total - (i * cost1) ways += (rem // cost2) + 1 return ways for i in range(0, (total // cost2)+1): rem = total - (i * cost2) ways += (rem // cost1) + 1 return ways
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1962778/Python-easy-solution-faster-than-90
2
You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil. Return the number of distinct ways you can buy some number of pens and pencils. Example 1: Input: total = 20, cost1 = 10, cost2 = 5 Output: 9 Explanation: The price of a pen is 10 and the price of a pencil is 5. - If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils. - If you buy 1 pen, you can buy 0, 1, or 2 pencils. - If you buy 2 pens, you cannot buy any pencils. The total number of ways to buy pens and pencils is 5 + 3 + 1 = 9. Example 2: Input: total = 5, cost1 = 10, cost2 = 10 Output: 1 Explanation: The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils. Constraints: 1 <= total, cost1, cost2 <= 106
Python easy solution faster than 90%
84
number-of-ways-to-buy-pens-and-pencils
0.57
alishak1999
Medium
31,026
2,240
maximum score of a node sequence
class Solution: def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int: connection = {} for source, target in edges: if source not in connection: connection[source] = [target] else: connection[source].append(target) if target not in connection: connection[target] = [source] else: connection[target].append(source) res = -1 max_dict = {} for key, value in connection.items(): max1, max2, max3 = -sys.maxsize, -sys.maxsize, -sys.maxsize n1, n2, n3 = None, None, None for element in value: if scores[element] > max1: max1, max2, max3 = scores[element], max1, max2 n1, n2, n3 = element, n1, n2 elif scores[element] > max2: max2, max3 = scores[element], max2 n2, n3 = element, n2 elif scores[element] > max3: max3 = scores[element] n3 = element max_dict[key] = [] if n1 != None: max_dict[key].append(n1) if n2 != None: max_dict[key].append(n2) if n3 != None: max_dict[key].append(n3) for source, target in edges: base = scores[source] + scores[target] n_s = max_dict[source] n_t = max_dict[target] if len(n_s) == 1 or len(n_t) == 1: pass else: new_n_s = [x for x in n_s if x != target] new_n_t = [x for x in n_t if x != source] if new_n_s[0] != new_n_t[0]: res = max(res, base + scores[new_n_s[0]] + scores[new_n_t[0]]) else: if len(new_n_s) > 1: res = max(res, base + scores[new_n_s[1]] + scores[new_n_t[0]]) if len(new_n_t) > 1: res = max(res, base + scores[new_n_s[0]] + scores[new_n_t[1]]) return res
https://leetcode.com/problems/maximum-score-of-a-node-sequence/discuss/1984916/Python3-O(orEor)-solution
2
There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. A node sequence is valid if it meets the following conditions: There is an edge connecting every pair of adjacent nodes in the sequence. No node appears more than once in the sequence. The score of a node sequence is defined as the sum of the scores of the nodes in the sequence. Return the maximum score of a valid node sequence with a length of 4. If no such sequence exists, return -1. Example 1: Input: scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]] Output: 24 Explanation: The figure above shows the graph and the chosen node sequence [0,1,2,3]. The score of the node sequence is 5 + 2 + 9 + 8 = 24. It can be shown that no other node sequence has a score of more than 24. Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24. The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3. Example 2: Input: scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]] Output: -1 Explanation: The figure above shows the graph. There are no valid node sequences of length 4, so we return -1. Constraints: n == scores.length 4 <= n <= 5 * 104 1 <= scores[i] <= 108 0 <= edges.length <= 5 * 104 edges[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no duplicate edges.
Python3 O(|E|) solution
239
maximum-score-of-a-node-sequence
0.375
xxHRxx
Hard
31,037
2,242
calculate digit sum of a string
class Solution: def digitSum(self, s: str, k: int) -> str: while len(s) > k: set_3 = [s[i:i+k] for i in range(0, len(s), k)] s = '' for e in set_3: val = 0 for n in e: val += int(n) s += str(val) return s
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1955460/Python3-elegant-pythonic-clean-and-easy-to-understand
10
You are given a string s consisting of digits and an integer k. A round can be completed if the length of s is greater than k. In one round, do the following: Divide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k. Replace each group of s with a string representing the sum of all its digits. For example, "346" is replaced with "13" because 3 + 4 + 6 = 13. Merge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1. Return s after all rounds have been completed. Example 1: Input: s = "11111222223", k = 3 Output: "135" Explanation: - For the first round, we divide s into groups of size 3: "111", "112", "222", and "23". Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round. - For the second round, we divide s into "346" and "5". Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. So, s becomes "13" + "5" = "135" after second round. Now, s.length <= k, so we return "135" as the answer. Example 2: Input: s = "00000000", k = 3 Output: "000" Explanation: We divide s into "000", "000", and "00". Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000". Constraints: 1 <= s.length <= 100 2 <= k <= 100 s consists of digits only.
Python3 elegant pythonic clean and easy to understand
881
calculate-digit-sum-of-a-string
0.668
Tallicia
Easy
31,038
2,243
minimum rounds to complete all tasks
class Solution: def minimumRounds(self, tasks: List[int]) -> int: table, res = Counter(tasks), 0 # Counter to hold frequency of ith task and res stores the result. for count in table.values(): if count <= 1: return -1 # If count <= 1 then it cannot follow the condition hence return -1. res += ceil(count / 3) # Total number of groups increments after 3 values. return res
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1955367/Well-Explained-Python-Solution
4
You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks. Example 1: Input: tasks = [2,2,3,3,2,4,4,4,4,4] Output: 4 Explanation: To complete all the tasks, a possible plan is: - In the first round, you complete 3 tasks of difficulty level 2. - In the second round, you complete 2 tasks of difficulty level 3. - In the third round, you complete 3 tasks of difficulty level 4. - In the fourth round, you complete 2 tasks of difficulty level 4. It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4. Example 2: Input: tasks = [2,3,3] Output: -1 Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1. Constraints: 1 <= tasks.length <= 105 1 <= tasks[i] <= 109
⭐ Well Explained Python Solution
184
minimum-rounds-to-complete-all-tasks
0.575
anCoderr
Medium
31,071
2,244
maximum trailing zeros in a cornered path
class Solution: def maxTrailingZeros(self, grid: List[List[int]]) -> int: ans = 0 m, n = len(grid), len(grid[0]) prefixH = [[[0] * 2 for _ in range(n + 1)] for __ in range(m)] prefixV = [[[0] * 2 for _ in range(n)] for __ in range(m + 1)] for i in range(m): for j in range(n): temp= grid[i][j] while temp % 2 == 0: prefixH[i][j + 1][0] += 1 prefixV[i + 1][j][0] += 1 temp //= 2 while temp % 5 == 0: prefixH[i][j + 1][1] += 1 prefixV[i + 1][j][1] += 1 temp //= 5 for k in range(2): prefixH[i][j + 1][k] += prefixH[i][j][k] prefixV[i + 1][j][k] += prefixV[i][j][k] for i in range(m): for j in range(n): left = prefixH[i][j] up = prefixV[i][j] right, down, center = [0] * 2, [0] * 2, [0] * 2 for k in range(2): right[k] = prefixH[i][n][k] - prefixH[i][j + 1][k] down[k] = prefixV[m][j][k] - prefixV[i + 1][j][k] center[k] = prefixH[i][j + 1][k] - prefixH[i][j][k] LU, LD, RU, RD = [0] * 2, [0] * 2, [0] * 2, [0] * 2 for k in range(2): LU[k] += left[k] + up[k] + center[k] LD[k] += left[k] + down[k] + center[k] RU[k] += right[k] + up[k] + center[k] RD[k] += right[k] + down[k] + center[k] ans = max(ans, min(LU[0], LU[1]), min(LD[0], LD[1]), min(RU[0], RU[1]), min(RD[0], RD[1])) return ans
https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/discuss/1955502/Python-Prefix-Sum-O(m-*-n)
7
You are given a 2D integer array grid of size m x n, where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell. The product of a path is defined as the product of all the values in the path. Return the maximum number of trailing zeros in the product of a cornered path found in grid. Note: Horizontal movement means moving in either the left or right direction. Vertical movement means moving in either the up or down direction. Example 1: Input: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]] Output: 3 Explanation: The grid on the left shows a valid cornered path. It has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros. It can be shown that this is the maximum trailing zeros in the product of a cornered path. The grid in the middle is not a cornered path as it has more than one turn. The grid on the right is not a cornered path as it requires a return to a previously visited cell. Example 2: Input: grid = [[4,3,2],[7,6,1],[8,8,8]] Output: 0 Explanation: The grid is shown in the figure above. There are no cornered paths in the grid that result in a product with a trailing zero. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 105 1 <= m * n <= 105 1 <= grid[i][j] <= 1000
[Python] Prefix Sum, O(m * n)
574
maximum-trailing-zeros-in-a-cornered-path
0.35
xil899
Medium
31,090
2,245
longest path with different adjacent characters
class Solution: def longestPath(self, par: List[int], s: str) -> int: dit = {} # store tree in dictionary for i in range(len(par)): if par[i] in dit: dit[par[i]].append(i) else: dit[par[i]] = [i] ans = 1 def dfs(n): nonlocal ans if n not in dit: return 1 largest=0 # largest path lenght among all children second_largest=0 # second largest path lenght among all children for u in dit[n]: curr = dfs(u) if s[u]!=s[n]: # pick child path if child and parent both have different value if curr>largest: second_largest = largest largest = curr elif curr>second_largest: second_largest = curr ans = max(ans,largest+second_largest+1) # largest path including parent with at most two children return largest+1 # return largest path end at parent dfs(0) return ans ```
https://leetcode.com/problems/longest-path-with-different-adjacent-characters/discuss/2494179/Python-oror-Faster-than-100-oror-Simple-DFS-oror-Easy-Explanation
10
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1. You are also given a string s of length n, where s[i] is the character assigned to node i. Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them. Example 1: Input: parent = [-1,0,0,1,1,2], s = "abacbe" Output: 3 Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned. It can be proven that there is no longer path that satisfies the conditions. Example 2: Input: parent = [-1,0,0,0], s = "aabc" Output: 3 Explanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned. Constraints: n == parent.length == s.length 1 <= n <= 105 0 <= parent[i] <= n - 1 for all i >= 1 parent[0] == -1 parent represents a valid tree. s consists of only lowercase English letters.
Python || Faster than 100% || Simple DFS || Easy Explanation
359
longest-path-with-different-adjacent-characters
0.453
Laxman_Singh_Saini
Hard
31,094
2,246
intersection of multiple arrays
class Solution: def intersection(self, nums: List[List[int]]) -> List[int]: res = set(nums[0]) for i in range(1, len(nums)): res &amp;= set(nums[i]) res = list(res) res.sort() return res
https://leetcode.com/problems/intersection-of-multiple-arrays/discuss/2428232/94.58-faster-using-set-and-and-operator-in-Python
6
Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order. Example 1: Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]] Output: [3,4] Explanation: The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4]. Example 2: Input: nums = [[1,2,3],[4,5,6]] Output: [] Explanation: There does not exist any integer present both in nums[0] and nums[1], so we return an empty list []. Constraints: 1 <= nums.length <= 1000 1 <= sum(nums[i].length) <= 1000 1 <= nums[i][j] <= 1000 All the values of nums[i] are unique.
94.58% faster using set and & operator in Python
172
intersection-of-multiple-arrays
0.695
ankurbhambri
Easy
31,101
2,248
count lattice points inside a circle
class Solution: def countLatticePoints(self, circles: List[List[int]]) -> int: points = set() for x, y, r in circles: for dx in range(-r, r + 1, 1): temp = math.floor(math.sqrt(r ** 2 - dx ** 2)) for dy in range(-temp, temp + 1): points.add((x + dx, y + dy)) return len(points)
https://leetcode.com/problems/count-lattice-points-inside-a-circle/discuss/1977094/Python-Math-(Geometry)-and-Set-Solution-No-Brute-Force
1
Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi) and radius ri of the ith circle drawn on a grid, return the number of lattice points that are present inside at least one circle. Note: A lattice point is a point with integer coordinates. Points that lie on the circumference of a circle are also considered to be inside it. Example 1: Input: circles = [[2,2,1]] Output: 5 Explanation: The figure above shows the given circle. The lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green. Other points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle. Hence, the number of lattice points present inside at least one circle is 5. Example 2: Input: circles = [[2,2,2],[3,4,1]] Output: 16 Explanation: The figure above shows the given circles. There are exactly 16 lattice points which are present inside at least one circle. Some of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4). Constraints: 1 <= circles.length <= 200 circles[i].length == 3 1 <= xi, yi <= 100 1 <= ri <= min(xi, yi)
[Python] Math (Geometry) and Set Solution, No Brute Force
60
count-lattice-points-inside-a-circle
0.503
xil899
Medium
31,147
2,249
count number of rectangles containing each point
class Solution: def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]: mp = defaultdict(list) for l, h in rectangles: mp[h].append(l) for v in mp.values(): v.sort() ans = [] for x, y in points: cnt = 0 for yy in range(y, 101): if yy in mp: cnt += len(mp[yy]) - bisect_left(mp[yy], x) ans.append(cnt) return ans
https://leetcode.com/problems/count-number-of-rectangles-containing-each-point/discuss/1980349/Python3-binary-search
3
You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj). The ith rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (li, hi). Return an integer array count of length points.length where count[j] is the number of rectangles that contain the jth point. The ith rectangle contains the jth point if 0 <= xj <= li and 0 <= yj <= hi. Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle. Example 1: Input: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]] Output: [2,1] Explanation: The first rectangle contains no points. The second rectangle contains only the point (2, 1). The third rectangle contains the points (2, 1) and (1, 4). The number of rectangles that contain the point (2, 1) is 2. The number of rectangles that contain the point (1, 4) is 1. Therefore, we return [2, 1]. Example 2: Input: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]] Output: [1,3] Explanation: The first rectangle contains only the point (1, 1). The second rectangle contains only the point (1, 1). The third rectangle contains the points (1, 3) and (1, 1). The number of rectangles that contain the point (1, 3) is 1. The number of rectangles that contain the point (1, 1) is 3. Therefore, we return [1, 3]. Constraints: 1 <= rectangles.length, points.length <= 5 * 104 rectangles[i].length == points[j].length == 2 1 <= li, xj <= 109 1 <= hi, yj <= 100 All the rectangles are unique. All the points are unique.
[Python3] binary search
55
count-number-of-rectangles-containing-each-point
0.341
ye15
Medium
31,154
2,250
number of flowers in full bloom
class Solution: def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: start, end, res = [], [], [] for i in flowers: start.append(i[0]) end.append(i[1]) start.sort() #bisect only works with sorted data end.sort() for p in persons: num = bisect_right(start, p) - bisect_left(end, p) res.append(num) return res #bisect_right(start, p) gives you the number of flowers that are in full bloom at person p. #bisect_left(end, p) gives you number of flowers that are not in full bloom at person p. #we have to tighten our bound to get exact number of flowers that are in bloom or not, thats why we are using right and left of bisect module.
https://leetcode.com/problems/number-of-flowers-in-full-bloom/discuss/2757459/Binary-Search-with-Explanation-Fast-and-Easy-Solution
0
You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where people[i] is the time that the ith person will arrive to see the flowers. Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives. Example 1: Input: flowers = [[1,6],[3,7],[9,12],[4,13]], people = [2,3,7,11] Output: [1,2,2,2] Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. For each person, we return the number of flowers in full bloom during their arrival. Example 2: Input: flowers = [[1,10],[3,3]], people = [3,3,2] Output: [2,2,1] Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. For each person, we return the number of flowers in full bloom during their arrival. Constraints: 1 <= flowers.length <= 5 * 104 flowers[i].length == 2 1 <= starti <= endi <= 109 1 <= people.length <= 5 * 104 1 <= people[i] <= 109
Binary Search with Explanation - Fast and Easy Solution
2
number-of-flowers-in-full-bloom
0.519
user6770yv
Hard
31,158
2,251
count prefixes of a given string
class Solution: def countPrefixes(self, words: List[str], s: str) -> int: count=0 for i in words: if (s[:len(i)]==i): count+=1 return count
https://leetcode.com/problems/count-prefixes-of-a-given-string/discuss/2076295/Easy-python-solution
9
You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters. Return the number of strings in words that are a prefix of s. A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string. Example 1: Input: words = ["a","b","c","ab","bc","abc"], s = "abc" Output: 3 Explanation: The strings in words which are a prefix of s = "abc" are: "a", "ab", and "abc". Thus the number of strings in words which are a prefix of s is 3. Example 2: Input: words = ["a","a"], s = "aa" Output: 2 Explanation: Both of the strings are a prefix of s. Note that the same string can occur multiple times in words, and it should be counted each time. Constraints: 1 <= words.length <= 1000 1 <= words[i].length, s.length <= 10 words[i] and s consist of lowercase English letters only.
Easy python solution
336
count-prefixes-of-a-given-string
0.734
tusharkhanna575
Easy
31,166
2,255
minimum average difference
class Solution: def minimumAverageDifference(self, a: List[int]) -> int: l=0 r=sum(a) z=100001 y=0 n=len(a) for i in range(n-1): l+=a[i] r-=a[i] d=abs((l//(i+1))-(r//(n-i-1))) if d<z: z=d y=i if sum(a)//n<z: y=n-1 return y
https://leetcode.com/problems/minimum-average-difference/discuss/2098497/PYTHON-oror-EASY-oror-BEGINER-FRIENDLY
1
You are given a 0-indexed integer array nums of length n. The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer. Return the index with the minimum average difference. If there are multiple such indices, return the smallest one. Note: The absolute difference of two numbers is the absolute value of their difference. The average of n elements is the sum of the n elements divided (integer division) by n. The average of 0 elements is considered to be 0. Example 1: Input: nums = [2,5,3,9,5,3] Output: 3 Explanation: - The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3. - The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2. - The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2. - The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0. - The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1. - The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4. The average difference of index 3 is the minimum average difference so return 3. Example 2: Input: nums = [0] Output: 0 Explanation: The only index is 0 so return 0. The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0. Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 105
✔️PYTHON || EASY || ✔️ BEGINER FRIENDLY
75
minimum-average-difference
0.359
karan_8082
Medium
31,199
2,256
count unguarded cells in the grid
class Solution: def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int: vis = [[0]*n for _ in range(m)] # i - rows, j - colums # sum(row.count('hit') for row in grid) for i,j in walls: vis[i][j] = 2 for i,j in guards: vis[i][j] = 2 for i,j in guards: for l in range(j-1,-1,-1): if self.checkWall(i,l,vis): break vis[i][l] = 1 for r in range(j+1,n): if self.checkWall(i,r,vis): break vis[i][r] = 1 for u in range(i-1,-1,-1): if self.checkWall(u,j,vis): break vis[u][j] = 1 for d in range(i+1,m): if self.checkWall(d,j, vis): break vis[d][j] = 1 return sum(row.count(0) for row in vis) def checkWall(self, i, j, vis): if vis[i][j] ==2: return True
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/1994806/Simple-python-code
1
You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively. A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded. Example 1: Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]] Output: 7 Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram. There are a total of 7 unguarded cells, so we return 7. Example 2: Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]] Output: 4 Explanation: The unguarded cells are shown in green in the above diagram. There are a total of 4 unguarded cells, so we return 4. Constraints: 1 <= m, n <= 105 2 <= m * n <= 105 1 <= guards.length, walls.length <= 5 * 104 2 <= guards.length + walls.length <= m * n guards[i].length == walls[j].length == 2 0 <= rowi, rowj < m 0 <= coli, colj < n All the positions in guards and walls are unique.
Simple python code
37
count-unguarded-cells-in-the-grid
0.522
beast316
Medium
31,211
2,257
escape the spreading fire
class Solution: def maximumMinutes(self, grid: List[List[int]]) -> int: #region growing to assign each grass with the time that it will catch fire m, n = len(grid), len(grid[0]) start = [] for i in range(m): for j in range(n): if grid[i][j] == 1: start.append([i,j]) grid[i][j] = 'F' elif grid[i][j] == 2: grid[i][j] = 'W' visited = set() for element in start: visited.add(tuple(element)) time = 1 while start: new_start = [] for x, y in start: if x >= 1: if grid[x-1][y] == 0 and (x-1, y) not in visited: new_start.append([x-1, y]) visited.add((x-1, y)) grid[x-1][y] = time if x < m-1: if grid[x+1][y] == 0 and (x+1, y) not in visited: new_start.append([x+1, y]) visited.add((x+1, y)) grid[x+1][y] = time if y >= 1: if grid[x][y-1] == 0 and (x, y-1) not in visited: new_start.append([x, y-1]) visited.add((x, y-1)) grid[x][y-1] = time if y < n-1: if grid[x][y+1] == 0 and (x, y+1) not in visited: new_start.append([x, y+1]) visited.add((x, y+1)) grid[x][y+1] = time time += 1 start = new_start #memo variable will save time from search path that is already proved to be impossible memo = {} def search(x, y, time, visited): if (x,y) in memo and time >= memo[(x,y)]: return False if time > grid[-1][-1]: return False if x == m-1 and y == n-1: if grid[x][y] == 0: return True else: if grid[x][y] >= time: return True else: if grid[x][y] == time: return False visited.add((x,y)) if x >= 1: if grid[x-1][y] != 'W' and grid[x-1][y] != 'F' and grid[x-1][y] > time and (x-1, y) not in visited: res = search(x-1, y, time+1, visited) if res: return True if x < m-1: if grid[x+1][y] != 'W' and grid[x+1][y] != 'F' and grid[x+1][y] > time and (x+1, y) not in visited: res = search(x+1, y, time+1, visited) if res: return True if y >= 1: if grid[x][y-1] != 'W' and grid[x][y-1] != 'F' and grid[x][y-1] > time and (x, y-1) not in visited: res = search(x, y-1, time+1, visited) if res: return True if y < n-1: if grid[x][y+1] != 'W' and grid[x][y+1] != 'F' and grid[x][y+1] > time and (x, y+1) not in visited: res = search(x, y+1, time+1, visited) if res: return True visited.remove((x,y)) if (x,y) not in memo: memo[(x,y)] = time else: memo[(x,y)] = min(time, memo[(x,y)]) return False if grid[0][0] == 0: if search(0, 0, -sys.maxsize, set()): return 10**9 else: return -1 else: start, end = 0, grid[0][0]-1 #binary search while start < end: mid = ceil((start + end)/2) if search(0, 0, mid, set()): start = mid else: end = mid - 1 if start != 0: return start else: if search(0, 0, 0, set()): return 0 else: return -1
https://leetcode.com/problems/escape-the-spreading-fire/discuss/2005513/Python3-BFS-%2B-DFS-%2B-Binary-Search-Solution
0
You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values: 0 represents grass, 1 represents fire, 2 represents a wall that you and fire cannot pass through. You are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls. Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1. If you can always reach the safehouse regardless of the minutes stayed, return 109. Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Example 1: Input: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]] Output: 3 Explanation: The figure above shows the scenario where you stay in the initial position for 3 minutes. You will still be able to safely reach the safehouse. Staying for more than 3 minutes will not allow you to safely reach the safehouse. Example 2: Input: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]] Output: -1 Explanation: The figure above shows the scenario where you immediately move towards the safehouse. Fire will spread to any cell you move towards and it is impossible to safely reach the safehouse. Thus, -1 is returned. Example 3: Input: grid = [[0,0,0],[2,2,0],[1,2,0]] Output: 1000000000 Explanation: The figure above shows the initial grid. Notice that the fire is contained by walls and you will always be able to safely reach the safehouse. Thus, 109 is returned. Constraints: m == grid.length n == grid[i].length 2 <= m, n <= 300 4 <= m * n <= 2 * 104 grid[i][j] is either 0, 1, or 2. grid[0][0] == grid[m - 1][n - 1] == 0
Python3 BFS + DFS + Binary Search Solution
44
escape-the-spreading-fire
0.347
xxHRxx
Hard
31,221
2,258
remove digit from number to maximize result
class Solution: def removeDigit(self, number: str, digit: str) -> str: # Initializing the last index as zero last_index = 0 #iterating each number to find the occurences, \ # and to find if the number is greater than the next element \ for num in range(1, len(number)): # Handling [case 1] and [case 2] if number[num-1] == digit: if int(number[num]) > int(number[num-1]): return number[:num-1] + number[num:] else: last_index = num - 1 # If digit is the last number (last occurence) in the string [case 3] if number[-1] == digit: last_index = len(number) - 1 return number[:last_index] + number[last_index + 1:]
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2074599/Python-O(N)-solution-oror-Faster-than-99-submissions-oror-Detailed-explanation.
16
You are given a string number representing a positive integer and a character digit. Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number. Example 1: Input: number = "123", digit = "3" Output: "12" Explanation: There is only one '3' in "123". After removing '3', the result is "12". Example 2: Input: number = "1231", digit = "1" Output: "231" Explanation: We can remove the first '1' to get "231" or remove the second '1' to get "123". Since 231 > 123, we return "231". Example 3: Input: number = "551", digit = "5" Output: "51" Explanation: We can remove either the first or second '5' from "551". Both result in the string "51". Constraints: 2 <= number.length <= 100 number consists of digits from '1' to '9'. digit is a digit from '1' to '9'. digit occurs at least once in number.
🔥🔥🔥Python O(N) solution || Faster than 99% submissions || Detailed explanation.
1,400
remove-digit-from-number-to-maximize-result
0.47
litdatascience
Easy
31,224
2,259
minimum consecutive cards to pick up
class Solution: def minimumCardPickup(self, cards: List[int]) -> int: minPick = float('inf') seen = {} for i, n in enumerate(cards): if n in seen: if i - seen[n] + 1 < minPick: minPick = i - seen[n] + 1 seen[n] = i if minPick == float('inf'): return -1 return minPick
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996393/Python3-or-Beginner-friendly-explained-or
22
You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value. Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1. Example 1: Input: cards = [3,4,2,3,4,7] Output: 4 Explanation: We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal. Example 2: Input: cards = [1,0,5,3] Output: -1 Explanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards. Constraints: 1 <= cards.length <= 105 0 <= cards[i] <= 106
Python3 | Beginner-friendly explained |
919
minimum-consecutive-cards-to-pick-up
0.517
hanjo108
Medium
31,251
2,260
k divisible elements subarrays
class Solution: def countDistinct(self, nums: List[int], k: int, p: int) -> int: n = len(nums) sub_arrays = set() # generate all combinations of subarray for start in range(n): cnt = 0 temp = '' for i in range(start, n): if nums[i]%p == 0: cnt+=1 temp+=str(nums[i]) + ',' # build the sequence subarray in CSV format if cnt>k: # check for termination break sub_arrays.add(temp) return len(sub_arrays)
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/1996643/Python-Simple-Count-all-combinations
20
Given an integer array nums and two integers k and p, return the number of distinct subarrays, which have at most k elements that are divisible by p. Two arrays nums1 and nums2 are said to be distinct if: They are of different lengths, or There exists at least one index i where nums1[i] != nums2[i]. A subarray is defined as a non-empty contiguous sequence of elements in an array. Example 1: Input: nums = [2,3,3,2,2], k = 2, p = 2 Output: 11 Explanation: The elements at indices 0, 3, and 4 are divisible by p = 2. The 11 distinct subarrays which have at most k = 2 elements divisible by 2 are: [2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2]. Note that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once. The subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2. Example 2: Input: nums = [1,2,3,4], k = 4, p = 1 Output: 10 Explanation: All element of nums are divisible by p = 1. Also, every subarray of nums will have at most 4 elements that are divisible by 1. Since all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10. Constraints: 1 <= nums.length <= 200 1 <= nums[i], p <= 200 1 <= k <= nums.length Follow up: Can you solve this problem in O(n2) time complexity?
✅ Python - Simple Count all combinations
885
k-divisible-elements-subarrays
0.476
constantine786
Medium
31,275
2,261
total appeal of a string
class Solution: def appealSum(self, s: str) -> int: res, cur, prev = 0, 0, defaultdict(lambda: -1) for i, ch in enumerate(s): cur += i - prev[ch] prev[ch] = i res += cur return res
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1996203/DP
245
The appeal of a string is the number of distinct characters found in the string. For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'. Given a string s, return the total appeal of all of its substrings. A substring is a contiguous sequence of characters within a string. Example 1: Input: s = "abbca" Output: 28 Explanation: The following are the substrings of "abbca": - Substrings of length 1: "a", "b", "b", "c", "a" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5. - Substrings of length 2: "ab", "bb", "bc", "ca" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7. - Substrings of length 3: "abb", "bbc", "bca" have an appeal of 2, 2, and 3 respectively. The sum is 7. - Substrings of length 4: "abbc", "bbca" have an appeal of 3 and 3 respectively. The sum is 6. - Substrings of length 5: "abbca" has an appeal of 3. The sum is 3. The total sum is 5 + 7 + 7 + 6 + 3 = 28. Example 2: Input: s = "code" Output: 20 Explanation: The following are the substrings of "code": - Substrings of length 1: "c", "o", "d", "e" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4. - Substrings of length 2: "co", "od", "de" have an appeal of 2, 2, and 2 respectively. The sum is 6. - Substrings of length 3: "cod", "ode" have an appeal of 3 and 3 respectively. The sum is 6. - Substrings of length 4: "code" has an appeal of 4. The sum is 4. The total sum is 4 + 6 + 6 + 4 = 20. Constraints: 1 <= s.length <= 105 s consists of lowercase English letters.
DP
10,100
total-appeal-of-a-string
0.583
votrubac
Hard
31,287
2,262
largest 3 same digit number in string
class Solution: def largestGoodInteger(self, n: str) -> str: return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else "" for i in range(2, len(n)))
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2017786/Compare-with-2-previous
51
You are given a string num representing a large integer. An integer is good if it meets the following conditions: It is a substring of num with length 3. It consists of only one unique digit. Return the maximum good integer as a string or an empty string "" if no such integer exists. Note: A substring is a contiguous sequence of characters within a string. There may be leading zeroes in num or a good integer. Example 1: Input: num = "6777133339" Output: "777" Explanation: There are two distinct good integers: "777" and "333". "777" is the largest, so we return "777". Example 2: Input: num = "2300019" Output: "000" Explanation: "000" is the only good integer. Example 3: Input: num = "42352338" Output: "" Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers. Constraints: 3 <= num.length <= 1000 num only consists of digits.
Compare with 2 previous
2,300
largest-3-same-digit-number-in-string
0.59
votrubac
Easy
31,303
2,264
count nodes equal to average of subtree
class Solution: def averageOfSubtree(self, root: Optional[TreeNode]) -> int: def fn(node): nonlocal ans if not node: return 0, 0 ls, ln = fn(node.left) rs, rn = fn(node.right) s = node.val + ls + rs n = 1 + ln + rn if s//n == node.val: ans += 1 return s, n ans = 0 fn(root) return ans
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2017794/Python3-post-order-dfs
6
Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree. Note: The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer. A subtree of root is a tree consisting of root and all of its descendants. Example 1: Input: root = [4,8,5,0,1,null,6] Output: 5 Explanation: For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4. For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5. For the node with value 0: The average of its subtree is 0 / 1 = 0. For the node with value 1: The average of its subtree is 1 / 1 = 1. For the node with value 6: The average of its subtree is 6 / 1 = 6. Example 2: Input: root = [1] Output: 1 Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1. Constraints: The number of nodes in the tree is in the range [1, 1000]. 0 <= Node.val <= 1000
[Python3] post-order dfs
266
count-nodes-equal-to-average-of-subtree
0.856
ye15
Medium
31,327
2,265
count number of texts
class Solution: def countTexts(self, pressedKeys: str) -> int: MOD = 1_000_000_007 @cache def fn(n, k): """Return number of possible text of n repeated k times.""" if n < 0: return 0 if n == 0: return 1 ans = 0 for x in range(1, k+1): ans = (ans + fn(n-x, k)) % MOD return ans ans = 1 for key, grp in groupby(pressedKeys): if key in "79": k = 4 else: k = 3 ans = (ans * fn(len(list(grp)), k)) % MOD return ans
https://leetcode.com/problems/count-number-of-texts/discuss/2017834/Python3-group-by-group
8
Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. For example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice. Note that the digits '0' and '1' do not map to any letters, so Alice does not use them. However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead. For example, when Alice sent the message "bob", Bob received the string "2266622". Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent. Since the answer may be very large, return it modulo 109 + 7. Example 1: Input: pressedKeys = "22233" Output: 8 Explanation: The possible text messages Alice could have sent are: "aaadd", "abdd", "badd", "cdd", "aaae", "abe", "bae", and "ce". Since there are 8 possible messages, we return 8. Example 2: Input: pressedKeys = "222222222222222222222222222222222222" Output: 82876089 Explanation: There are 2082876103 possible text messages Alice could have sent. Since we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089. Constraints: 1 <= pressedKeys.length <= 105 pressedKeys only consists of digits from '2' - '9'.
[Python3] group-by-group
371
count-number-of-texts
0.473
ye15
Medium
31,339
2,266
check if there is a valid parentheses string path
class Solution: def hasValidPath(self, grid: List[List[str]]) -> bool: m = len(grid) n = len(grid[0]) @lru_cache(maxsize=None) def hasValidPathInner(x, y, cnt): # cnt variable would act as a counter to track # the balance of parantheses sequence if x == m or y == n or cnt < 0: return False # logic to check the balance of sequence cnt += 1 if grid[x][y] == '(' else -1 # if balanced and end of grid, return True if x == m - 1 and y == n - 1 and not cnt: return True return hasValidPathInner(x + 1, y, cnt) or hasValidPathInner(x, y + 1, cnt) return hasValidPathInner(0, 0, 0)
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2018005/Python-Simple-MemoisationCaching
13
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given an m x n matrix of parentheses grid. A valid parentheses string path in the grid is a path satisfying all of the following conditions: The path starts from the upper left cell (0, 0). The path ends at the bottom-right cell (m - 1, n - 1). The path only ever moves down or right. The resulting parentheses string formed by the path is valid. Return true if there exists a valid parentheses string path in the grid. Otherwise, return false. Example 1: Input: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]] Output: true Explanation: The above diagram shows two possible paths that form valid parentheses strings. The first path shown results in the valid parentheses string "()(())". The second path shown results in the valid parentheses string "((()))". Note that there may be other valid parentheses string paths. Example 2: Input: grid = [[")",")"],["(","("]] Output: false Explanation: The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100 grid[i][j] is either '(' or ')'.
✅ Python Simple Memoisation/Caching
405
check-if-there-is-a-valid-parentheses-string-path
0.38
constantine786
Hard
31,346
2,267
find the k beauty of a number
class Solution: """ Time: O(log10(n)*k) Memory: O(log10(n)) """ def divisorSubstrings(self, num: int, k: int) -> int: str_num = str(num) return sum( num % int(str_num[i - k:i]) == 0 for i in range(k, len(str_num) + 1) if int(str_num[i - k:i]) != 0 )
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2611592/Python-Elegant-and-Short-or-Sliding-window-or-O(log10(n))-time-or-O(1)-memory
3
The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions: It has a length of k. It is a divisor of num. Given integers num and k, return the k-beauty of num. Note: Leading zeros are allowed. 0 is not a divisor of any value. A substring is a contiguous sequence of characters in a string. Example 1: Input: num = 240, k = 2 Output: 2 Explanation: The following are the substrings of num of length k: - "24" from "240": 24 is a divisor of 240. - "40" from "240": 40 is a divisor of 240. Therefore, the k-beauty is 2. Example 2: Input: num = 430043, k = 2 Output: 2 Explanation: The following are the substrings of num of length k: - "43" from "430043": 43 is a divisor of 430043. - "30" from "430043": 30 is not a divisor of 430043. - "00" from "430043": 0 is not a divisor of 430043. - "04" from "430043": 4 is not a divisor of 430043. - "43" from "430043": 43 is a divisor of 430043. Therefore, the k-beauty is 2. Constraints: 1 <= num <= 109 1 <= k <= num.length (taking num as a string)
Python Elegant & Short | Sliding window | O(log10(n)) time | O(1) memory
211
find-the-k-beauty-of-a-number
0.567
Kyrylo-Ktl
Easy
31,355
2,269
number of ways to split array
class Solution: def waysToSplitArray(self, n: List[int]) -> int: n = list(accumulate(n)) return sum(n[i] >= n[-1] - n[i] for i in range(len(n) - 1))
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2038567/Prefix-Sum
14
You are given a 0-indexed integer array nums of length n. nums contains a valid split at index i if the following are true: The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements. There is at least one element to the right of i. That is, 0 <= i < n - 1. Return the number of valid splits in nums. Example 1: Input: nums = [10,4,-8,7] Output: 2 Explanation: There are three ways of splitting nums into two non-empty parts: - Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split. - Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split. - Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split. Thus, the number of valid splits in nums is 2. Example 2: Input: nums = [2,3,1,0] Output: 2 Explanation: There are two valid splits in nums: - Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. - Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split. Constraints: 2 <= nums.length <= 105 -105 <= nums[i] <= 105
Prefix Sum
1,100
number-of-ways-to-split-array
0.446
votrubac
Medium
31,385
2,270
maximum white tiles covered by a carpet
class Solution: def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int: tiles.sort() ans = ii = val = 0 for i in range(len(tiles)): hi = tiles[i][0] + carpetLen - 1 while ii < len(tiles) and tiles[ii][1] <= hi: val += tiles[ii][1] - tiles[ii][0] + 1 ii += 1 partial = 0 if ii < len(tiles): partial = max(0, hi - tiles[ii][0] + 1) ans = max(ans, val + partial) val -= tiles[i][1] - tiles[i][0] + 1 return ans
https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/discuss/2148636/Python3-greedy
1
You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li <= j <= ri is colored white. You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere. Return the maximum number of white tiles that can be covered by the carpet. Example 1: Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10 Output: 9 Explanation: Place the carpet starting on tile 10. It covers 9 white tiles, so we return 9. Note that there may be other places where the carpet covers 9 white tiles. It can be shown that the carpet cannot cover more than 9 white tiles. Example 2: Input: tiles = [[10,11],[1,1]], carpetLen = 2 Output: 2 Explanation: Place the carpet starting on tile 10. It covers 2 white tiles, so we return 2. Constraints: 1 <= tiles.length <= 5 * 104 tiles[i].length == 2 1 <= li <= ri <= 109 1 <= carpetLen <= 109 The tiles are non-overlapping.
[Python3] greedy
105
maximum-white-tiles-covered-by-a-carpet
0.327
ye15
Medium
31,402
2,271
substring with largest variance
class Solution: def largestVariance(self, s: str) -> int: ans = 0 seen = set(s) for x in ascii_lowercase: for y in ascii_lowercase: if x != y and x in seen and y in seen: vals = [] for ch in s: if ch == x: vals.append(1) elif ch == y: vals.append(-1) cand = prefix = least = 0 ii = -1 for i, v in enumerate(vals): prefix += v if prefix < least: least = prefix ii = i ans = max(ans, min(prefix-least, i-ii-1)) return ans
https://leetcode.com/problems/substring-with-largest-variance/discuss/2148640/Python3-pairwise-prefix-sum
3
The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same. Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s. A substring is a contiguous sequence of characters within a string. Example 1: Input: s = "aababbb" Output: 3 Explanation: All possible variances along with their respective substrings are listed below: - Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb". - Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab". - Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb". - Variance 3 for substring "babbb". Since the largest possible variance is 3, we return it. Example 2: Input: s = "abcde" Output: 0 Explanation: No letter occurs more than once in s, so the variance of every substring is 0. Constraints: 1 <= s.length <= 104 s consists of lowercase English letters.
[Python3] pairwise prefix sum
620
substring-with-largest-variance
0.374
ye15
Hard
31,410
2,272
find resultant array after removing anagrams
class Solution: def removeAnagrams(self, w: List[str]) -> List[str]: return [next(g) for _, g in groupby(w, sorted)]
https://leetcode.com/problems/find-resultant-array-after-removing-anagrams/discuss/2039752/Weird-Description
39
You are given a 0-indexed string array words, where words[i] consists of lowercase English letters. In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions. Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc". Example 1: Input: words = ["abba","baba","bbaa","cd","cd"] Output: ["abba","cd"] Explanation: One of the ways we can obtain the resultant array is by using the following operations: - Since words[2] = "bbaa" and words[1] = "baba" are anagrams, we choose index 2 and delete words[2]. Now words = ["abba","baba","cd","cd"]. - Since words[1] = "baba" and words[0] = "abba" are anagrams, we choose index 1 and delete words[1]. Now words = ["abba","cd","cd"]. - Since words[2] = "cd" and words[1] = "cd" are anagrams, we choose index 2 and delete words[2]. Now words = ["abba","cd"]. We can no longer perform any operations, so ["abba","cd"] is the final answer. Example 2: Input: words = ["a","b","c","d","e"] Output: ["a","b","c","d","e"] Explanation: No two adjacent strings in words are anagrams of each other, so no operations are performed. Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 10 words[i] consists of lowercase English letters.
Weird Description
2,900
find-resultant-array-after-removing-anagrams
0.583
votrubac
Easy
31,414
2,273
maximum consecutive floors without special floors
class Solution: def maxConsecutive(self, bottom: int, top: int, special: list[int]) -> int: special.sort() res = special[0] - bottom for i in range(1, len(special)): res = max(res, special[i] - special[i - 1] - 1) return max(res, top - special[-1])
https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/discuss/2039754/Python-Simulation-Just-sort-the-array-special
7
Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only. You are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given the integer array special, where special[i] denotes a special floor that Alice has designated for relaxation. Return the maximum number of consecutive floors without a special floor. Example 1: Input: bottom = 2, top = 9, special = [4,6] Output: 3 Explanation: The following are the ranges (inclusive) of consecutive floors without a special floor: - (2, 3) with a total amount of 2 floors. - (5, 5) with a total amount of 1 floor. - (7, 9) with a total amount of 3 floors. Therefore, we return the maximum number which is 3 floors. Example 2: Input: bottom = 6, top = 8, special = [7,6,8] Output: 0 Explanation: Every floor rented is a special floor, so we return 0. Constraints: 1 <= special.length <= 105 1 <= bottom <= special[i] <= top <= 109 All the values of special are unique.
Python Simulation - Just sort the array special
326
maximum-consecutive-floors-without-special-floors
0.521
GigaMoksh
Medium
31,445
2,274
largest combination with bitwise and greater than zero
class Solution: def largestCombination(self, candidates: List[int]) -> int: return max(sum(n &amp; (1 << i) > 0 for n in candidates) for i in range(0, 24))
https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/discuss/2039717/Check-Each-Bit
55
The bitwise AND of an array nums is the bitwise AND of all integers in nums. For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1. Also, for nums = [7], the bitwise AND is 7. You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination. Return the size of the largest combination of candidates with a bitwise AND greater than 0. Example 1: Input: candidates = [16,17,71,62,12,24,14] Output: 4 Explanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0. The size of the combination is 4. It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0. Note that more than one combination may have the largest size. For example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0. Example 2: Input: candidates = [8,8] Output: 2 Explanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0. The size of the combination is 2, so we return 2. Constraints: 1 <= candidates.length <= 105 1 <= candidates[i] <= 107
Check Each Bit
3,600
largest-combination-with-bitwise-and-greater-than-zero
0.724
votrubac
Medium
31,457
2,275
percentage of letter in string
class Solution: def percentageLetter(self, s: str, letter: str) -> int: a = s.count(letter) return (a*100)//len(s)
https://leetcode.com/problems/percentage-of-letter-in-string/discuss/2061930/Simple-Python-Solution-or-Easy-to-Understand-or-Two-Liner-Solution-or-O(N)-Solution
2
Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent. Example 1: Input: s = "foobar", letter = "o" Output: 33 Explanation: The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33. Example 2: Input: s = "jjjj", letter = "k" Output: 0 Explanation: The percentage of characters in s that equal the letter 'k' is 0%, so we return 0. Constraints: 1 <= s.length <= 100 s consists of lowercase English letters. letter is a lowercase English letter.
Simple Python Solution | Easy to Understand | Two Liner Solution | O(N) Solution
63
percentage-of-letter-in-string
0.741
AkashHooda
Easy
31,468
2,278
maximum bags with full capacity of rocks
class Solution: def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int: remaining = [0] * len(capacity) res = 0 for i in range(len(capacity)): remaining[i] = capacity[i] - rocks[i] remaining.sort() for i in range(len(remaining)): if remaining[i] > additionalRocks: break additionalRocks -= remaining[i] res += 1 return res
https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/discuss/2062186/Python-Easy-Solution
1
You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags. Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags. Example 1: Input: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2 Output: 3 Explanation: Place 1 rock in bag 0 and 1 rock in bag 1. The number of rocks in each bag are now [2,3,4,4]. Bags 0, 1, and 2 have full capacity. There are 3 bags at full capacity, so we return 3. It can be shown that it is not possible to have more than 3 bags at full capacity. Note that there may be other ways of placing the rocks that result in an answer of 3. Example 2: Input: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100 Output: 3 Explanation: Place 8 rocks in bag 0 and 2 rocks in bag 2. The number of rocks in each bag are now [10,2,2]. Bags 0, 1, and 2 have full capacity. There are 3 bags at full capacity, so we return 3. It can be shown that it is not possible to have more than 3 bags at full capacity. Note that we did not use all of the additional rocks. Constraints: n == capacity.length == rocks.length 1 <= n <= 5 * 104 1 <= capacity[i] <= 109 0 <= rocks[i] <= capacity[i] 1 <= additionalRocks <= 109
Python Easy Solution
28
maximum-bags-with-full-capacity-of-rocks
0.626
MiKueen
Medium
31,492
2,279
minimum lines to represent a line chart
class Solution: def minimumLines(self, stockPrices: List[List[int]]) -> int: # key point: never use devision to judge whether 3 points are on a same line or not, use the multiplication instead !! n = len(stockPrices) stockPrices.sort(key = lambda x: (x[0], x[1])) if n == 1: return 0 pre_delta_y = stockPrices[0][1] - stockPrices[1][1] pre_delta_x = stockPrices[0][0] - stockPrices[1][0] num = 1 for i in range(1, n-1): cur_delta_y = stockPrices[i][1] - stockPrices[i+1][1] cur_delta_x = stockPrices[i][0] - stockPrices[i+1][0] if pre_delta_y * cur_delta_x != pre_delta_x * cur_delta_y: num += 1 pre_delta_x = cur_delta_x pre_delta_y = cur_delta_y return num
https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart/discuss/2061893/Python-or-Easy-to-Understand
11
You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below: Return the minimum number of lines needed to represent the line chart. Example 1: Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]] Output: 3 Explanation: The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price. The following 3 lines can be drawn to represent the line chart: - Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4). - Line 2 (in blue) from (4,4) to (5,4). - Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1). It can be shown that it is not possible to represent the line chart using less than 3 lines. Example 2: Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]] Output: 1 Explanation: As shown in the diagram above, the line chart can be represented with a single line. Constraints: 1 <= stockPrices.length <= 105 stockPrices[i].length == 2 1 <= dayi, pricei <= 109 All dayi are distinct.
Python | Easy to Understand
548
minimum-lines-to-represent-a-line-chart
0.238
Mikey98
Medium
31,507
2,280
sum of total strength of wizards
class Solution: def totalStrength(self, strength: List[int]) -> int: strength = [0] + strength + [0] def calc_prefix_sum(array): if not array: return [] result = [array[0]] for el in array[1:]: result.append(array[-1]+el) return result prefix_sums = calc_prefix_sum(strength) pp_sums = calc_prefix_sum(prefix_sums) stack = [0] total = 0 for right in range(len(strength)): while pp_sums[stack[-1]] > pp_sums[right]: left = stack[-2] i = stack.pop() pos = (i - left) * (pp_sums[right] - pp_sums[i]) neg = (right - i) * (pp_sums[i] - pp_sums[left]) total += pp_sums[i] * (pos - neg) stack.push(right) return total % (10**9+7) def totalStrength(self, strength): res, S, A = 0, [0], [0] + strength + [0] # O(N) P = list(itertools.accumulate(itertools.accumulate(A), initial=0)) # O(N) for r in range(len(A)): # O(N) while A[S[-1]] > A[r]: # O(1) amortized l, i = S[-2], S.pop() res += A[i] * ((i - l) * (P[r] - P[i]) - (r - i) * (P[i] - P[l])) S.append(r) return res % (10 ** 9 + 7)
https://leetcode.com/problems/sum-of-total-strength-of-wizards/discuss/2373525/faster-than-98.90-or-easy-python-or-solution
2
As the ruler of a kingdom, you have an army of wizards at your command. You are given a 0-indexed integer array strength, where strength[i] denotes the strength of the ith wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength), the total strength is defined as the product of the following two values: The strength of the weakest wizard in the group. The total of all the individual strengths of the wizards in the group. Return the sum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 109 + 7. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: strength = [1,3,1,2] Output: 44 Explanation: The following are all the contiguous groups of wizards: - [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1 - [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9 - [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1 - [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4 - [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4 - [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4 - [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3 - [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5 - [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6 - [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7 The sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44. Example 2: Input: strength = [5,4,6] Output: 213 Explanation: The following are all the contiguous groups of wizards: - [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25 - [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16 - [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36 - [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36 - [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40 - [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60 The sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213. Constraints: 1 <= strength.length <= 105 1 <= strength[i] <= 109
faster than 98.90% | easy python | solution
1,800
sum-of-total-strength-of-wizards
0.279
vimla_kushwaha
Hard
31,516
2,281
check if number has equal digit count and digit value
class Solution: def digitCount(self, num: str) -> bool: counter=Counter(num) for i in range(len(num)): if counter[f'{i}'] != int(num[i]): return False return True
https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/discuss/2084112/Python-Easy-solution
3
You are given a 0-indexed string num of length n consisting of digits. Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false. Example 1: Input: num = "1210" Output: true Explanation: num[0] = '1'. The digit 0 occurs once in num. num[1] = '2'. The digit 1 occurs twice in num. num[2] = '1'. The digit 2 occurs once in num. num[3] = '0'. The digit 3 occurs zero times in num. The condition holds true for every index in "1210", so return true. Example 2: Input: num = "030" Output: false Explanation: num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num. num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num. num[2] = '0'. The digit 2 occurs zero times in num. The indices 0 and 1 both violate the condition, so return false. Constraints: n == num.length 1 <= n <= 10 num consists of digits.
Python Easy solution
142
check-if-number-has-equal-digit-count-and-digit-value
0.735
constantine786
Easy
31,518
2,283
sender with largest word count
class Solution: def largestWordCount(self, messages: List[str], senders: List[str]) -> str: d={} l=[] for i in range(len(messages)): if senders[i] not in d: d[senders[i]]=len(messages[i].split()) else: d[senders[i]]+=len(messages[i].split()) x=max(d.values()) for k,v in d.items(): if v==x : l.append(k) if len(l)==1: return l[0] else: l=sorted(l)[::-1] #Lexigograhical sorting of list return l[0]
https://leetcode.com/problems/sender-with-largest-word-count/discuss/2084222/Easy-Python-Solution-With-Dictionary
7
You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i]. A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message. Return the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name. Note: Uppercase letters come before lowercase letters in lexicographical order. "Alice" and "alice" are distinct. Example 1: Input: messages = ["Hello userTwooo","Hi userThree","Wonderful day Alice","Nice day userThree"], senders = ["Alice","userTwo","userThree","Alice"] Output: "Alice" Explanation: Alice sends a total of 2 + 3 = 5 words. userTwo sends a total of 2 words. userThree sends a total of 3 words. Since Alice has the largest word count, we return "Alice". Example 2: Input: messages = ["How is leetcode for everyone","Leetcode is useful for practice"], senders = ["Bob","Charlie"] Output: "Charlie" Explanation: Bob sends a total of 5 words. Charlie sends a total of 5 words. Since there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie. Constraints: n == messages.length == senders.length 1 <= n <= 104 1 <= messages[i].length <= 100 1 <= senders[i].length <= 10 messages[i] consists of uppercase and lowercase English letters and ' '. All the words in messages[i] are separated by a single space. messages[i] does not have leading or trailing spaces. senders[i] consists of uppercase and lowercase English letters only.
Easy Python Solution With Dictionary
356
sender-with-largest-word-count
0.561
a_dityamishra
Medium
31,546
2,284
maximum total importance of roads
class Solution: def maximumImportance(self, n: int, roads: List[List[int]]) -> int: Arr = [0] * n # i-th city has Arr[i] roads for A,B in roads: Arr[A] += 1 # Each road increase the road count Arr[B] += 1 Arr.sort() # Cities with most road should receive the most score summ = 0 for i in range(len(Arr)): summ += Arr[i] * (i+1) # Multiply city roads with corresponding score return summ
https://leetcode.com/problems/maximum-total-importance-of-roads/discuss/2083990/Very-simple-Python-solution-O(nlog(n))
14
You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1. You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi. You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects. Return the maximum total importance of all roads possible after assigning the values optimally. Example 1: Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]] Output: 43 Explanation: The figure above shows the country and the assigned values of [2,4,5,3,1]. - The road (0,1) has an importance of 2 + 4 = 6. - The road (1,2) has an importance of 4 + 5 = 9. - The road (2,3) has an importance of 5 + 3 = 8. - The road (0,2) has an importance of 2 + 5 = 7. - The road (1,3) has an importance of 4 + 3 = 7. - The road (2,4) has an importance of 5 + 1 = 6. The total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43. It can be shown that we cannot obtain a greater total importance than 43. Example 2: Input: n = 5, roads = [[0,3],[2,4],[1,3]] Output: 20 Explanation: The figure above shows the country and the assigned values of [4,3,2,5,1]. - The road (0,3) has an importance of 4 + 5 = 9. - The road (2,4) has an importance of 2 + 1 = 3. - The road (1,3) has an importance of 3 + 5 = 8. The total importance of all roads is 9 + 3 + 8 = 20. It can be shown that we cannot obtain a greater total importance than 20. Constraints: 2 <= n <= 5 * 104 1 <= roads.length <= 5 * 104 roads[i].length == 2 0 <= ai, bi <= n - 1 ai != bi There are no duplicate roads.
Very simple Python solution O(nlog(n))
452
maximum-total-importance-of-roads
0.608
Eba472
Medium
31,580
2,285
rearrange characters to make target string
class Solution: def rearrangeCharacters(self, s: str, target: str) -> int: counter_s = Counter(s) return min(counter_s[c] // count for c,count in Counter(target).items())
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2085849/Python-Two-Liner-Beats-~95
14
You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings. Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them. Example 1: Input: s = "ilovecodingonleetcode", target = "code" Output: 2 Explanation: For the first copy of "code", take the letters at indices 4, 5, 6, and 7. For the second copy of "code", take the letters at indices 17, 18, 19, and 20. The strings that are formed are "ecod" and "code" which can both be rearranged into "code". We can make at most two copies of "code", so we return 2. Example 2: Input: s = "abcba", target = "abc" Output: 1 Explanation: We can make one copy of "abc" by taking the letters at indices 0, 1, and 2. We can make at most one copy of "abc", so we return 1. Note that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of "abc". Example 3: Input: s = "abbaccaddaeea", target = "aaaaa" Output: 1 Explanation: We can make one copy of "aaaaa" by taking the letters at indices 0, 3, 6, 9, and 12. We can make at most one copy of "aaaaa", so we return 1. Constraints: 1 <= s.length <= 100 1 <= target.length <= 10 s and target consist of lowercase English letters.
Python Two Liner Beats ~95%
854
rearrange-characters-to-make-target-string
0.578
constantine786
Easy
31,592
2,287
apply discount to prices
class Solution: def discountPrices(self, sentence: str, discount: int) -> str: s = sentence.split() # convert to List to easily update m = discount / 100 for i,word in enumerate(s): if word[0] == "$" and word[1:].isdigit(): # Check whether it is in correct format num = int(word[1:]) * (1-m) # discounted price w = "$" + "{:.2f}".format(num) #correctly format s[i] = w #Change inside the list return " ".join(s) #Combine the updated list ```
https://leetcode.com/problems/apply-discount-to-prices/discuss/2085723/Simple-Python-with-explanation
7
A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign. For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" do not. You are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places. Return a string representing the modified sentence. Note that all prices will contain at most 10 digits. Example 1: Input: sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50 Output: "there are $0.50 $1.00 and 5$ candies in the shop" Explanation: The words which represent prices are "$1" and "$2". - A 50% discount on "$1" yields "$0.50", so "$1" is replaced by "$0.50". - A 50% discount on "$2" yields "$1". Since we need to have exactly 2 decimal places after a price, we replace "$2" with "$1.00". Example 2: Input: sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100 Output: "1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$" Explanation: Applying a 100% discount on any price will result in 0. The words representing prices are "$3", "$5", "$6", and "$9". Each of them is replaced by "$0.00". Constraints: 1 <= sentence.length <= 105 sentence consists of lowercase English letters, digits, ' ', and '$'. sentence does not have leading or trailing spaces. All words in sentence are separated by a single space. All prices will be positive numbers without leading zeros. All prices will have at most 10 digits. 0 <= discount <= 100
Simple Python with explanation
311
apply-discount-to-prices
0.274
Eba472
Medium
31,615
2,288
steps to make array non decreasing
class Solution: def totalSteps(self, nums: List[int]) -> int: n = len(nums) l = [i-1 for i in range(n)] r = [i+1 for i in range(n)] q = [] dist = dict() ans = 0 for i in range(1, n): if nums[i] < nums[i-1]: q.append(i) dist[i] = 1 ans = 1 while len(q) != 0: u = q.pop(0) ans = max(ans, dist[u]) if r[u] < n: l[r[u]] = l[u] if l[u] > -1: r[l[u]] = r[u] if r[u] not in dist and r[u] < n and nums[r[u]] < nums[l[u]]: dist[r[u]] = dist[u] + 1 q.append(r[u]) return ans
https://leetcode.com/problems/steps-to-make-array-non-decreasing/discuss/2567529/BFS-with-updating-neighbours-or-O(n)-or-Python3
0
You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length. Return the number of steps performed until nums becomes a non-decreasing array. Example 1: Input: nums = [5,3,4,4,7,3,6,11,8,5,11] Output: 3 Explanation: The following are the steps performed: - Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11] - Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11] - Step 3: [5,4,7,11,11] becomes [5,7,11,11] [5,7,11,11] is a non-decreasing array. Therefore, we return 3. Example 2: Input: nums = [4,5,7,7,13] Output: 0 Explanation: nums is already a non-decreasing array. Therefore, we return 0. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109
BFS with updating neighbours | O(n) | Python3
67
steps-to-make-array-non-decreasing
0.214
DheerajGadwala
Medium
31,634
2,289
minimum obstacle removal to reach corner
class Solution: def minimumObstacles(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dist = [[inf]*n for _ in range(m)] dist[0][0] = 0 pq = [(0, 0, 0)] while pq: x, i, j = heappop(pq) if i == m-1 and j == n-1: return x 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 x + grid[ii][jj] < dist[ii][jj]: dist[ii][jj] = x + grid[ii][jj] heappush(pq, (dist[ii][jj], ii, jj))
https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/discuss/2313936/Python3-Dijkstra's-algo
1
You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values: 0 represents an empty cell, 1 represents an obstacle that may be removed. You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1). Example 1: Input: grid = [[0,1,1],[1,1,0],[1,1,0]] Output: 2 Explanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2). It can be shown that we need to remove at least 2 obstacles, so we return 2. Note that there may be other ways to remove 2 obstacles to create a path. Example 2: Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]] Output: 0 Explanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0. Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 105 2 <= m * n <= 105 grid[i][j] is either 0 or 1. grid[0][0] == grid[m - 1][n - 1] == 0
[Python3] Dijkstra's algo
32
minimum-obstacle-removal-to-reach-corner
0.487
ye15
Hard
31,637
2,290
min max game
class Solution: def minMaxGame(self, nums: List[int]) -> int: l=nums while len(l)>1: is_min=True tmp=[] for i in range(0, len(l), 2): if is_min: tmp.append(min(l[i:i+2])) else: tmp.append(max(l[i:i+2])) is_min=not is_min l=tmp return l[0]
https://leetcode.com/problems/min-max-game/discuss/2112349/Python-Easy-Approach
8
You are given a 0-indexed integer array nums whose length is a power of 2. Apply the following algorithm on nums: Let n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2. For every even index i where 0 <= i < n / 2, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]). For every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]). Replace the array nums with newNums. Repeat the entire process starting from step 1. Return the last number that remains in nums after applying the algorithm. Example 1: Input: nums = [1,3,5,2,4,8,2,2] Output: 1 Explanation: The following arrays are the results of applying the algorithm repeatedly. First: nums = [1,5,4,2] Second: nums = [1,4] Third: nums = [1] 1 is the last remaining number, so we return 1. Example 2: Input: nums = [3] Output: 3 Explanation: 3 is already the last remaining number, so we return 3. Constraints: 1 <= nums.length <= 1024 1 <= nums[i] <= 109 nums.length is a power of 2.
✅ Python Easy Approach
503
min-max-game
0.643
constantine786
Easy
31,641
2,293
partition array such that maximum difference is k
class Solution: def partitionArray(self, nums: List[int], k: int) -> int: nums.sort() ans = 1 # To keep track of starting element of each subsequence start = nums[0] for i in range(1, len(nums)): diff = nums[i] - start if diff > k: # If difference of starting and current element of subsequence is greater # than K, then only start new subsequence ans += 1 start = nums[i] return ans
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2111923/Python-Easy-Solution-using-Sorting
19
You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: nums = [3,6,1,2,5], k = 2 Output: 2 Explanation: We can partition nums into the two subsequences [3,1,2] and [6,5]. The difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2. The difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1. Since two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed. Example 2: Input: nums = [1,2,3], k = 1 Output: 2 Explanation: We can partition nums into the two subsequences [1,2] and [3]. The difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1. The difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0. Since two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3]. Example 3: Input: nums = [2,2,4,5], k = 0 Output: 3 Explanation: We can partition nums into the three subsequences [2,2], [4], and [5]. The difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0. The difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0. The difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0. Since three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed. Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 105 0 <= k <= 105
Python Easy Solution using Sorting
877
partition-array-such-that-maximum-difference-is-k
0.726
MiKueen
Medium
31,669
2,294
replace elements in an array
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: replacements = {} for x, y in reversed(operations): replacements[x] = replacements.get(y, y) for idx, val in enumerate(nums): if val in replacements: nums[idx] = replacements[val] return nums
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2112285/Python-Simple-Map-Approach
25
You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1]. It is guaranteed that in the ith operation: operations[i][0] exists in nums. operations[i][1] does not exist in nums. Return the array obtained after applying all the operations. Example 1: Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]] Output: [3,2,7,1] Explanation: We perform the following operations on nums: - Replace the number 1 with 3. nums becomes [3,2,4,6]. - Replace the number 4 with 7. nums becomes [3,2,7,6]. - Replace the number 6 with 1. nums becomes [3,2,7,1]. We return the final array [3,2,7,1]. Example 2: Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]] Output: [2,1] Explanation: We perform the following operations to nums: - Replace the number 1 with 3. nums becomes [3,2]. - Replace the number 2 with 1. nums becomes [3,1]. - Replace the number 3 with 2. nums becomes [2,1]. We return the array [2,1]. Constraints: n == nums.length m == operations.length 1 <= n, m <= 105 All the values of nums are distinct. operations[i].length == 2 1 <= nums[i], operations[i][0], operations[i][1] <= 106 operations[i][0] will exist in nums when applying the ith operation. operations[i][1] will not exist in nums when applying the ith operation.
✅ Python Simple Map Approach
1,300
replace-elements-in-an-array
0.576
constantine786
Medium
31,692
2,295
strong password checker ii
class Solution: def strongPasswordCheckerII(self, pwd: str) -> bool: return ( len(pwd) > 7 and max(len(list(p[1])) for p in groupby(pwd)) == 1 and reduce( lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0 ) == 15 )
https://leetcode.com/problems/strong-password-checker-ii/discuss/2139499/Nothing-Special
22
A password is said to be strong if it satisfies all the following criteria: It has at least 8 characters. It contains at least one lowercase letter. It contains at least one uppercase letter. It contains at least one digit. It contains at least one special character. The special characters are the characters in the following string: "!@#$%^&*()-+". It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates this condition, but "aba" does not). Given a string password, return true if it is a strong password. Otherwise, return false. Example 1: Input: password = "IloveLe3tcode!" Output: true Explanation: The password meets all the requirements. Therefore, we return true. Example 2: Input: password = "Me+You--IsMyDream" Output: false Explanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false. Example 3: Input: password = "1aB!" Output: false Explanation: The password does not meet the length requirement. Therefore, we return false. Constraints: 1 <= password.length <= 100 password consists of letters, digits, and special characters: "!@#$%^&*()-+".
Nothing Special
882
strong-password-checker-ii
0.567
votrubac
Easy
31,708
2,299
successful pairs of spells and potions
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions.sort() ans, n = [], len(potions) for spell in spells: val = success // spell if success % spell == 0: idx = bisect.bisect_left(potions, val) else: idx = bisect.bisect_right(potions, val) ans.append(n - idx) return ans
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2139547/Python-3-or-Math-Binary-Search-or-Explanation
2
You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion. You are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success. Return an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell. Example 1: Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7 Output: [4,0,3] Explanation: - 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful. - 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful. - 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful. Thus, [4,0,3] is returned. Example 2: Input: spells = [3,1,2], potions = [8,5,8], success = 16 Output: [2,0,2] Explanation: - 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful. - 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. - 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. Thus, [2,0,2] is returned. Constraints: n == spells.length m == potions.length 1 <= n, m <= 105 1 <= spells[i], potions[i] <= 105 1 <= success <= 1010
Python 3 | Math, Binary Search | Explanation
89
successful-pairs-of-spells-and-potions
0.317
idontknoooo
Medium
31,719
2,300
match substring after replacement
class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: s_maps = defaultdict(lambda : set()) for x,y in mappings: s_maps[x].add(y) # build a sequence of set for substring match # eg: sub=leet, mappings = {e: 3, t:7} # subs = [{l}, {e, 3}, {e, 3}, {t, 7}] # precalculation helps to eliminate TLE subs = [s_maps[c] | {c} for c in sub] for i in range(len(s)-len(sub) + 1): c=s[i] j=i # Try to match substring while j-i<len(sub) and s[j] in subs[j-i]: j+=1 if j-i==len(sub): # a valid match if iterated through the whole length of substring return True return False
https://leetcode.com/problems/match-substring-after-replacement/discuss/2140652/Python-Precalculation-O(n*k)-without-TLE
7
You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: Replace a character oldi of sub with newi. Each character in sub cannot be replaced more than once. Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false. A substring is a contiguous non-empty sequence of characters within a string. Example 1: Input: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]] Output: true Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'. Now sub = "l3e7" is a substring of s, so we return true. Example 2: Input: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]] Output: false Explanation: The string "f00l" is not a substring of s and no replacements can be made. Note that we cannot replace '0' with 'o'. Example 3: Input: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]] Output: true Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'. Now sub = "l33tb" is a substring of s, so we return true. Constraints: 1 <= sub.length <= s.length <= 5000 0 <= mappings.length <= 1000 mappings[i].length == 2 oldi != newi s and sub consist of uppercase and lowercase English letters and digits. oldi and newi are either uppercase or lowercase English letters or digits.
✅ Python Precalculation O(n*k) without TLE
181
match-substring-after-replacement
0.393
constantine786
Hard
31,727
2,301
count subarrays with score less than k
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: sum, res, j = 0, 0, 0 for i, n in enumerate(nums): sum += n while sum * (i - j + 1) >= k: sum -= nums[j] j += 1 res += i - j + 1 return res
https://leetcode.com/problems/count-subarrays-with-score-less-than-k/discuss/2138778/Sliding-Window
126
The score of an array is defined as the product of its sum and its length. For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75. Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k. A subarray is a contiguous sequence of elements within an array. Example 1: Input: nums = [2,1,4,3,5], k = 10 Output: 6 Explanation: The 6 subarrays having scores less than 10 are: - [2] with score 2 * 1 = 2. - [1] with score 1 * 1 = 1. - [4] with score 4 * 1 = 4. - [3] with score 3 * 1 = 3. - [5] with score 5 * 1 = 5. - [2,1] with score (2 + 1) * 2 = 6. Note that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10. Example 2: Input: nums = [1,1,1], k = 5 Output: 5 Explanation: Every subarray except [1,1,1] has a score less than 5. [1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5. Thus, there are 5 subarrays having scores less than 5. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 105 1 <= k <= 1015
Sliding Window
4,700
count-subarrays-with-score-less-than-k
0.522
votrubac
Hard
31,734
2,302
calculate amount paid in taxes
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: ans = prev = 0 for hi, pct in brackets: hi = min(hi, income) ans += (hi - prev)*pct/100 prev = hi return ans
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2141187/Python3-bracket-by-bracket
14
You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length). Tax is calculated as follows: The first upper0 dollars earned are taxed at a rate of percent0. The next upper1 - upper0 dollars earned are taxed at a rate of percent1. The next upper2 - upper1 dollars earned are taxed at a rate of percent2. And so on. You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: brackets = [[3,50],[7,10],[12,25]], income = 10 Output: 2.65000 Explanation: Based on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket. The tax rate for the three tax brackets is 50%, 10%, and 25%, respectively. In total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes. Example 2: Input: brackets = [[1,0],[4,25],[5,50]], income = 2 Output: 0.25000 Explanation: Based on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket. The tax rate for the two tax brackets is 0% and 25%, respectively. In total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes. Example 3: Input: brackets = [[2,50]], income = 0 Output: 0.00000 Explanation: You have no income to tax, so you have to pay a total of $0 in taxes. Constraints: 1 <= brackets.length <= 100 1 <= upperi <= 1000 0 <= percenti <= 100 0 <= income <= 1000 upperi is sorted in ascending order. All the values of upperi are unique. The upper bound of the last tax bracket is greater than or equal to income.
[Python3] bracket by bracket
535
calculate-amount-paid-in-taxes
0.634
ye15
Easy
31,740
2,303
minimum path cost in a grid
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: max_row, max_col = len(grid), len(grid[0]) dp = [[-1] * max_col for _ in range(max_row)] def recursion(row, col): if row == max_row - 1: # If last row then return nodes value return grid[row][col] if dp[row][col] == -1: # If DP for this node is not computed then we will do so now. current = grid[row][col] # Current Node Value res = float('inf') # To store best path from Current Node for c in range(max_col): # Traverse all path from Current Node val = moveCost[current][c] + recursion(row + 1, c) # Move cost + Target Node Value res = min(res, val) dp[row][col] = res + current # DP[current node] = Best Path + Target Node Val + Current Node Val return dp[row][col] for c in range(max_col): recursion(0, c) # Start recursion from all nodes in 1st row return min(dp[0]) # Return min value from 1st row
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2141004/Python-Recursion-%2B-Memoization
13
You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from cells in the last row. Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n, where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored. The cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row. Example 1: Input: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]] Output: 17 Explanation: The path with the minimum possible cost is the path 5 -> 0 -> 1. - The sum of the values of cells visited is 5 + 0 + 1 = 6. - The cost of moving from 5 to 0 is 3. - The cost of moving from 0 to 1 is 8. So the total cost of the path is 6 + 3 + 8 = 17. Example 2: Input: grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]] Output: 6 Explanation: The path with the minimum possible cost is the path 2 -> 3. - The sum of the values of cells visited is 2 + 3 = 5. - The cost of moving from 2 to 3 is 1. So the total cost of this path is 5 + 1 = 6. Constraints: m == grid.length n == grid[i].length 2 <= m, n <= 50 grid consists of distinct integers from 0 to m * n - 1. moveCost.length == m * n moveCost[i].length == n 1 <= moveCost[i][j] <= 100
Python Recursion + Memoization
501
minimum-path-cost-in-a-grid
0.656
anCoderr
Medium
31,761
2,304
fair distribution of cookies
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: l = [0]*k self.s = float('inf') def ser(l,i): if i>=len(cookies): self.s = min(self.s,max(l)) return if max(l)>=self.s: return for j in range(k): l[j]+=cookies[i] ser(l,i+1) l[j]-=cookies[i] ser(l,0) return self.s
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2141013/Python-optimized-solution-or-Backtracking-Implemented-or-O(KN)-Time-Complexity
5
You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up. The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution. Return the minimum unfairness of all distributions. Example 1: Input: cookies = [8,15,10,20,8], k = 2 Output: 31 Explanation: One optimal distribution is [8,15,8] and [10,20] - The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies. - The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies. The unfairness of the distribution is max(31,30) = 31. It can be shown that there is no distribution with an unfairness less than 31. Example 2: Input: cookies = [6,1,3,2,2,4,1,2], k = 3 Output: 7 Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2] - The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies. - The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies. - The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies. The unfairness of the distribution is max(7,7,7) = 7. It can be shown that there is no distribution with an unfairness less than 7. Constraints: 2 <= cookies.length <= 8 1 <= cookies[i] <= 105 2 <= k <= cookies.length
Python optimized solution | Backtracking Implemented | O(K^N) Time Complexity
852
fair-distribution-of-cookies
0.626
AkashHooda
Medium
31,780
2,305
naming a company
class Solution: def distinctNames(self, ideas: List[str]) -> int: names=defaultdict(set) res=0 #to store first letter as key and followed suffix as val for i in ideas: names[i[0]].add(i[1:]) #list of distinct first-letters available in ideas (may or may not contain all alphabets,depends upon elements in ideas) arr=list(names.keys()) ans,n=0,len(arr) for i in range(n): for j in range(i+1,n): #a,b => 2 distinct first letters a,b=arr[i],arr[j] # adding the number of distinct posssible suffixes and multiplying by 2 as the new word formed might be "newword1 newword2" or "newword2 newword1" res+=len(names[a]-names[b])*len(names[b]-names[a])*2 return res
https://leetcode.com/problems/naming-a-company/discuss/2147565/Python-or-Faster-than-100-or-groupby-detailed-explanation
4
You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: Choose 2 distinct names from ideas, call them ideaA and ideaB. Swap the first letters of ideaA and ideaB with each other. If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name. Otherwise, it is not a valid name. Return the number of distinct valid names for the company. Example 1: Input: ideas = ["coffee","donuts","time","toffee"] Output: 6 Explanation: The following selections are valid: - ("coffee", "donuts"): The company name created is "doffee conuts". - ("donuts", "coffee"): The company name created is "conuts doffee". - ("donuts", "time"): The company name created is "tonuts dime". - ("donuts", "toffee"): The company name created is "tonuts doffee". - ("time", "donuts"): The company name created is "dime tonuts". - ("toffee", "donuts"): The company name created is "doffee tonuts". Therefore, there are a total of 6 distinct company names. The following are some examples of invalid selections: - ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array. - ("time", "toffee"): Both names are still the same after swapping and exist in the original array. - ("coffee", "toffee"): Both names formed after swapping already exist in the original array. Example 2: Input: ideas = ["lack","back"] Output: 0 Explanation: There are no valid selections. Therefore, 0 is returned. Constraints: 2 <= ideas.length <= 5 * 104 1 <= ideas[i].length <= 10 ideas[i] consists of lowercase English letters. All the strings in ideas are unique.
Python | Faster than 100% | groupby detailed explanation
172
naming-a-company
0.344
anjalianupam23
Hard
31,793
2,306
greatest english letter in upper and lower case
class Solution: def greatestLetter(self, s: str) -> str: cnt = Counter(s) return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), "")
https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/discuss/2168442/Counter
37
Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string. An English letter b is greater than another letter a if b appears after a in the English alphabet. Example 1: Input: s = "lEeTcOdE" Output: "E" Explanation: The letter 'E' is the only letter to appear in both lower and upper case. Example 2: Input: s = "arRAzFif" Output: "R" Explanation: The letter 'R' is the greatest letter to appear in both lower and upper case. Note that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'. Example 3: Input: s = "AbCdEfGhIjK" Output: "" Explanation: There is no letter that appears in both lower and upper case. Constraints: 1 <= s.length <= 1000 s consists of lowercase and uppercase English letters.
Counter
2,500
greatest-english-letter-in-upper-and-lower-case
0.686
votrubac
Easy
31,796
2,309
sum of numbers with units digit k
class Solution: def minimumNumbers(self, num: int, k: int) -> int: if num == 0: return 0 if num < k: return -1 if num == k: return 1 ans = -1 i = 1 while i <= 10: if (num - i * k) % 10 == 0 and i * k <= num: return i i += 1 return ans
https://leetcode.com/problems/sum-of-numbers-with-units-digit-k/discuss/2168546/Python-oror-Easy-Approach-oror-beats-90.00-Both-Runtime-and-Memory-oror-Remainder
1
Given two integers num and k, consider a set of positive integers with the following properties: The units digit of each integer is k. The sum of the integers is num. Return the minimum possible size of such a set, or -1 if no such set exists. Note: The set can contain multiple instances of the same integer, and the sum of an empty set is considered 0. The units digit of a number is the rightmost digit of the number. Example 1: Input: num = 58, k = 9 Output: 2 Explanation: One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9. Another valid set is [19,39]. It can be shown that 2 is the minimum possible size of a valid set. Example 2: Input: num = 37, k = 2 Output: -1 Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2. Example 3: Input: num = 0, k = 7 Output: 0 Explanation: The sum of an empty set is considered 0. Constraints: 0 <= num <= 3000 0 <= k <= 9
✅Python || Easy Approach || beats 90.00% Both Runtime & Memory || Remainder
43
sum-of-numbers-with-units-digit-k
0.255
chuhonghao01
Medium
31,845
2,310
longest binary subsequence less than or equal to k
class Solution: def longestSubsequence(self, s: str, k: int) -> int: n = len(s) ones = [] # Notice how I reversed the string, # because the binary representation is written from greatest value of 2**n for i, val in enumerate(s[::-1]): if val == '1': ones.append(i) # Initialize ans, there are already number of zeroes (num_of_zeroes = len(nums) - len(ones) ans = n - len(ones) i = 0 # imagine k == 5 and binary string 001011 # ones = [0, 1, 3] # first loop: 5 - 2**0 -> 4, ans += 1 # second loop: 4 - 2**1 -> 2, ans +=1 # Third loop does not occur because 2 - 2**3 -> -6 which is less than zero # So the ans is 3 + 2 = 5 while i < len(ones) and k - 2 ** ones[i] >= 0: ans += 1 k -= 2 ** ones[i] i += 1 return ans
https://leetcode.com/problems/longest-binary-subsequence-less-than-or-equal-to-k/discuss/2168527/PythonororGreedyororFastororEasy-to-undestandoror-With-explanations
5
You are given a binary string s and a positive integer k. Return the length of the longest subsequence of s that makes up a binary number less than or equal to k. Note: The subsequence can contain leading zeroes. The empty string is considered to be equal to 0. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Example 1: Input: s = "1001010", k = 5 Output: 5 Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal. Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively. The length of this subsequence is 5, so 5 is returned. Example 2: Input: s = "00101001", k = 1 Output: 6 Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal. The length of this subsequence is 6, so 6 is returned. Constraints: 1 <= s.length <= 1000 s[i] is either '0' or '1'. 1 <= k <= 109
Python||Greedy||Fast||Easy to undestand|| With explanations
127
longest-binary-subsequence-less-than-or-equal-to-k
0.364
muctep_k
Medium
31,860
2,311
selling pieces of wood
class Solution: def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: dp = [[0]*(n+1) for _ in range(m+1)] for h, w, p in prices: dp[h][w] = p for i in range(1, m+1): for j in range(1, n+1): v = max(dp[k][j] + dp[i - k][j] for k in range(1, i // 2 + 1)) if i > 1 else 0 h = max(dp[i][k] + dp[i][j - k] for k in range(1, j // 2 + 1)) if j > 1 else 0 dp[i][j] = max(dp[i][j], v, h) return dp[m][n]
https://leetcode.com/problems/selling-pieces-of-wood/discuss/2194345/Python-bottom-up-DP-faster-than-99
1
You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars. To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width. Return the maximum money you can earn after cutting an m x n piece of wood. Note that you can cut the piece of wood as many times as you want. Example 1: Input: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]] Output: 19 Explanation: The diagram above shows a possible scenario. It consists of: - 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14. - 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3. - 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2. This obtains a total of 14 + 3 + 2 = 19 money earned. It can be shown that 19 is the maximum amount of money that can be earned. Example 2: Input: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]] Output: 32 Explanation: The diagram above shows a possible scenario. It consists of: - 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30. - 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2. This obtains a total of 30 + 2 = 32 money earned. It can be shown that 32 is the maximum amount of money that can be earned. Notice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood. Constraints: 1 <= m, n <= 200 1 <= prices.length <= 2 * 104 prices[i].length == 3 1 <= hi <= m 1 <= wi <= n 1 <= pricei <= 106 All the shapes of wood (hi, wi) are pairwise distinct.
Python bottom up DP faster than 99%
75
selling-pieces-of-wood
0.482
metaphysicalist
Hard
31,875
2,312
count asterisks
class Solution: """ Time: O(n) Memory: O(1) """ def countAsterisks(self, s: str) -> int: is_closed = True count = 0 for c in s: count += is_closed * c == '*' is_closed ^= c == '|' return count class Solution: """ Time: O(n) Memory: O(n) """ def countAsterisks(self, s: str) -> int: return sum(chunk.count('*') for chunk in s.split('|')[0::2])
https://leetcode.com/problems/count-asterisks/discuss/2484633/Python-Elegant-and-Short-or-Two-solutions-or-One-pass-One-line
3
You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth. Return the number of '*' in s, excluding the '*' between each pair of '|'. Note that each '|' will belong to exactly one pair. Example 1: Input: s = "l|*e*et|c**o|*de|" Output: 2 Explanation: The considered characters are underlined: "l|*e*et|c**o|*de|". The characters between the first and second '|' are excluded from the answer. Also, the characters between the third and fourth '|' are excluded from the answer. There are 2 asterisks considered. Therefore, we return 2. Example 2: Input: s = "iamprogrammer" Output: 0 Explanation: In this example, there are no asterisks in s. Therefore, we return 0. Example 3: Input: s = "yo|uar|e**|b|e***au|tifu|l" Output: 5 Explanation: The considered characters are underlined: "yo|uar|e**|b|e***au|tifu|l". There are 5 asterisks considered. Therefore, we return 5. Constraints: 1 <= s.length <= 1000 s consists of lowercase English letters, vertical bars '|', and asterisks '*'. s contains an even number of vertical bars '|'.
Python Elegant & Short | Two solutions | One pass / One line
137
count-asterisks
0.825
Kyrylo-Ktl
Easy
31,877
2,315
count unreachable pairs of nodes in an undirected graph
class Solution: def countPairs(self, n: int, edges: List[List[int]]) -> int: def dfs(graph,node,visited): visited.add(node) self.c += 1 for child in graph[node]: if child not in visited: dfs(graph, child, visited) #build graph graph = {} for i in range(n): graph[i] = [] for u, v in edges: graph[u].append(v) graph[v].append(u) visited = set() count = 0 totalNodes = 0 #run dfs in unvisited nodes for i in range(n): if i not in visited: self.c = 0 dfs(graph, i, visited) count += totalNodes*self.c # result totalNodes += self.c # total nodes visited return count
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2199190/Simple-and-easy-to-understand-using-dfs-with-explanation-Python
8
You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. Return the number of pairs of different nodes that are unreachable from each other. Example 1: Input: n = 3, edges = [[0,1],[0,2],[1,2]] Output: 0 Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0. Example 2: Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]] Output: 14 Explanation: There are 14 pairs of nodes that are unreachable from each other: [[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]]. Therefore, we return 14. Constraints: 1 <= n <= 105 0 <= edges.length <= 2 * 105 edges[i].length == 2 0 <= ai, bi < n ai != bi There are no repeated edges.
Simple and easy to understand using dfs with explanation [Python]
217
count-unreachable-pairs-of-nodes-in-an-undirected-graph
0.386
ratre21
Medium
31,909
2,316
maximum xor after operations
class Solution: def maximumXOR(self, nums: List[int]) -> int: return reduce(lambda x,y: x|y, nums) class Solution: def maximumXOR(self, nums: List[int]) -> int: return reduce(or_, nums) class Solution: def maximumXOR(self, nums: List[int]) -> int: ans = 0 for n in nums: ans |= n return ans
https://leetcode.com/problems/maximum-xor-after-operations/discuss/2366537/Python3-oror-1-line-bit-operations-w-explanation-oror-TM%3A-8887
5
You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times. Example 1: Input: nums = [3,2,4,6] Output: 7 Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2. Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7. It can be shown that 7 is the maximum possible bitwise XOR. Note that other operations may be used to achieve a bitwise XOR of 7. Example 2: Input: nums = [1,2,3,9,2] Output: 11 Explanation: Apply the operation zero times. The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11. It can be shown that 11 is the maximum possible bitwise XOR. Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 108
Python3 || 1 line, bit operations, w/ explanation || T/M: 88%/87%
88
maximum-xor-after-operations
0.786
warrenruud
Medium
31,922
2,317