post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/convert-the-temperature/discuss/2815504/python-solution-no-need-for-10*-5
class Solution: def convertTemperature(self, celsius: float) -> List[float]: kelvin = celsius + 273.15 fahrenheit = (celsius * 1.80) + 32.00 return [kelvin, fahrenheit]
convert-the-temperature
python solution no need for 10*-5
samanehghafouri
0
2
convert the temperature
2,469
0.909
Easy
33,900
https://leetcode.com/problems/convert-the-temperature/discuss/2815390/Fastest-and-Simplest-Solution-Python-(One-Liner-Code)
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.8 + 32.0]
convert-the-temperature
Fastest and Simplest Solution - Python (One-Liner Code)
PranavBhatt
0
2
convert the temperature
2,469
0.909
Easy
33,901
https://leetcode.com/problems/convert-the-temperature/discuss/2815231/Hardest-Problem-EVER!
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.80 + 32.00]
convert-the-temperature
Hardest Problem EVER!
elbasrouisama
0
6
convert the temperature
2,469
0.909
Easy
33,902
https://leetcode.com/problems/convert-the-temperature/discuss/2814881/Python3
class Solution: def convertTemperature(self, celsius: float) -> List[float]: Kelvin = celsius + 273.15 Fahrenheit = celsius * 1.80 + 32 return [Kelvin, Fahrenheit]
convert-the-temperature
Python3
anashaupt
0
2
convert the temperature
2,469
0.909
Easy
33,903
https://leetcode.com/problems/convert-the-temperature/discuss/2814833/Beats-100-Python
class Solution: def convertTemperature(self, celsius: float) -> List[float]: ans=[] Kelvin=celsius + 273.15 Fahrenheit=celsius * 1.80 + 32.00 ans.append(Kelvin) ans.append(Fahrenheit) return ans
convert-the-temperature
Beats 100%, Python
prakritig2
0
2
convert the temperature
2,469
0.909
Easy
33,904
https://leetcode.com/problems/convert-the-temperature/discuss/2814701/Python-Simple-Python-Solution
class Solution: def convertTemperature(self, celsius: float) -> List[float]: Kelvin = celsius + 273.15 Fahrenheit = celsius * 1.80 + 32.00 return [Kelvin,Fahrenheit]
convert-the-temperature
[ Python ] ✅✅ Simple Python Solution🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
6
convert the temperature
2,469
0.909
Easy
33,905
https://leetcode.com/problems/convert-the-temperature/discuss/2814432/Super-easy-and-fast-Python3-Answer
class Solution: def convertTemperature(self, c: float) -> List[float]: return [c + 273.15, c*1.80+32.00]
convert-the-temperature
Super easy and fast Python3 Answer
hyamtx
0
1
convert the temperature
2,469
0.909
Easy
33,906
https://leetcode.com/problems/convert-the-temperature/discuss/2813960/One-line-100-speed
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.80 + 32.00]
convert-the-temperature
One line, 100% speed
EvgenySH
0
5
convert the temperature
2,469
0.909
Easy
33,907
https://leetcode.com/problems/convert-the-temperature/discuss/2810375/Python-Solution-or-One-Liner-or-100-Faster
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [ celsius + 273.15, (celsius * 1.80) + 32.00 ]
convert-the-temperature
Python Solution | One Liner | 100% Faster
Gautam_ProMax
0
12
convert the temperature
2,469
0.909
Easy
33,908
https://leetcode.com/problems/convert-the-temperature/discuss/2810108/Python-Solution
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius+273.15,celsius*1.80+32.00]
convert-the-temperature
Python Solution
CEOSRICHARAN
0
3
convert the temperature
2,469
0.909
Easy
33,909
https://leetcode.com/problems/convert-the-temperature/discuss/2809679/Easiest-Python-Solution-oror-Full-Explanation
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius+273.15,celsius*1.80+32.00]
convert-the-temperature
✔💖Easiest Python Solution || Full Explanation
AdityaTrivedi88
0
4
convert the temperature
2,469
0.909
Easy
33,910
https://leetcode.com/problems/convert-the-temperature/discuss/2809644/Python-or-Easy-or-Faster-than-100
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, (celsius * 1.80) + 32.00]
convert-the-temperature
Python | Easy | Faster than 100%
pawangupta
0
6
convert the temperature
2,469
0.909
Easy
33,911
https://leetcode.com/problems/convert-the-temperature/discuss/2809252/Easy-Python-Solution
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius+ 273.15, (celsius * 1.80) + 32]
convert-the-temperature
Easy Python Solution
imash_9
0
4
convert the temperature
2,469
0.909
Easy
33,912
https://leetcode.com/problems/convert-the-temperature/discuss/2809215/Python3JavaScript-Self-Explanatory
class Solution: def convertTemperature(self, celsius: float) -> List[float]: kelvin = celsius + 273.15 fahrenheit = celsius * 1.80 + 32.00 return [kelvin, fahrenheit]
convert-the-temperature
✅[Python3/JavaScript] Self Explanatory
MusfiqDehan
0
10
convert the temperature
2,469
0.909
Easy
33,913
https://leetcode.com/problems/convert-the-temperature/discuss/2809047/Easy-python-beats-100.00-just-convert
class Solution: def convertTemperature(self, c): return [c+273.15,c*1.8+32]
convert-the-temperature
Easy python beats 100.00% [just convert]
U753L
0
9
convert the temperature
2,469
0.909
Easy
33,914
https://leetcode.com/problems/convert-the-temperature/discuss/2808910/One-liner-Python3-O(1)-Solution-Easiest-to-understand
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [(celsius + 273.15), (celsius * 1.80 + 32.00)]
convert-the-temperature
One liner Python3 O(1) Solution Easiest to understand
jubinsoni
0
8
convert the temperature
2,469
0.909
Easy
33,915
https://leetcode.com/problems/convert-the-temperature/discuss/2808873/Python-1-liner-simple-solution
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.80 + 32.00]
convert-the-temperature
✅ Python 1 liner simple solution
sezanhaque
0
8
convert the temperature
2,469
0.909
Easy
33,916
https://leetcode.com/problems/convert-the-temperature/discuss/2808832/return-celsius-%2B-273.15-celsius-*-1.80-%2B-32.00
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return celsius + 273.15, celsius * 1.80 + 32.00
convert-the-temperature
return celsius + 273.15, celsius * 1.80 + 32.00
Silvia42
0
14
convert the temperature
2,469
0.909
Easy
33,917
https://leetcode.com/problems/convert-the-temperature/discuss/2808794/python-solution
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.80 + 32.00]
convert-the-temperature
python solution
akaghosting
0
27
convert the temperature
2,469
0.909
Easy
33,918
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2808943/Beginners-Approach-%3A
class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: def find_lcm(num1, num2): if(num1>num2): num = num1 den = num2 else: num = num2 den = num1 rem = num % den while(rem != 0): num = den den = rem rem = num % den gcd = den lcm = int(int(num1 * num2)/int(gcd)) return lcm count=0 for i in range(len(nums)): lcm=1 for j in range(i,len(nums)): lcm=find_lcm(nums[j],lcm) if lcm==k: count+=1 if lcm>k: break return count
number-of-subarrays-with-lcm-equal-to-k
Beginners Approach :
goxy_coder
1
57
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,919
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2835262/Python-(Simple-Maths)
class Solution: def subarrayLCM(self, nums, k): n, count = len(nums), 0 for i in range(n): temp = nums[i] for j in range(i,n): temp = math.lcm(temp,nums[j]) if temp == k: count += 1 elif temp > k: break return count
number-of-subarrays-with-lcm-equal-to-k
Python (Simple Maths)
rnotappl
0
5
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,920
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2828569/More-Efficient-GCD-based-Solution-The-Best
class Solution: def subarrayLCM(self, nums: list[int], k: int) -> int: coprime_count = 0 for subarray_end, n in enumerate(nums): nums[subarray_end] = k // n if k % n == 0 else None running_gcd = 0 for subarray_start in reversed(range(subarray_end + 1)): if not nums[subarray_start]: break running_gcd = gcd(running_gcd, nums[subarray_start]) coprime_count += running_gcd == 1 return coprime_count
number-of-subarrays-with-lcm-equal-to-k
More Efficient GCD-based Solution, The Best
Triquetra
0
19
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,921
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2824249/Python-A-DP-approach
class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: n = len(nums) dp = [[0] * n for _ in range(n)] result = 0 for i in range(n-1,-1,-1): for j in range(i, n): temp = math.lcm(nums[i], nums[j]) if i + 1 == j or i == j: dp[i][j] = temp else: dp[i][j] = math.lcm(temp, dp[i+1][j-1]) if dp[i][j] == k: result += 1 return result
number-of-subarrays-with-lcm-equal-to-k
[Python] A DP approach
hengsoo
0
7
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,922
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2809141/python-solution
class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: res = 0 for i in range(len(nums)): curLcm = nums[i] if nums[i] <= k: for j in range(i, len(nums)): if nums[j] <= k: curLcm = lcm(curLcm, nums[j]) if curLcm == k: res += 1 else: break return res
number-of-subarrays-with-lcm-equal-to-k
python solution
akaghosting
0
19
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,923
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2809139/Python-Answer-Simple-Two-Loops-(start-and-end-index)
class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: res = 0 for i in range(len(nums)): l = nums[i] if l == k: res+=1 for j in range(i+1,len(nums)): l = lcm(l,nums[j]) if l == k: res+=1 return res
number-of-subarrays-with-lcm-equal-to-k
[Python Answer🤫🐍🐍🐍] Simple Two Loops (start and end index)
xmky
0
16
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,924
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2809111/Python3-running-LCM-beats-100.00
class Solution: def subarrayLCM(self, nums, k): cnt=0 # number of working subsets for i in range(len(nums)): # left bound runningLCM = nums[i] for j in range(i, len(nums)): runningLCM = lcm(runningLCM, nums[j]) # generate new gcd of given subset if runningLCM==k: cnt+=1 elif runningLCM>k: break return cnt
number-of-subarrays-with-lcm-equal-to-k
[Python3] running LCM, beats 100.00%
U753L
0
17
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,925
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2808985/Python3-brute-force
class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: ans = 0 for i in range(len(nums)): val = 1 for j in range(i, len(nums)): val = lcm(val, nums[j]) if val == k: ans += 1 return ans
number-of-subarrays-with-lcm-equal-to-k
[Python3] brute-force
ye15
0
15
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,926
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2808978/Python-Simple-Solution
class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: res = 0 for left in range(len(nums)): curr = nums[left] right = left while right < len(nums) and k % nums[right] == 0: curr = math.lcm(curr, nums[right]) if curr > k: break elif curr == k: res += 1 right += 1 return res
number-of-subarrays-with-lcm-equal-to-k
✅ Python Simple Solution
sezanhaque
0
56
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,927
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2808921/Python-Brute-Force
class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: n = len(nums) ans = 0 for i in range(n): lcm = nums[i] for j in range(i, n): lcm = lcm * nums[j] // math.gcd(lcm, nums[j]) if lcm == k: ans += 1 elif lcm >k: break return ans
number-of-subarrays-with-lcm-equal-to-k
Python Brute Force
rbhandu
0
17
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,928
https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2808840/Optimized-Bruteforce-or-Short-and-simple-to-understand-or-with-explanation
class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: num_subarray = 0 n = len(nums) for i in range(n): lcm = nums[i] for j in range(i, n): lcm = math.lcm(lcm, nums[j]) if lcm > k: break else: num_subarray += (lcm == k) return num_subarray
number-of-subarrays-with-lcm-equal-to-k
Optimized Bruteforce | Short and simple to understand | with explanation
jubinsoni
0
40
number of subarrays with lcm equal to k
2,470
0.388
Medium
33,929
https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2808960/Python3-BFS
class Solution: def minimumOperations(self, root: Optional[TreeNode]) -> int: ans = 0 queue = deque([root]) while queue: vals = [] for _ in range(len(queue)): node = queue.popleft() vals.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) mp = {x : i for i, x in enumerate(sorted(vals))} visited = [0]*len(vals) for i in range(len(vals)): cnt = 0 while not visited[i] and i != mp[vals[i]]: visited[i] = 1 cnt += 1 i = mp[vals[i]] ans += max(0, cnt-1) return ans
minimum-number-of-operations-to-sort-a-binary-tree-by-level
[Python3] BFS
ye15
6
567
minimum number of operations to sort a binary tree by level
2,471
0.629
Medium
33,930
https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2808987/Easy-Level-order-traversal-with-comments-oror-Python
class Solution: def cntSwap(self,arr): n = len(arr) cnt = 0 a = sorted(arr) index = {} # store index of elements in arr for ind in range(n): index[arr[ind]] = ind for ind in range(n): # If element in arr is out of position we need to swap hence increase cnt if (arr[ind] != a[ind]): cnt += 1 pos = arr[ind] # Replace it with element that should be at this "ind" in arr using a[ind] arr[ind], arr[index[a[ind]]] = arr[index[a[ind]]], arr[ind] # Update the indexes for swaped elements in "index" index[pos] = index[a[ind]] index[a[ind]] = ind return cnt def minimumOperations(self, root: Optional[TreeNode]) -> int: res = 0 q = [root] # Level order traversal while q : level = [] values = [] for n in q: if n.left : level.append(n.left) values.append(n.left.val) if n.right : level.append(n.right) values.append(n.right.val) res += self.cntSwap(values) q = level return res
minimum-number-of-operations-to-sort-a-binary-tree-by-level
Easy Level order traversal with comments || Python
CoderIsCodin
4
203
minimum number of operations to sort a binary tree by level
2,471
0.629
Medium
33,931
https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2836036/Python-(Simple-DFS-%2BSorting)
class Solution: def func_(self,nums): dict2 = {n:j for j,n in enumerate(sorted(nums))} count, i = 0, 0 while i < len(nums): j = dict2[nums[i]] if i != j: nums[i], nums[j] = nums[j], nums[i] count += 1 else: i += 1 return count def minimumOperations(self, root): if not root: return 0 dict1 = defaultdict(list) def dfs(node,level): if not node: return 0 dict1[level].append(node.val) dfs(node.left,level+1) dfs(node.right,level+1) dfs(root,0) ans = list(dict1.values()) return sum([self.func_(i) for i in ans])
minimum-number-of-operations-to-sort-a-binary-tree-by-level
Python (Simple DFS +Sorting)
rnotappl
0
5
minimum number of operations to sort a binary tree by level
2,471
0.629
Medium
33,932
https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2831314/Optimal-and-Without-Actually-Swapping-Values-The-Best
class Solution: def minimumOperations(self, root: Optional[TreeNode]) -> int: return sum([self.minimum_swaps(level) for level in self.bfs_levels(root)]) def bfs_levels(self, root: Optional[TreeNode]) -> list[list[int]]: nodes, levels, index = [root], [0], 0 while index != len(nodes): for child in nodes[index].left, nodes[index].right: if child: nodes.append(child) levels.append(levels[index] + 1) index += 1 values = [[] for _ in range(levels[-1] + 1)] for index in range(len(nodes)): values[levels[index]].append(nodes[index].val) return values def minimum_swaps(self, array: list[int]) -> int: sorted_indexes = sorted(range(len(array)), key=array.__getitem__) return len(array) - sum(self.has_cycle(sorted_indexes, index) for index in range(len(array))) def has_cycle(self, sorted_indexes: list[int], index: int) -> bool: had_cycle = False while sorted_indexes[index] != -1: sorted_indexes[index], next_index = -1, sorted_indexes[index] index, had_cycle = next_index, True return had_cycle
minimum-number-of-operations-to-sort-a-binary-tree-by-level
Optimal and Without Actually Swapping Values, The Best
Triquetra
0
5
minimum number of operations to sort a binary tree by level
2,471
0.629
Medium
33,933
https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2823256/Python-solution
class Solution: def minimumOperations(self, root: Optional[TreeNode]) -> int: levels = [] res = 0 def levelorder(node, level): if level >= len(levels): levels.append([]) if node: levels[level].append(node.val) if node.left: levelorder(node.left, level + 1) if node.right: levelorder(node.right, level + 1) def diff(nums): s = sorted(nums) dic = {} diff = 0 for i, n in enumerate(nums): dic[n] = i for i in range(len(nums)): if nums[i] != s[i]: idx = dic[s[i]] dic[nums[i]] = idx dic[s[i]] = i nums[i], nums[idx] = nums[idx], nums[i] diff += 1 return diff levelorder(root,0) for i in range(len(levels)): res += diff(levels[i]) return res
minimum-number-of-operations-to-sort-a-binary-tree-by-level
Python solution
maomao1010
0
8
minimum number of operations to sort a binary tree by level
2,471
0.629
Medium
33,934
https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2812540/Python3-Level-BFS-and-manipulate-vals-index
class Solution: def minimumOperations(self, root: Optional[TreeNode]) -> int: cur, ans = [root], 0 while cur: nxt, nums, numidx = [], [], dict() for node in cur: numidx[node.val] = len(nums) nums.append(node.val) if node.left: nxt.append(node.left) if node.right: nxt.append(node.right) for i, v in enumerate(sorted(nums)): if i != numidx[v]: ans += 1 nums[numidx[v]] = nums[i] numidx[nums[i]] = numidx[v] cur = nxt return ans
minimum-number-of-operations-to-sort-a-binary-tree-by-level
[Python3] Level BFS and manipulate vals index
cava
0
4
minimum number of operations to sort a binary tree by level
2,471
0.629
Medium
33,935
https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2809954/Python-BFS-%2B-count-swaps-required-simple-solution
class Solution: def countswaps(self, arr): count = 0 temp = sorted(arr) h = {} for i in range(len(arr)): h[arr[i]] = i for i in range(len(arr)): if arr[i] != temp[i]: count += 1 # swap to correct place j = h[temp[i]] h[arr[i]], h[arr[j]] = j, i arr[i], arr[j] = arr[j], arr[i] return count def minimumOperations(self, root: Optional[TreeNode]) -> int: q = collections.deque() q.append(root) ans = 0 while q: size = len(q) level = [] for _ in range(size): temp = q.popleft() level.append(temp.val) if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) ans += self.countswaps(level) return ans
minimum-number-of-operations-to-sort-a-binary-tree-by-level
Python BFS + count swaps required simple solution
ishaan06
0
19
minimum number of operations to sort a binary tree by level
2,471
0.629
Medium
33,936
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2808845/Python3-DP-with-Explanations-or-Only-Check-Substrings-of-Length-k-and-k-%2B-1
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) dp = [0] * (n + 1) for i in range(k, n + 1): dp[i] = dp[i - 1] for length in range(k, k + 2): j = i - length if j < 0: break if self.isPalindrome(s, j, i): dp[i] = max(dp[i], 1 + dp[j]) return dp[-1] def isPalindrome(self, s, j, i): left, right = j, i - 1 while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True
maximum-number-of-non-overlapping-palindrome-substrings
[Python3] DP with Explanations | Only Check Substrings of Length k and k + 1
xil899
11
542
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,937
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2832974/Python3-or-Memoization
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n=len(s) def checkIfPalindrome(i,j): while i<j: if s[i]!=s[j]: return False i+=1 j-=1 return True @lru_cache(2000) def dp(i,j): if i>=n or j>=n or (j-i)>k+1: return 0 if s[i]==s[j]: if checkIfPalindrome(i,j): return 1+dp(j+1,j+k) return max(dp(i,j+1),dp(i+1,j+1)) return dp(0,k-1)
maximum-number-of-non-overlapping-palindrome-substrings
Python3 | Memoization
Dr_Negative
1
9
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,938
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2814448/Simplest-Greedy-Python-Solution-or-O(1)-Space-or-O(n*k)-Time
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) # function to check whether substring is a palindrome def valid(i, j): # if end index is greater then length of string if j > len(s): return False if s[i : j] == s[i : j][::-1]: return True return False maxSubstrings = 0 start = 0 while start < n: if valid(start, start + k): maxSubstrings += 1 start += k elif valid(start, start + k + 1): maxSubstrings += 1 start += k + 1 else: # when there is no palindrome starting at that particular index start += 1 return maxSubstrings
maximum-number-of-non-overlapping-palindrome-substrings
Simplest Greedy Python Solution | O(1) Space | O(n*k) Time
deepaklaksman
1
18
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,939
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2811830/Python-Very-simple-solution-O(n)-oror-no-DP
class Solution: def maxPalindromes(self, s: str, k: int) -> int: res = 0 lastp = -1 def helper(l, r): nonlocal lastp, res while l >= 0 and r < len(s) and s[l] == s[r] and l > lastp: if r-l+1 >= k: res += 1 lastp = r break # find the shortest palindrome else: l -= 1 r += 1 for i in range(len(s)): helper(i, i) # odd length helper(i, i+1) # even length return res
maximum-number-of-non-overlapping-palindrome-substrings
✅ [Python] Very simple solution - O(n) || no DP
Meerka_
1
22
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,940
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2809266/Python3-greedy-only-check-length-k-and-k-%2B-1
class Solution: def maxPalindromes(self, s: str, k: int) -> int: ans = 0 l = 0 while l<len(s): cdd1 = s[l:l+k] if len(cdd1)>=k and cdd1 == cdd1[::-1]: ans += 1 l = l+k continue cdd2 = s[l:l+k+1] if len(cdd2)>=k and cdd2 == cdd2[::-1]: ans += 1 l = l+k+1 continue l += 1 return ans
maximum-number-of-non-overlapping-palindrome-substrings
[Python3] greedy - only check length k and k + 1
nxiayu
1
39
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,941
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2816429/Python-Two-DP-O(NK)
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) if k == 1: return n ispalindromes, palidxs = [[True] * n for _ in range(n)], [[] for _ in range(n + 1)] for step in range(1, k + 2): for i in range(n - step): ispalindromes[i][i + step] = (ispalindromes[i + 1][i + step - 1] and s[i] == s[i + step]) if step + 1 >= k and ispalindromes[i][i + step]: palidxs[i + step + 1].append(i) dp = [0] * (n + 1) for i in range(n + 1): if i > 0: dp[i] = max(dp[i], dp[i - 1]) for j in palidxs[i]: dp[i] = max(dp[i], dp[j] + 1) return dp[-1]
maximum-number-of-non-overlapping-palindrome-substrings
[Python] Two DP, O(NK)
cava
0
6
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,942
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2814368/Python3-or-Memoization
class Solution: def maxPalindromes(self, s: str, k: int) -> int: @cache def dp(ind): if ind >= n-k+1: return 0 val = 0 for i in range(k,k+2): if s[ind:ind+i] == s[ind:ind+i][::-1]: val = max(val,1 + dp(ind+i)) break val = max(val,dp(ind+1)) return val n = len(s) return dp(0)
maximum-number-of-non-overlapping-palindrome-substrings
[Python3] | Memoization
swapnilsingh421
0
11
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,943
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2811654/Non-Overlapping-Intervals-or-Greedy-or-Python3
class Solution: def maxPalindromes(self, s: str, k: int) -> int: intervals = [] n = len(s) for i in range(n): j = 0 while i - j > -1 and i + j < n and s[i - j] == s[i + j]: st, e = i - j, i + j if e - st + 1 >= k: intervals.append([st, e]) j += 1 for i in range(n - 1): j = 0 while i - j > -1 and i + 1 + j < n and s[i - j] == s[i + 1 + j]: st, e = i - j, i + 1 + j if e - st + 1 >= k: intervals.append([st, e]) break j += 1 intervals.sort(key = lambda x: x[1]) t = -1 ans = 0 for s, e in intervals: if s > t: t = e ans += 1 return ans
maximum-number-of-non-overlapping-palindrome-substrings
Non Overlapping Intervals | Greedy | Python3
DheerajGadwala
0
15
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,944
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2811186/Python-3Greedy-cutting
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) if k == 1: return n # palindrome length with center at x without overalpping with previous string end at index "prev" def helper(x, prev): i, j = x - 1, x + 1 while i > prev and j < n: if s[i] != s[j]: break # as long as the palindrom met the minimum length return the right index if j - i + 1 >= k: return j i -= 1 j += 1 i, j = x, x + 1 while i > prev and j < n: if s[i] != s[j]: break if j - i + 1 >= k: return j i -= 1 j += 1 return -1 # build the right index array idx = [-1] * n prev = -1 for i in range(n): tmp = helper(i, prev) if tmp != -1: prev = tmp idx[i] = tmp ans = i = 0 while i < n: if idx[i] < 0: i += 1 else: ans += 1 i = idx[i] + 1 return ans
maximum-number-of-non-overlapping-palindrome-substrings
[Python 3]Greedy cutting
chestnut890123
0
15
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,945
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2810522/Python-O(nk)-without-DP-or-recursion.-Simple-iterative-solution-with-explanation
class Solution: def checkPalindromeAndReturnShortestGreaterThanK(self, s, i, j, beg, k): while i > beg and j < len(s) and s[i]==s[j]: if j-i-1 >= k: return j-1 i-=1 j+=1 if j-i-1 >= k: return j-1 return -1 def getShortestPalindromeEndPosition(self, s, cur, beg, k): i = cur-1 j = cur+1 ans1 = self.checkPalindromeAndReturnShortestGreaterThanK(s, i, j, beg, k) if ans1 != -1: return ans1 if cur+1<len(s) and s[cur] == s[cur+1]: i = cur-1 j = cur+2 ans2 = self.checkPalindromeAndReturnShortestGreaterThanK(s, i, j, beg, k) if ans2 != -1: return ans2 return cur def maxPalindromes(self, s: str, k: int) -> int: beg = -1 i = 0 count = 0 while i < len(s): end = self.getShortestPalindromeEndPosition(s, i, beg, k) if end != i or (end == i and k==1): beg = end count += 1 i = end + 1 return count
maximum-number-of-non-overlapping-palindrome-substrings
Python O(nk) without DP or recursion. Simple iterative solution with explanation
AkshayDagar
0
3
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,946
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2809409/Python-Time-O(NK)-or-Space-O(1)
class Solution: def maxPalindromes(self, s: str, k: int) -> int: def expand(i, j): # j - i <= k means we have to expand only until # len(palindrome) >= k, and len(palindrome) is as small as possible while i > left_boundary and j < len(s) and j - i <= k and s[i] == s[j]: i -= 1 j += 1 return i + 1, j - 1 if k == 1: return len(s) res = 0 left_boundary = -1 # to cut the part of the string we've already seen i = 0 while i < len(s) - 1: left1, right1 = expand(i, i) left2, right2 = expand(i, i + 1) i += 1 # If an odd-length palindrome is found, it's always shorter than the one with even length if right1 - left1 + 1 >= k: left_boundary = right1 res += 1 i = right1 + 1 elif right2 - left2 + 1 >= k: left_boundary = right2 res += 1 i = right2 + 1 return res
maximum-number-of-non-overlapping-palindrome-substrings
[Python] Time O(NK) | Space O(1)
miguel_v
0
11
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,947
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2809306/Python-solution-with-explanation
class Solution: def maxPalindromes(self, s: str, k: int) -> int: def getPalindrome(idx, single): i, j = idx - 1, idx + 1 length = 1 if not single: length += 1 j += 1 while i >= 0 and j < len(s) and s[i] == s[j]: length += 2 i -= 1 j += 1 return length palindromes = [] for i in range(len(s)): length = getPalindrome(i, True) if length >= k: palindromes.append([i - (k // 2), i + (k // 2)]) if k > 1 and i < len(s) - 1 and s[i] == s[i + 1]: length = getPalindrome(i, False) if length >= k: palindromes.append([i - ((k // 2) - 1), i + (k // 2)]) last = -inf total = 0 for start, end in sorted(palindromes, key = lambda p: p[1]): if start > last: last = end total += 1 return total
maximum-number-of-non-overlapping-palindrome-substrings
Python solution with explanation
nawrazi
0
17
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,948
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2809175/Python3-DP%2BGreedy
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) palEnds = -1 # previous palindrome ending pos res = 0 for i in range(n): for j in range(i + k - 1, n): if i <= palEnds and j >= palEnds: break pal = s[i:j+1] if pal == pal[::-1]: if i > palEnds: res += 1 palEnds = j return res
maximum-number-of-non-overlapping-palindrome-substrings
Python3 DP+Greedy
fengqifeng
0
10
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,949
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2809175/Python3-DP%2BGreedy
class Solution: def maxPalindromes(self, s: str, k: int) -> int: def isPalindrome(i: int, j: int) -> bool: while i < j: if s[i] != s[j]: return False i += 1 j -= 1 return True n, i, res = len(s), 0, 0 while i <= n - k: if s[i] == s[i+k-1] and isPalindrome(i, i+k-1): res += 1 i = i + k elif i+k < n and s[i] == s[i+k] and isPalindrome(i, i+k): res += 1 i = i + k + 1 else: i += 1 return res
maximum-number-of-non-overlapping-palindrome-substrings
Python3 DP+Greedy
fengqifeng
0
10
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,950
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2809114/Python-Answer-Until-K-%2B-2-FAST-Beats-75
class Solution: def maxPalindromes(self, s: str, k: int) -> int: @cache def checkPall(ss): return ss == ss[::-1] @cache def checkPal(i,j): ss = s[i:j] return checkPall(ss) dp = [0] * (len(s) + 1) for i in range(len(s)-k+1): dp[i] = dp[i-1]) for j in range(i+k, i+k+2 ): if j <= len(s) and checkPal(i,j): dp[j] = max(dp[j], 1 + dp[i]) break return max(dp) '''
maximum-number-of-non-overlapping-palindrome-substrings
[Python Answer🤫🐍🐍🐍] Until K + 2 - FAST Beats 75%
xmky
0
7
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,951
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2809071/Python-Greedy-Approach-O(nk)O(1)
class Solution: def find_first_palindrome(self, string, i, k): N = len(string) L = N - i M = L + L - 1 for j in range(M): if j % 2 == 0: ll = rr = i + j // 2 else: ll = i + j // 2 rr = ll + 1 while ll >= i and rr < N and string[ll] == string[rr]: if rr - ll + 1 >= k: return (ll, rr) ll -= 1 rr += 1 return def maxPalindromes(self, s: str, k: int) -> int: N = len(s) if k == 1: return N count = 0 i = 0 while i < N: pair = self.find_first_palindrome(s, i, k) if pair: count += 1 i = pair[1] + 1 else: i = N return count
maximum-number-of-non-overlapping-palindrome-substrings
[Python] Greedy Approach O(nk)/O(1)
ryanmeow
0
11
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,952
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2809042/Very-easy-and-short-O(n)-solution-or-python
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) if k == 1: return n ans = 0 i = 0 while i + k <= n: if s[i:i + k] == s[i:i + k][::-1]: ans += 1 i = i + k elif s[i:i + k + 1] == s[i:i + k + 1][::-1]: ans += 1 i = i + k + 1 else: i += 1 return ans
maximum-number-of-non-overlapping-palindrome-substrings
Very easy and short O(n) solution | python
jackie890621
0
19
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,953
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2809025/Enumerate-and-greedy-O(n*k)
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) self.ans = 0 self.start = 0 i = 0 while i < n: r1 = self.is_pal(i, i, s, k) r2 = self.is_pal(i, i+1, s, k) if r1 < n or r2 < n: i = min(r1, r2) + 1 self.ans += 1 self.start = i else: i += 1 return self.ans def is_pal(self, left, right, s, k): size = right - left + 1 l, r = left, right n = len(s) ans = float("inf") while l >= self.start and r < n and s[l] == s[r]: if size >= k: # self.ans += 1 # ps.add(s[l:r+1]) return r l -= 1 r += 1 size += 2 return ans
maximum-number-of-non-overlapping-palindrome-substrings
Enumerate and greedy, O(n*k)
goodgoodwish
0
26
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,954
https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2808975/Python3-dp
class Solution: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) vals = [1]*n for i in range(2*n-1): lo, hi = i//2, (i+1)//2 while 0 <= lo <= hi < n and s[lo] == s[hi]: if vals[lo] < k: vals[lo] = max(vals[lo], hi-lo+1) lo -= 1 hi += 1 dp = [0]*(n+1) for i in range(n-1, -1, -1): dp[i] = dp[i+1] if vals[i] >= k: dp[i] = max(dp[i], 1+dp[i+vals[i]]) return dp[0]
maximum-number-of-non-overlapping-palindrome-substrings
[Python3] dp
ye15
0
21
maximum number of non overlapping palindrome substrings
2,472
0.366
Hard
33,955
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2834169/Python-Hashmap-O(n)-with-diagrams
class Solution: def unequalTriplets(self, nums: List[int]) -> int: c = Counter(nums) res = 0 left = 0 right = len(nums) for _, freq in c.items(): right -= freq res += left * freq * right left += freq return res
number-of-unequal-triplets-in-array
Python Hashmap O(n) with diagrams
cheatcode-ninja
10
242
number of unequal triplets in array
2,475
0.699
Easy
33,956
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2832078/PythonC%2B%2BJavaScript-O(n)-beats-100
class Solution: def unequalTriplets(self, nums: List[int]) -> int: count = 0 prev, nxt = 0, len(nums) for _, frequency in Counter(nums).items(): nxt -= frequency count += prev * frequency * nxt prev += frequency return count
number-of-unequal-triplets-in-array
✅ [Python/C++/JavaScript] O(n) beats 100%
sezanhaque
8
533
number of unequal triplets in array
2,475
0.699
Easy
33,957
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2831993/Easy-Brute-Force-solution-or-Python-or-TC-O(n3)
class Solution: def unequalTriplets(self, nums: List[int]) -> int: c = 0 for i in range(len(nums)): for j in range(i+1, len(nums)): for k in range(j+1, len(nums)): if nums[i]!=nums[j] and nums[i]!=nums[k] and nums[j] != nums[k]: c+=1 return c
number-of-unequal-triplets-in-array
Easy Brute Force solution | Python | TC = O(n^3)
jayvardhanrathore111
2
118
number of unequal triplets in array
2,475
0.699
Easy
33,958
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2834376/Python-One-Pass-O(n)-Count-invalid-triplets
class Solution: def unequalTriplets(self, nums: List[int]) -> int: from collections import Counter num_count = Counter() n_invalid_pairs = 0 n_invalid_triplets = 0 for (i, num) in enumerate(nums): n_invalid_triplets += (i-num_count.get(num, 0)) * num_count.get(num, 0) n_invalid_triplets += n_invalid_pairs n_invalid_pairs += num_count[num] num_count[num] += 1 n_nums = len(nums) return n_nums * (n_nums-1) * (n_nums-2) // 6 - n_invalid_triplets
number-of-unequal-triplets-in-array
Python One Pass O(n) Count invalid triplets
Rinnegan_Sep
1
52
number of unequal triplets in array
2,475
0.699
Easy
33,959
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2831749/Python-Simple-Python-Solution-Using-Brute-Force
class Solution: def unequalTriplets(self, nums: List[int]) -> int: result = 0 for i in range(len(nums)-2): for j in range(i+1,len(nums)-1): for k in range(j+1,len(nums)): if nums[i] != nums[j] and nums[j] != nums[k] and nums[i] != nums[k]: result = result + 1 return result
number-of-unequal-triplets-in-array
[ Python ] ✅✅ Simple Python Solution Using Brute Force🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
1
80
number of unequal triplets in array
2,475
0.699
Easy
33,960
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2849851/Python-brute-force-solution
class Solution: def unequalTriplets(self, nums: List[int]) -> int: ans = 0 for i in range(len(nums)): for j in range(i+1,len(nums)): for k in range(j+1, len(nums)): if nums[i] != nums[j] and nums[i] != nums[k] and nums[j] != nums[k]: ans += 1 return ans
number-of-unequal-triplets-in-array
Python brute force solution
StikS32
0
3
number of unequal triplets in array
2,475
0.699
Easy
33,961
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2843209/O(n)-Simple-one-pass-Math-solution-with-detailed-explanation
class Solution: def unequalTriplets(self, nums: List[int]) -> int: n = len(nums) combinations = math.comb(n, 3) for num, frq in Counter(nums).items(): if frq >= 3: combinations -= math.comb(frq, 3) if frq >= 2: combinations -= math.comb(frq, 2) * (n - frq) return(combinations)
number-of-unequal-triplets-in-array
O(n) Simple one-pass Math solution with detailed explanation
ckush
0
10
number of unequal triplets in array
2,475
0.699
Easy
33,962
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2839719/Three-loops-and-set-92-speed
class Solution: def unequalTriplets(self, nums: List[int]) -> int: ans = 0 len_nums = len(nums) for i in range(len_nums - 2): s = {nums[i]} for j in range(i + 1, len_nums - 1): if nums[j] in s: continue s.add(nums[j]) for k in range(j + 1, len_nums): if nums[k] in s: continue ans += 1 s.remove(nums[j]) return ans
number-of-unequal-triplets-in-array
Three loops and set, 92% speed
EvgenySH
0
9
number of unequal triplets in array
2,475
0.699
Easy
33,963
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2836490/Python-Solution
class Solution: def unequalTriplets(self, nums: List[int]) -> int: c=0 for i in range(len(nums)): for j in range(i+1,len(nums)): for k in range(j+1,len(nums)): if(nums[i]!=nums[j] and nums[i]!=nums[k] and nums[j]!=nums[k]): c+=1 return c
number-of-unequal-triplets-in-array
Python Solution
CEOSRICHARAN
0
9
number of unequal triplets in array
2,475
0.699
Easy
33,964
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2835397/Simple-Solution-by-python
class Solution: def unequalTriplets(self, nums: List[int]) -> int: count = 0 for i in range(0,len(nums)-2): for j in range(i+1,len(nums)-1): for k in range(j+1,len(nums)): if (nums[i]!=nums[j]) and (nums[j]!=nums[k]) and (nums[i]!=nums[k]): count +=1 return count
number-of-unequal-triplets-in-array
Simple Solution by python
pypypymi
0
9
number of unequal triplets in array
2,475
0.699
Easy
33,965
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2834252/Python3-freq-table
class Solution: def unequalTriplets(self, nums: List[int]) -> int: freq = Counter(nums) ans = prefix = 0 suffix = len(nums) for k, v in freq.items(): suffix -= v ans += prefix * v * suffix prefix += v return ans
number-of-unequal-triplets-in-array
[Python3] freq table
ye15
0
17
number of unequal triplets in array
2,475
0.699
Easy
33,966
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2833997/Easiest-python-solution-using-Combinations-(5-liner)
class Solution: def unequalTriplets(self, nums: List[int]) -> int: z=itertools.combinations(nums, 3) count=0 for i in z: if len(set(i))==3: count+=1 return count
number-of-unequal-triplets-in-array
Easiest python solution using Combinations, (5 liner)
fahim_ash
0
13
number of unequal triplets in array
2,475
0.699
Easy
33,967
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2833704/Python-brute-force
class Solution: def unequalTriplets(self, nums: List[int]) -> int: result = 0 for i in range(len(nums)-2): for j in range(i+1, len(nums)-1): for k in range(j+1, len(nums)): if nums[i] != nums[j] and nums[j] != nums[k] and nums[i] != nums[k]: result += 1 return result
number-of-unequal-triplets-in-array
Python, brute force
blue_sky5
0
6
number of unequal triplets in array
2,475
0.699
Easy
33,968
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2832446/Python-one-line-brute-force
class Solution: def unequalTriplets(self, nums: List[int]) -> int: return len([[i,j,k] for i in range(len(nums)) for j in range(i,len(nums)) for k in range(j,len(nums)) if nums[i]!=nums[j] and nums[i]!=nums[k] and nums[j]!=nums[k]])
number-of-unequal-triplets-in-array
Python, one line brute force
Leox2022
0
14
number of unequal triplets in array
2,475
0.699
Easy
33,969
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2832414/Python-easy-Solution-using-brute-force
class Solution: def unequalTriplets(self, nums: List[int]) -> int: count=0 for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i]!=nums[j]: for k in range(j+1,len(nums)): if nums[i]!=nums[k] and nums[j]!=nums[k]: count+=1 return count
number-of-unequal-triplets-in-array
Python easy Solution using brute force
Motaharozzaman1996
0
2
number of unequal triplets in array
2,475
0.699
Easy
33,970
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2832190/python-simple-iteration
class Solution: def unequalTriplets(self, nums: List[int]) -> int: c=0 n=len(nums) for i in range(n-2): for j in range(i+1,n-1): for k in range(j+1,n): if nums[i]!=nums[j] and nums[i]!=nums[k] and nums[j]!=nums[k]: c+=1 return c
number-of-unequal-triplets-in-array
python simple iteration
insane_me12
0
11
number of unequal triplets in array
2,475
0.699
Easy
33,971
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2832020/Python-Brute-Force-Solution
class Solution: def unequalTriplets(self, nums: List[int]) -> int: l = len(nums) count = 0 for i in range(l-2): for j in range(i+1,l-1): for k in range(j+1,l): if nums[i] != nums[j] and nums[j] != nums[k] and nums[k] != nums[i]: count += 1 return count
number-of-unequal-triplets-in-array
Python Brute Force Solution
saivamshi0103
0
4
number of unequal triplets in array
2,475
0.699
Easy
33,972
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2831882/Python-Easy-solution
class Solution: def unequalTriplets(self, nums: List[int]) -> int: count=0 for i in range(len(nums)): for j in range(i+1,len(nums)): for k in range(j+1,len(nums)): if nums[i]!=nums[j] and nums[j]!=nums[k] and nums[k]!=nums[i]: count+=1 return count
number-of-unequal-triplets-in-array
Python Easy solution
Vimalshetty07
0
25
number of unequal triplets in array
2,475
0.699
Easy
33,973
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2831772/Python-Bruteforce-or-Easy-to-understand
class Solution: def unequalTriplets(self, nums: List[int]) -> int: n = len(nums) trip = 0 for i in range(n): for j in range(i+1, n): for k in range(j+1, n): if (nums[i] != nums[j] and nums[i] != nums[k] and nums[j] != nums[k]): trip += 1 return trip
number-of-unequal-triplets-in-array
Python Bruteforce | Easy to understand
jubinsoni
0
9
number of unequal triplets in array
2,475
0.699
Easy
33,974
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2831689/Python3-Simple
class Solution: def unequalTriplets(self, nums: List[int]) -> int: n=len(nums) answ=0 for i in range(n): for j in range(i+1,n): for k in range(j+1,n): answ+= len({nums[i],nums[j],nums[k]})==3 return answ
number-of-unequal-triplets-in-array
Python3, Simple
Silvia42
0
36
number of unequal triplets in array
2,475
0.699
Easy
33,975
https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2831665/pythonjava-brute-force
class Solution: def unequalTriplets(self, nums: List[int]) -> int: n = len(nums) res = 0 for i in range(n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): if nums[i] != nums[j] and nums[i] != nums[k] and nums[j] != nums[k]: res += 1 return res class Solution { public int unequalTriplets(int[] nums) { int n = nums.length; int res = 0; for (int i = 0; i < n - 2; i ++) { for (int j = i + 1; j < n - 1; j ++) { for (int k = j + 1; k < n; k ++) { if (nums[i] != nums[j] &amp;&amp; nums[i] != nums[k] &amp;&amp; nums[j] != nums[k]) { res ++; } } } } return res; } }
number-of-unequal-triplets-in-array
python/java brute force
akaghosting
0
23
number of unequal triplets in array
2,475
0.699
Easy
33,976
https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2831726/Binary-Search-Approach-or-Python
class Solution(object): def closestNodes(self, root, queries): def dfs(root, arr): if not root: return dfs(root.left, arr) arr.append(root.val) dfs(root.right, arr) arr = [] dfs(root, arr) ans = [] n = len(arr) for key in queries: left, right = 0, n - 1 while right >= left: mid = (right + left) // 2 if arr[mid] == key: break elif arr[mid] > key: right = mid - 1 else: left = mid + 1 if arr[mid] == key: ans.append([arr[mid], arr[mid]]) elif arr[mid] > key: if (mid - 1) >= 0: ans.append([arr[mid - 1], arr[mid]]) else: ans.append([-1, arr[mid]]) else: if (mid + 1) < n: ans.append([arr[mid], arr[mid + 1]]) else: ans.append([arr[mid], -1]) return ans
closest-nodes-queries-in-a-binary-search-tree
Binary Search Approach | Python
its_krish_here
11
975
closest nodes queries in a binary search tree
2,476
0.404
Medium
33,977
https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2838464/Python-solution
class Solution: def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]: nums = [] def dfs(node): if node: nums.append(node.val) if node.left: dfs(node.left) if node.right: dfs(node.right) dfs(root) nums.sort() n = len(nums) ans = [] for i in range(len(queries)): left = 0 right = n - 1 while right > left: mid = (left + right)//2 if nums[mid] == queries[i]: left = right = mid elif nums[mid] > queries[i]: right = mid elif nums[mid] < queries[i]: left = mid + 1 if nums[right] == queries[i]: sub = (nums[left], nums[right]) elif nums[right] > queries[i]: sub = (nums[right-1], nums[right]) if right - 1 >= 0 else (-1, nums[right]) elif nums[right] < queries[i]: sub = (nums[left], nums[left]) if left + 1 < n else (nums[left], -1) ans.append(sub) return ans
closest-nodes-queries-in-a-binary-search-tree
Python solution
maomao1010
0
2
closest nodes queries in a binary search tree
2,476
0.404
Medium
33,978
https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2836153/Python-(Simple-DFS)
class Solution: def closestNodes(self, root, queries): ans = [] def dfs(node): if not node: return dfs(node.left) ans.append(node.val) dfs(node.right) dfs(root) res = [] n = len(ans) for i in queries: r1 = bisect.bisect_left(ans,i) if r1 == n: res.append([ans[-1],-1]) elif ans[r1] == i: res.append([i,i]) elif r1 == 0: res.append([-1,ans[0]]) else: res.append([ans[r1-1],ans[r1]]) return res
closest-nodes-queries-in-a-binary-search-tree
Python (Simple DFS)
rnotappl
0
4
closest nodes queries in a binary search tree
2,476
0.404
Medium
33,979
https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2834272/Python3-in-order-traversal
class Solution: def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]: vals = [] node = root stack = [] while node or stack: if node: stack.append(node) node = node.left else: node = stack.pop() vals.append(node.val) node = node.right ans = [] for q in queries: ans.append([-1, -1]) lo = bisect_right(vals, q)-1 if 0 <= lo: ans[-1][0] = vals[lo] hi = bisect_left(vals, q) if hi < len(vals): ans[-1][1] = vals[hi] return ans
closest-nodes-queries-in-a-binary-search-tree
[Python3] in-order traversal
ye15
0
4
closest nodes queries in a binary search tree
2,476
0.404
Medium
33,980
https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2832423/Inorder-%2B-Binary-search-or-Python-or-easy-method
class Solution: def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]: dic = {} inorder_array = [] res = [] def inorder(node): if(not node): return inorder(node.left) inorder_array.append(node.val) inorder(node.right) inorder(root) def find(target): start = 0 end = len(inorder_array) - 1 mid = 0 while(start <= end): mid = (start + end) // 2 if(inorder_array[mid] == target): #if target in the tree return [target, target] elif(inorder_array[mid] > target): end = mid - 1 else: start = mid + 1 #target not in the tree and then find the interval of this target if(inorder_array[mid] > target): if(mid != 0): return [inorder_array[mid - 1], inorder_array[mid]] else: return [-1, inorder_array[mid]] #target is at index 0 else: if(mid != len(inorder_array) - 1): return [inorder_array[mid], inorder_array[mid + 1]] else: return [inorder_array[mid], -1] #target is at last index for i in queries: res.append(find(i)) return res
closest-nodes-queries-in-a-binary-search-tree
Inorder + Binary search | Python | easy method
55337123kk3
0
16
closest nodes queries in a binary search tree
2,476
0.404
Medium
33,981
https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2831885/Inorder-Traversal
class Solution: def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]: nums = [] def in_order(node): nonlocal nums if not node: return in_order(node.left) nums.append(node.val) in_order(node.right) in_order(root) q_temp = sorted(queries) ht = {} p = 0 for i in range(len(q_temp)): temp = [-1, -1] while p < len(nums) and nums[p] <= q_temp[i]: p += 1 if p > 0 and p < len(nums): if nums[p-1] == q_temp[i] or nums[p] == q_temp[i]: temp = [nums[p-1], nums[p-1]] else: temp = [nums[p-1], nums[p]] elif p == 0: temp = [-1, nums[p]] else: if nums[p-1] == q_temp[i]: temp = [nums[p-1], nums[p-1]] else: temp = [nums[p-1], -1] ht[q_temp[i]] = temp rst = [] for n in queries: rst.append(ht[n]) return rst
closest-nodes-queries-in-a-binary-search-tree
Inorder Traversal
tiaotiao5762
0
3
closest nodes queries in a binary search tree
2,476
0.404
Medium
33,982
https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2831856/Python-Simple-Python-Solution-Using-Binary-Search
class Solution: def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]: array = [] def PrintTree(node): if node != None: PrintTree(node.left) array.append(node.val) PrintTree(node.right) PrintTree(root) result = [] for query in queries: left, right = 0, len(array) - 1 while right >= left: mid = (right + left) // 2 if array[mid] == query: break elif array[mid] > query: right = mid - 1 else: left = mid + 1 if array[mid] == query: result.append([array[mid], array[mid]]) elif array[mid] > query: if (mid - 1) >= 0: result.append([array[mid - 1], array[mid]]) else: result.append([-1, array[mid]]) else: if (mid + 1) < len(array): result.append([array[mid], array[mid + 1]]) else: result.append([array[mid], -1]) return result
closest-nodes-queries-in-a-binary-search-tree
[ Python ] ✅✅ Simple Python Solution Using Binary Search🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
27
closest nodes queries in a binary search tree
2,476
0.404
Medium
33,983
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2834516/Python-DFS-Picture-explanation-O(N)
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: n = len(roads) + 1 graph = defaultdict(list) for a, b in roads: graph[a].append(b) graph[b].append(a) def dfs(u, p): cnt = 1 for v in graph[u]: if v == p: continue cnt += dfs(v, u) if u != 0: self.ans += math.ceil(cnt / seats) # number of litters for `cnt` people to travel from node `u` to node `p` return cnt self.ans = 0 dfs(0, -1) return self.ans
minimum-fuel-cost-to-report-to-the-capital
[Python] DFS - Picture explanation - O(N)
hiepit
33
528
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,984
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2831713/Python-DFS
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: graph = defaultdict(list) for e in roads: graph[e[0]].append(e[1]) graph[e[1]].append(e[0]) visited = set() fuel = [0] def dfs(node): visited.add(node) people = 0 for n in graph[node]: if n in visited: continue p = dfs(n) people += p fuel[0] += ceil(p / seats) if not people: return 1 return people + 1 dfs(0) return fuel[0]
minimum-fuel-cost-to-report-to-the-capital
Python DFS
JSTM2022
7
220
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,985
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2839984/Python-DFS-Picture-explanation-Video-Solution-O(n)
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: m = defaultdict(list) for a,b in roads: m[a].append(b) m[b].append(a) ans = [0] def dfs(node, prev): people = 1 for i in m[node]: if i==prev: continue people+=dfs(i, node) if node!=0: ans[0]+=math.ceil(people/seats) return people dfs(0, None) return ans[0]
minimum-fuel-cost-to-report-to-the-capital
[Python] DFS - Picture explanation - Video Solution - O(n)
cheatcode-ninja
2
17
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,986
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2832516/Python-3-Easy-to-understand-DFS
class Solution: def minimumFuelCost(self, roads, seats): graph = defaultdict(set) # find the adjacency list representation for i,j in roads: graph[i].add(j) graph[j].add(i) n = len(graph) if n==0: return 0 visited = [False]*n self.ans = 0 def dfs(city): # return total number of representatives can be at city # and update answer self.ans for each city visited[city] = True repnum = 1 # initialize with 1 representative of city for neighbor in graph[city]: if not visited[neighbor]: repnum += dfs(neighbor) if city==0: return None # do not update answer for capital self.ans += math.ceil(repnum/seats) # update answer return repnum dfs(0) # execute the DFS return self.ans
minimum-fuel-cost-to-report-to-the-capital
Python 3, Easy to understand DFS
cuongmng
1
24
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,987
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2839206/Python3-Concise-and-Commented-DFS-approach
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: # we can do dfs into the leaf nodes and on return calculate the # amount of people that travel together. We will travel to the # leaves first and count the collected representatives on the # way back. During that we also continously add the fuel needed # to travel from node to next node closer to root. # make the graph for all of the roads in order to have a quick # lookup graph = collections.defaultdict(list) for start, end in roads: graph[start].append(end) graph[end].append(start) # make a instance variable to count the fuel self.fuel = 0 # start the depth first approach self.dfs(0, -1, graph, seats) # return our result return self.fuel def dfs(self, position, parent, graph, seats): # go deeper into the graph for all connections still open and # add up the representatives travelling to our node. Do not # forget to start at one representative, as our node also # has an representative representatives = 1 for target in graph[position]: # check that we do not go back in root direction if target != parent: # count the representatives coming from nodes deeper in the # tree representatives += self.dfs(target, position, graph, seats) # get the fuel costs for each car of collected representatives, but # take care to not travel further once we are at root node ( position == 0) if position > 0: # calculate the number of cars we need to go further # this is just a quick way of saying: math.ceil(representatives/2) self.fuel += (representatives + seats-1) // seats # go in the the root node direction and hand over the number of incoming # representatives return representatives
minimum-fuel-cost-to-report-to-the-capital
[Python3] - Concise and Commented DFS approach
Lucew
0
3
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,988
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2839206/Python3-Concise-and-Commented-DFS-approach
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: graph = collections.defaultdict(list) for start, end in roads: graph[start].append(end) graph[end].append(start) self.fuel = 0 self.dfs(0, -1, graph, seats) return self.fuel def dfs(self, position, parent, graph, seats): representatives = 1 for target in graph[position]: if target != parent: representatives += self.dfs(target, position, graph, seats) if position > 0: self.fuel += (representatives + seats-1) // seats return representatives
minimum-fuel-cost-to-report-to-the-capital
[Python3] - Concise and Commented DFS approach
Lucew
0
3
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,989
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2835335/My-Python-solution
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: graph = defaultdict(list) for x, y in roads: graph[x].append(y) graph[y].append(x) self.ans = 0 def dfs(i, prev, people = 1): for x in graph[i]: if x == prev: continue people += dfs(x, i) self.ans += (int(ceil(people / seats)) if i else 0) return people dfs(0, 0) return self.ans
minimum-fuel-cost-to-report-to-the-capital
My Python solution
Chiki1601
0
5
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,990
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2834288/Python3-post-order-dfs
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: graph = [[] for _ in range(len(roads)+1)] for u, v in roads: graph[u].append(v) graph[v].append(u) ans = 0 def dfs(u, p): """Return number of people going through city u.""" nonlocal ans ppl = 0 for v in graph[u]: if v != p: ppl += dfs(v, u) ppl += 1 if u: ans += (ppl + seats - 1) // seats return ppl dfs(0, -1) return ans
minimum-fuel-cost-to-report-to-the-capital
[Python3] post-order dfs
ye15
0
12
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,991
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2832330/Naive-BFS-(bottom-up)-with-degree
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: import collections node = collections.defaultdict(list) n = len(roads)+1 degree = [0] * n people = [1] * n for i, j in roads: degree[i] +=1 degree[j] +=1 node[i].append(j) node[j].append(i) ans = 0 dq = collections.deque([i for i, d in enumerate(degree) if d == 1 and i > 0]) while dq: i = dq.popleft() degree[i] = 0 for n in node[i]: if degree[n] > 0: ans += ceil(people[i]/seats) people[n] += people[i] degree[n] -= 1 if degree[n] == 1 and n > 0: dq.append(n) return ans
minimum-fuel-cost-to-report-to-the-capital
Naive BFS (bottom up) with degree
her0e1c1
0
19
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,992
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2831941/Easiest-Python-Solution
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: n = len(roads) op =[0] graph = defaultdict(list) for i,j in roads: graph[i].append(j) graph[j].append(i) vis=[0 for _ in range(n+1)] def dfs(root,pr): vis[root]=1 for nei in graph[root]: if nei!=pr: dfs(nei,root) op[0]+=(vis[nei]+seats-1)//seats vis[root]+=vis[nei] dfs(0,-1) return op[0]
minimum-fuel-cost-to-report-to-the-capital
Easiest Python Solution
prateekgoel7248
0
49
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,993
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2831886/DFS-divide-and-merge-sub-problems-O(n)
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: g = defaultdict(list) for u, v in roads: g[u].append(v) g[v].append(u) # print(f"g {g}") def dp(u, pre): liters = 0 people = 0 if u > 0: people = 1 for v in g[u]: if v == pre: continue lc, pc = dp(v, u) liters += lc people += pc if u == 0: return liters, people cars = people//seats if people % seats > 0: cars += 1 liters += cars # print(f"u {u} people {people} liters {liters}") return liters, people liters, people = dp(0, None) return liters
minimum-fuel-cost-to-report-to-the-capital
DFS, divide and merge sub problems, O(n)
goodgoodwish
0
8
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,994
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2831710/Python-or-Topological-Sort
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: n = len(roads) + 1 deg = [0] * n reps = [1] * n g = defaultdict(list) for u, v in roads: g[u].append(v) g[v].append(u) deg[u] += 1 deg[v] += 1 ones = [] for i in range(n): if deg[i] == 1: ones.append(i) ans = 0 while ones: nxt = [] for u in ones: if u == 0: continue r, reps[u] = reps[u], 0 for v in g[u]: if reps[v] == 0: continue deg[v] -= 1 ans += (r + seats - 1) // seats reps[v] += r if deg[v] == 1: nxt.append(v) ones = nxt return ans
minimum-fuel-cost-to-report-to-the-capital
Python | Topological Sort
bachelorwang
0
55
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,995
https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2831694/Python3-BFS-Graph
class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: d = defaultdict(list) q = deque([]) c = Counter() c_acc = Counter() for x, y in roads: d[x].append(y) d[y].append(x) c[x] += 1 c[y] += 1 for k, v in c.items(): if v == 1 and k!=0: q.append(k) c_acc[k] += 1 res = 0 while q: node = q.popleft() p = c_acc[node] res += ceil(p/seats) for nei in d[node]: c_acc[nei] += p c[nei] -= 1 if c[nei] == 1 and nei != 0: c_acc[nei] += 1 q.append(nei) return res
minimum-fuel-cost-to-report-to-the-capital
Python3, BFS, Graph
mike840609
0
74
minimum fuel cost to report to the capital
2,477
0.53
Medium
33,996
https://leetcode.com/problems/number-of-beautiful-partitions/discuss/2833244/Python-Top-down-DP-Clean-and-Concise-O(N-*-K)
class Solution: def beautifulPartitions(self, s: str, k: int, minLength: int) -> int: n = len(s) MOD = 10**9 + 7 def isPrime(c): return c in ['2', '3', '5', '7'] @lru_cache(None) def dp(i, k): if k == 0 and i <= n: return 1 if i >= n: return 0 ans = dp(i+1, k) # Skip if isPrime(s[i]) and not isPrime(s[i-1]): # Split ans += dp(i+minLength, k-1) return ans % MOD if not isPrime(s[0]) or isPrime(s[-1]): return 0 return dp(minLength, k-1)
number-of-beautiful-partitions
[Python] Top down DP - Clean & Concise - O(N * K)
hiepit
21
382
number of beautiful partitions
2,478
0.294
Hard
33,997
https://leetcode.com/problems/number-of-beautiful-partitions/discuss/2831907/Python-simple-DP-with-optimization
class Solution: def beautifulPartitions(self, s: str, k: int, minLength: int) -> int: n = len(s) primes = ['2', '3', '5', '7'] # pruning if k * minLength > n or s[0] not in primes or s[-1] in primes: return 0 # posible starting indexes of a new partition ids = [0] for i in range(n-1): if s[i] not in primes and s[i+1] in primes: ids.append(i+1) m = len(ids) @cache # dp(i, kk) means number of ways to partition s[ids[i]:n] into kk partitions def dp(i, kk): # kk==1: last remaining partition, needs to have length >= l if kk == 1: return 1 if ids[i]+minLength-1 <= n-1 else 0 res = 0 # iterate possible starting index of next partition for j in range(i+1, m-kk+2): if ids[j]-ids[i] >= minLength: res += dp(j, kk-1) return res % (10**9+7) return dp(0, k)
number-of-beautiful-partitions
Python simple DP with optimization
zsk99881
7
353
number of beautiful partitions
2,478
0.294
Hard
33,998
https://leetcode.com/problems/number-of-beautiful-partitions/discuss/2832142/Python3-Solution-or-DP-or-100-Faster-or-Clean-and-Concise
class Solution: def beautifulPartitions(self, S, K, M): N = len(S) P = '2357' help = lambda a, b: a not in P and b in P if not help(S[-1], S[0]) or K * M > N: return 0 dp = [1] * (N - M) mod = 10 ** 9 + 7 for j in range(1, K): dp2 = [0] * (N - M) for i in range(j * M - 1, N - M): dp2[i] = (dp2[i - 1] + dp[i - M] * int(help(S[i], S[i + 1]))) % mod dp = dp2 return dp[-1]
number-of-beautiful-partitions
✔ Python3 Solution | DP | 100% Faster | Clean & Concise
satyam2001
1
89
number of beautiful partitions
2,478
0.294
Hard
33,999