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/longest-common-subsequence/discuss/1879971/Python-or-Bottom-Up-or-O(n)-Space
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: old_row = [0 for c in range(len(text2)+1)] for i in range(len(text1)-1,-1,-1): new_row = [0 for c in range(len(text2)+1)] for j in range(len(text2)-1,-1,-1): if text1[i] == text2[j]: new_row[j] = 1 + old_row[j+1] else: new_row[j] = max(old_row[j],new_row[j+1]) old_row = new_row return old_row[0]
longest-common-subsequence
Python | Bottom Up | O(n) Space
iamskd03
0
111
longest common subsequence
1,143
0.588
Medium
17,800
https://leetcode.com/problems/longest-common-subsequence/discuss/1755136/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: def dp(i: int, j: int) -> int: if i == m: return 0 if j == n: return 0 if memo[i][j] == -1: if text1[i] == text2[j]: memo[i][j] = 1 + dp(i+1, j+1) else: memo[i][j] = max(dp(i+1, j), dp(i, j+1)) return memo[i][j] m = len(text1) n = len(text2) memo = [[-1]*n for _ in range(m)] return dp(0, 0)
longest-common-subsequence
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
0
73
longest common subsequence
1,143
0.588
Medium
17,801
https://leetcode.com/problems/longest-common-subsequence/discuss/1755136/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1) n = len(text2) dp = [[0]*(n+1) for _ in range(m+1)] for i in range(m-1, -1, -1): for j in range(n-1, -1, -1): if text1[i] == text2[j]: dp[i][j] = 1 + dp[i+1][j+1] else: dp[i][j] = max(dp[i+1][j], dp[i][j+1]) return dp[0][0]
longest-common-subsequence
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
0
73
longest common subsequence
1,143
0.588
Medium
17,802
https://leetcode.com/problems/longest-common-subsequence/discuss/1682182/Python-DP-solution-Recursion-or-Memoization-or-Top-down
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1) n = len(text2) def helper(text1,text2,m,n): if m == 0 or n == 0: return 0 else: if text1[m-1] == text2[n-1]: return 1+ helper(text1,text2,m-1,n-1) else: return max(helper(text1,text2,m-1,n),helper(text1,text2,m,n-1)) return helper(text1,text2,m,n)
longest-common-subsequence
Python DP solution [ Recursion | Memoization | Top-down ]
abhishek_1305
0
88
longest common subsequence
1,143
0.588
Medium
17,803
https://leetcode.com/problems/longest-common-subsequence/discuss/1682182/Python-DP-solution-Recursion-or-Memoization-or-Top-down
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1) n = len(text2) dp = [[0 for i in range(n+1)] for i in range(m+1)] def helper(text1,text2,m,n): for i in range(1,m+1): for j in range(1,n+1): if text1[i-1] == text2[j-1]: dp[i][j] = 1 + dp[i-1][j-1] else: dp[i][j] = max(dp[i-1][j],dp[i][j-1]) return dp[m][n] return helper(text1,text2,m,n)
longest-common-subsequence
Python DP solution [ Recursion | Memoization | Top-down ]
abhishek_1305
0
88
longest common subsequence
1,143
0.588
Medium
17,804
https://leetcode.com/problems/longest-common-subsequence/discuss/1496500/Python3-DP-O(m*n)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1) n = len(text2) dp = [[0 for _ in range(n+1)] for _ in range(m+1)] for i in range(m): for j in range(n): if text1[i] == text2[j]: dp[i+1][j+1] = dp[i][j]+1 else: dp[i+1][j+1] = max(dp[i+1][j],dp[i][j+1]) return dp[-1][-1]
longest-common-subsequence
Python3 DP O(m*n)
hemingway_23
0
52
longest common subsequence
1,143
0.588
Medium
17,805
https://leetcode.com/problems/longest-common-subsequence/discuss/1461956/python-oror-clean-oror-memoization
class Solution: def longestCommonSubsequence(self, x: str, y: str) -> int: m=len(x) n=len(y) dp=[[-1]*(n+1) for i in range(m+1)] for i in range(m+1): for j in range(n+1): if i==0 or j==0: dp[i][j]=0 elif x[i-1] == y[j-1]: dp[i][j]=1+dp[i-1][j-1] else: dp[i][j]=max(dp[i][j-1],dp[i-1][j]) print(dp[m][n]) return dp[m][n]
longest-common-subsequence
python || clean || memoization
minato_namikaze
0
167
longest common subsequence
1,143
0.588
Medium
17,806
https://leetcode.com/problems/longest-common-subsequence/discuss/1449086/Simple-Python-O(mn)-dynamic-programming-solution
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # let dp[i][j] be the length of the longest common subsequence # using the first i chars in text1 and first j chars in text2 # state transition: # dp[i][j] = dp[i-1][j-1]+1 if nums[i-1] == nums[j-1] # dp[i][j] = max(dp[i][j-1], dp[i-1][j]) otherwise m, n = len(text1), len(text2) dp = [[0]*(n+1) for _ in range(m+1)] for i in range(1, m+1): for j in range(1, n+1): if text1[i-1] == text2[j-1]: dp[i][j] = dp[i-1][j-1]+1 else: dp[i][j] = max(dp[i][j-1], dp[i-1][j]) return dp[-1][-1]
longest-common-subsequence
Simple Python O(mn) dynamic programming solution
Charlesl0129
0
225
longest common subsequence
1,143
0.588
Medium
17,807
https://leetcode.com/problems/longest-common-subsequence/discuss/1447687/Python3-solution
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: arr = [] for i in range(len(text1)+1): x = [] for j in range(len(text2)+1): if i == 0 or j == 0: x.append(0) elif text1[i-1] == text2[j-1]: x.append(arr[i-1][j-1] + 1) else: x.append(max(x[j-1], arr[i-1][j])) arr.append(x) return arr[len(text1)][len(text2)]
longest-common-subsequence
Python3 solution
EklavyaJoshi
0
70
longest common subsequence
1,143
0.588
Medium
17,808
https://leetcode.com/problems/longest-common-subsequence/discuss/1426074/Recursive-and-Bottom-up-DP-or-Python
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # recusive solution def LCS(text1, text2, len1, len2): # base condition; if len1==0 or len2==0: return 0 if memo[len1][len2]!=None: return memo[len1][len2] if text1[len1-1]==text2[len2-1]: memo[len1][len2] = 1 + LCS(text1, text2, len1-1, len2-1) return memo[len1][len2] else: memo[len1][len2] = max(LCS(text1, text2, len1, len2-1), LCS(text1, text2, len1-1, len2)) return memo[len1][len2] memo = [[None for col in range(len(text2)+1)] for row in range(len(text1)+1)] answer = LCS(text1, text2, len(text1), len(text2)) return answer
longest-common-subsequence
Recursive and Bottom-up DP | Python
anud_07
0
76
longest common subsequence
1,143
0.588
Medium
17,809
https://leetcode.com/problems/longest-common-subsequence/discuss/1426074/Recursive-and-Bottom-up-DP-or-Python
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # bottom-up dp solution; # initlization; dp = [[0 if row==0 or col==0 else None for col in range(len(text2)+1)] for row in range(len(text1)+1)] for row in range(1, len(text1)+1): for col in range(1, len(text2)+1): if text1[row-1] == text2[col-1]: dp[row][col] = 1 + dp[row-1][col-1] else: dp[row][col] = max(dp[row][col-1], dp[row-1][col]) return dp[len(text1)][len(text2)]
longest-common-subsequence
Recursive and Bottom-up DP | Python
anud_07
0
76
longest common subsequence
1,143
0.588
Medium
17,810
https://leetcode.com/problems/longest-common-subsequence/discuss/761470/Python3-DP-O(M*N)-time-beat-96-O(N)-space-beat-95
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: l1, l2 = len(text1), len(text2) dp = [0] * l1 for m in range(l2): previous, current = 0, 0 for n in range(l1): previous, current = current, dp[n] if text1[n] == text2[m]: dp[n] = previous + 1 else: if n > 0: dp[n] = max(dp[n-1], dp[n]) return dp[l1-1]```
longest-common-subsequence
Python3 DP O(M*N) time beat 96% O(N) space beat 95%
JerryZhuzq
0
87
longest common subsequence
1,143
0.588
Medium
17,811
https://leetcode.com/problems/longest-common-subsequence/discuss/634459/Clean-Python3-DP-Solution-O(mn)-Time-and-Space
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0] * (len(text1)+1) for _ in range(len(text2)+1)] for i in range(1, len(text2)+1): for j in range(1, len(text1)+1): if text1[j-1] == text2[i-1]: dp[i][j] = dp[i-1][j-1] + 1 else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) return dp[len(text2)][len(text1)]
longest-common-subsequence
Clean Python3 DP Solution - O(mn) Time and Space
schedutron
0
261
longest common subsequence
1,143
0.588
Medium
17,812
https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/891850/Python-3-or-Greedy-Two-pass-or-Explanation
class Solution: def movesToMakeZigzag(self, nums: List[int]) -> int: def greedy(nums, small_first=True): if n <= 1: return 0 ans = 0 for i in range(n-1): if small_first and nums[i] >= nums[i+1]: ans += nums[i] - (nums[i+1]-1) nums[i] = nums[i+1] - 1 elif not small_first and nums[i] <= nums[i+1]: ans += nums[i+1] - (nums[i]-1) nums[i+1] = nums[i] - 1 small_first = not small_first return ans n = len(nums) return min(greedy(nums[:], True), greedy(nums[:], False))
decrease-elements-to-make-array-zigzag
Python 3 | Greedy Two pass | Explanation
idontknoooo
1
312
decrease elements to make array zigzag
1,144
0.47
Medium
17,813
https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/2227302/PYTHON-or-100-FASTER-or-WELL-WRITTEN-or-PERFECT-CODE-or-SIMPLE-or-EXPLAINED-WELL-or
class Solution: def solve(self,arr,n,x): idx = 1 ans = 0 while idx < n: if idx == 0: idx += 1 if idx % 2 == x: if arr[idx-1] >= arr[idx]: ans += arr[idx-1] - arr[idx] + 1 arr[idx-1] = arr[idx] - 1 idx = idx-1 else: idx = idx+1 else: if arr[idx-1] <= arr[idx]: ans += arr[idx] - arr[idx - 1] + 1 arr[idx] = arr[idx-1] - 1 idx += 1 return ans def movesToMakeZigzag(self, nums: List[int]) -> int: ans1 = self.solve([x for x in nums],len(nums),0) ans2 = self.solve([x for x in nums],len(nums),1) return min(ans1,ans2)
decrease-elements-to-make-array-zigzag
PYTHON | 100% FASTER | WELL WRITTEN | PERFECT CODE | SIMPLE | EXPLAINED WELL |
reaper_27
0
94
decrease elements to make array zigzag
1,144
0.47
Medium
17,814
https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/1755483/O(n)-constant-space-Python-Solution
class Solution: def movesToMakeZigzag(self, nums: List[int]) -> int: moves_even, moves_odd = 0, 0 ldec_even, ldec_odd = 0, 0 if len(nums) > 1: moves_even += max(0, nums[1] - nums[0] + 1) ldec_even = moves_even for i, num in enumerate(nums[1:], 1): if i % 2 == 0: # even moves_even += max(0, nums[i-1] - num - ldec_even + 1) if i+1 < len(nums): ldec_even = max(0, nums[i+1] - num + 1) moves_even += ldec_even else: # odd moves_odd += max(0, nums[i-1] - num - ldec_odd + 1) if i+1 < len(nums): ldec_odd = max(0, nums[i+1] - num + 1) moves_odd += ldec_odd return min(moves_even, moves_odd)
decrease-elements-to-make-array-zigzag
O(n), constant space Python Solution
Paindefender
0
135
decrease elements to make array zigzag
1,144
0.47
Medium
17,815
https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/1368058/Clean-comments-try-make-alternate-elements-less-neighbours-(evens-or-odds)
class Solution: def movesToMakeZigzag1(self, nums: List[int]) -> int: # try to make alternate less than left and right.. def alternateLess(start, nums): # returns cost cost = 0 for i in range(start, len(nums), 2): # 1. make me smaller than LEFT adjacent if i > 0 and nums[i-1] <= nums[i]: change = nums[i] - nums[i-1] + 1 # +1 as strict < not <= cost += change nums[i] -= change # 2. do same for right neighbour if i < len(nums)-1 and nums[i+1] <= nums[i]: change = nums[i] - nums[i+1] + 1 cost += change nums[i] -= change return cost return min(alternateLess(0, nums[:]), alternateLess(1,nums[:])) # cleaner and extensible to just take change to min(neighbours) def movesToMakeZigzag(self, nums: List[int]) -> int: # try to make alternate less than left and right.. def alternateLess(start): # returns cost cost = 0 for i in range(start, len(nums), 2): change = 0 # 1. make me smaller than LEFT adjacent if i > 0 and nums[i-1] <= nums[i]: left_change = nums[i] - nums[i-1] + 1 change = max(left_change, change) # 2. do same for right neighbour if i < len(nums)-1 and nums[i+1] <= nums[i]: right_change = nums[i] - nums[i+1] + 1 change = max(right_change, change) cost += change return cost return min(alternateLess(0), alternateLess(1)) """ tests [1,2,3] [9,6,1,6,2] [1] [1,2] [2,1,2] """
decrease-elements-to-make-array-zigzag
Clean comments try make alternate elements < neighbours (evens or odds)
yozaam
0
99
decrease elements to make array zigzag
1,144
0.47
Medium
17,816
https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/1167161/Python3-linear-sweep
class Solution: def movesToMakeZigzag(self, nums: List[int]) -> int: ans = [0, 0] for i in range(len(nums)): val = 0 if i: val = max(val, nums[i] - nums[i-1] + 1) if i+1 < len(nums): val = max(val, nums[i] - nums[i+1] + 1) ans[i&amp;1] += val return min(ans)
decrease-elements-to-make-array-zigzag
[Python3] linear sweep
ye15
0
105
decrease elements to make array zigzag
1,144
0.47
Medium
17,817
https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/350755/Solution-in-Python-3-(beats-100)-(-O(1)-space-)-(-O(n)-speed-)
class Solution: def movesToMakeZigzag(self, nums: List[int]) -> int: L, m, M = len(nums), 0, 0 for i in range(1,L-1,2): t = min(nums[i-1],nums[i+1]) if nums[i] >= t: m += nums[i] - t + 1 if i == L - 3 and nums[-1] >= nums[-2]: m += nums[-1] - nums[-2] + 1 for i in range(2,L-1,2): t = min(nums[i-1],nums[i+1]) if nums[i] >= t: M += nums[i] - t + 1 if nums[0] >= nums[1]: M += nums[0] - nums[1] + 1 if (i == L - 3 or i == 1) and nums[-1] >= nums[-2]: M += nums[-1] - nums[-2] + 1 return min(m,M) - Junaid Mansuri
decrease-elements-to-make-array-zigzag
Solution in Python 3 (beats 100%) ( O(1) space ) ( O(n) speed )
junaidmansuri
0
88
decrease elements to make array zigzag
1,144
0.47
Medium
17,818
https://leetcode.com/problems/binary-tree-coloring-game/discuss/797574/Python-3-or-DFS-or-One-pass-and-Three-pass-or-Explanation
class Solution: def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool: first = None def count(node): nonlocal first total = 0 if node: if node.val == x: first = node total += count(node.left) + count(node.right) + 1 return total s = count(root) # Get total number of nodes, and x node (first player's choice) l = count(first.left) # Number of nodes on left branch r = count(first.right) # Number of nodes on right branch p = s-l-r-1 # Number of nodes on parent branch (anything else other than node, left subtree of node or right subtree of node) return l+r < p or l+p < r or r+p < l
binary-tree-coloring-game
Python 3 | DFS | One pass & Three pass | Explanation
idontknoooo
13
501
binary tree coloring game
1,145
0.515
Medium
17,819
https://leetcode.com/problems/binary-tree-coloring-game/discuss/797574/Python-3-or-DFS-or-One-pass-and-Three-pass-or-Explanation
class Solution: def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool: l = r = 0 def count(node): nonlocal l, r total = 0 if node: l_count, r_count = count(node.left), count(node.right) if node.val == x: l, r = l_count, r_count total += l_count + r_count + 1 return total s = count(root) p = s-l-r-1 return l+r < p or l+p < r or r+p < l
binary-tree-coloring-game
Python 3 | DFS | One pass & Three pass | Explanation
idontknoooo
13
501
binary tree coloring game
1,145
0.515
Medium
17,820
https://leetcode.com/problems/binary-tree-coloring-game/discuss/1167266/Python3-post-order-dfs
class Solution: def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool: def fn(node): """Return size of subtree rooted at node.""" if not node: return 0 left, right = fn(node.left), fn(node.right) if node.val == x: cnt[0], cnt[1] = left, right return 1 + left + right cnt = [0, 0] fn(root) return max(max(cnt), n-1-sum(cnt)) > n//2
binary-tree-coloring-game
[Python3] post-order dfs
ye15
0
52
binary tree coloring game
1,145
0.515
Medium
17,821
https://leetcode.com/problems/binary-tree-coloring-game/discuss/960376/python3-overcomplicating-the-problem!
class Solution: def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool: # solution below doesn't use all the info provided # namely, total number of nodes # do a simple dfs to capture left, right nodes from target x # this gives you p1, p2 and p3 # O(N) time and O(H) tree height call space def rcrs(node) -> int: if not node: return 0 lt = rcrs(node.left) rt = rcrs(node.right) if node.val == x: self.cnts.extend([lt,rt]) return lt + rt + 1 self.cnts = [] rcrs(root) self.cnts.append( n - 1 - sum(self.cnts) ) return (2*max(self.cnts) - sum(self.cnts)) > 1 def btreeGameWinningMove1(self, root: TreeNode, n: int, x: int) -> bool: # draw tree diagrams to find the pattern # for any given node, there are three potential paths away # Pa, Pb, Pc == (up, left, right) # start from chosen X node, find length of path in directions A,B,C # if there exists a value P1 > (P2 + P3 + 1), then guaranteed win # or P1 - P2 - P3 > 1 # max(all) - (sum(all) - max(all)) > 1 # 2*max(all) - sum(all) > 1 # traverse tree from root, create parent dict to allow upward travel # then start from chosen X and find P_up, P_left, P_right # take the max value from paths, if > other two + 1, return true else false # recursive dfs helper function # repeat three times with each of x.left, x.right, x.prnt # O(N) time and space d, self.start = {}, None def rcrs_dn(node, prnt) -> None: if not node: return if node.val == x: self.start = node d[node] = prnt rcrs_dn(node.left, node) rcrs_dn(node.right, node) rcrs_dn(root, None) def dfs_away(node, last) -> int: if not node: return 0 cnt = 1 if node.left and (node.left is not last): cnt += dfs_away(node.left, node) if node.right and (node.right is not last): cnt += dfs_away(node.right, node) if d[node] and (d[node] is not last): cnt += dfs_away(d[node], node) return cnt p1 = dfs_away(self.start.left, self.start) p2 = dfs_away(self.start.right, self.start) p3 = dfs_away(d[self.start], self.start) return ( 2*max(p1, p2, p3) - (p1 + p2 + p3) ) > 1
binary-tree-coloring-game
python3 - overcomplicating the problem!
dachwadachwa
0
56
binary tree coloring game
1,145
0.515
Medium
17,822
https://leetcode.com/problems/longest-chunked-palindrome-decomposition/discuss/350711/Close-to-O(n)-Python-Rabin-Karp-Algorithm-with-two-pointer-technique-with-explanation-(~40ms)
class Solution: def longestDecomposition(self, text: str) -> int: # Used a prime number generator on the internet to grab a prime number to use. magic_prime = 32416189573 # Standard 2 pointer technique variables. low = 0 high = len(text) - 1 # These are the hash tracking variables. cur_low_hash = 0 cur_high_hash = 0 cur_hash_length = 0 # This is the number of parts we've found, i.e. the k value we need to return. k = 0 while low < high: # To put the current letter onto our low hash (i.e. the one that goes forward from # the start of the string, we shift up the existing hash by multiplying by the base # of 26, and then adding on the new character by converting it to a number from 0 - 25. cur_low_hash *= 26 # Shift up by the base of 26. cur_low_hash += ord(text[low]) - 97 # Take away 97 so that it's between 0 and 25. # The high one, i.e. the one backwards from the end is a little more complex, as we want the # hash to represent the characters in forward order, not backwards. If we did the exact same # thing we did for low, the string abc would be represented as cba, which is not right. # Start by getting the character's 0 - 25 number. high_char = ord(text[high]) - 97 # The third argument to pow is modular arithmetic. It says to give the answer modulo the # magic prime (more on that below). Just pretend it isn't doing that for now if it confuses you. # What we're doing is making an int that puts the high character at the top, and then the # existing hash at the bottom. cur_high_hash = (high_char * pow(26, cur_hash_length, magic_prime)) + cur_high_hash # Mathematically, we can safely do this. Impressive, huh? I'm not going to go into here, but # I recommend studying up on modular arithmetic if you're confused. # The algorithm would be correct without doing this, BUT it'd be very slow as the numbers could # become tens of thousands of bits long. The problem with that of course is that comparing the # numbers would no longer be O(1) constant. So we need to keep them small. cur_low_hash %= magic_prime cur_high_hash %= magic_prime # And now some standard 2 pointer technique stuff. low += 1 high -= 1 cur_hash_length += 1 # This piece of code checks if we currently have a match. # This is actually probabilistic, i.e. it is possible to get false positives. # For correctness, we should be verifying that this is actually correct. # We would do this by ensuring the characters in each hash (using # the low, high, and length variables we've been tracking) are # actually the same. But here I didn't bother as I figured Leetcode # would not have a test case that broke my specific prime. if cur_low_hash == cur_high_hash: k += 2 # We have just added 2 new strings to k. # And reset our hashing variables. cur_low_hash = 0 cur_high_hash = 0 cur_hash_length = 0 # At the end, there are a couple of edge cases we need to address.... # The first is if there is a middle character left. # The second is a non-paired off string in the middle. if (cur_hash_length == 0 and low == high) or cur_hash_length > 0: k += 1 return k
longest-chunked-palindrome-decomposition
Close to O(n) Python, Rabin Karp Algorithm with two pointer technique with explanation (~40ms)
Hai_dee
33
2,400
longest chunked palindrome decomposition
1,147
0.597
Hard
17,823
https://leetcode.com/problems/longest-chunked-palindrome-decomposition/discuss/2567646/Python3-or-Recursive-DP
class Solution: def longestDecomposition(self, text: str) -> int: n=len(text)-1 dp=[[-1 for i in range(n+1)] for j in range(n+1)] def dfs(start,end): if start>end: return 0 if dp[start][end]!=-1: return dp[start][end] best=1 l,r=start,end mid=(r+l)//2 while r>mid: chunk=end-r+1 if text[l:l+chunk]==text[r:end+1]: val=dfs(l+chunk,r-1)+2 best=max(best,val) r-=1 dp[start][end]=best return dp[start][end] return dfs(0,n)
longest-chunked-palindrome-decomposition
[Python3] | Recursive DP
swapnilsingh421
0
10
longest chunked palindrome decomposition
1,147
0.597
Hard
17,824
https://leetcode.com/problems/longest-chunked-palindrome-decomposition/discuss/1706178/Python3-solution
class Solution: def longestDecomposition(self, text: str) -> int: i, j = 0, len(text)-1 count = 0 left = '' right = '' while i <= j: left += text[i] right = text[j] + right if i == j: break else: if left == right: left = '' right = '' count += 2 i += 1 j -= 1 if left != '' and right != '': count += 1 return count
longest-chunked-palindrome-decomposition
Python3 solution
EklavyaJoshi
0
42
longest chunked palindrome decomposition
1,147
0.597
Hard
17,825
https://leetcode.com/problems/longest-chunked-palindrome-decomposition/discuss/1504109/Python3-Solution-with-using-two-pointers
class Solution: def longestDecomposition(self, text: str) -> int: begin, end = 0, len(text) - 1 count = 0 left, right = [], [] for i in range(len(text)): left.append(text[i]) right.append(text[len(text) - i - 1]) if left == list(reversed(right)): count += 1 left, right = [], [] return count
longest-chunked-palindrome-decomposition
[Python3] Solution with using two-pointers
maosipov11
0
66
longest chunked palindrome decomposition
1,147
0.597
Hard
17,826
https://leetcode.com/problems/longest-chunked-palindrome-decomposition/discuss/1421302/Python-oror-2-pointers-oror-28-ms
class Solution: def longestDecomposition(self, s: str) -> int: n=len(s) a,b=0,0 x,y=n-1,n-1 k=0 temp_b,temp_x=0,10 while b<x: if s[a:b+1]==s[x:y+1]: k+=2 temp_b,temp_x=b,x a=b+1 b=a y=x-1 x=y else: b+=1 x-=1 return k if temp_b+1==temp_x else k+1
longest-chunked-palindrome-decomposition
Python || 2 pointers || 28 ms
ketan_raut
0
55
longest chunked palindrome decomposition
1,147
0.597
Hard
17,827
https://leetcode.com/problems/longest-chunked-palindrome-decomposition/discuss/1167294/Python3-greedy
class Solution: def longestDecomposition(self, text: str) -> int: ii = i = ans = 0 jj = j = len(text)-1 while i < j: if text[ii:i+1] == text[j:jj+1]: ans += 2 ii, jj = i+1, j-1 # reset anchor ptr i, j = i+1, j-1 return ans + int(ii <= jj)
longest-chunked-palindrome-decomposition
[Python3] greedy
ye15
0
58
longest chunked palindrome decomposition
1,147
0.597
Hard
17,828
https://leetcode.com/problems/longest-chunked-palindrome-decomposition/discuss/376404/Python-Regex-solution
class Solution: def longestDecomposition(self, text: str) -> int: import re groups = 0 while True: match = re.fullmatch(r'(\w+?).*\1', text) if match: groups += 2 subend = match.end(1) text = text[subend:-subend] else: return groups + 1 if text else groups
longest-chunked-palindrome-decomposition
[Python] Regex solution
robbyg
0
80
longest chunked palindrome decomposition
1,147
0.597
Hard
17,829
https://leetcode.com/problems/day-of-the-year/discuss/449866/Python-3-Four-liner-Simple-Solution
class Solution: def dayOfYear(self, date: str) -> int: y, m, d = map(int, date.split('-')) days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if (y % 400) == 0 or ((y % 4 == 0) and (y % 100 != 0)): days[1] = 29 return d + sum(days[:m-1])
day-of-the-year
Python 3 - Four liner - Simple Solution
mmbhatk
30
1,700
day of the year
1,154
0.501
Easy
17,830
https://leetcode.com/problems/day-of-the-year/discuss/647517/simple-of-simple
class Solution: def dayOfYear(self, date: str) -> int: year, month, day = date.split('-') year = int(year) month = int(month) day = int(day) isleapYear = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 cnt = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if isleapYear: cnt[1] = cnt[1] + 1 ans = 0 for i in range(month-1): ans += cnt[i] return ans + day
day-of-the-year
simple of simple
seunggabi
3
115
day of the year
1,154
0.501
Easy
17,831
https://leetcode.com/problems/day-of-the-year/discuss/1069700/python-3-solution
class Solution: def dayOfYear(self, date: str) -> int: b = [31,28,31,30,31,30,31,31,30,31,30,31] a = 0 date = date.split("-") date[1] = int(date[1]) if int(date[0]) % 4 == 0 and int(date[1]) > 2: if int(date[0]) % 4 == 0 and int(date[0]) % 100 != 0: b[1] = 29 elif int(date[0]) % 4 == 0 and int(date[0]) % 400 == 0: b[1] = 29 else: pass a = sum(b[0:date[1]-1]) a += int(date[2]) return a
day-of-the-year
python 3 solution
Jingtian_ZHANG
2
132
day of the year
1,154
0.501
Easy
17,832
https://leetcode.com/problems/day-of-the-year/discuss/355888/Solution-in-Python-3-(beats-100)-(two-line-and-one-line-solutions)-(my-first-time-in-a-contest!)
class Solution: def dayOfYear(self, d: str) -> int: D, [y,m,d] = [31,28,31,30,31,30,31,31,30,31,30,31], [int(i) for i in d.split("-")] return sum(D[:(m-1)]) + d + ((m > 2) and (((y % 4 == 0) and (y % 100 != 0)) or (y % 400 == 0)))
day-of-the-year
Solution in Python 3 (beats 100%) (two line and one line solutions) (my first time in a contest!)
junaidmansuri
2
208
day of the year
1,154
0.501
Easy
17,833
https://leetcode.com/problems/day-of-the-year/discuss/2405909/Python-Easy-Solution
class Solution: def dayOfYear(self, date: str) -> int: map={ 0:0, 1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31 } year=int(date.split('-')[0]) month=date.split('-')[1] day=date.split('-')[2] days=0 for x in range(0,int(month)): days+=map.get(int(x)) if not year % 400: is_leap_year = True elif not year % 100: is_leap_year = False elif not year % 4: is_leap_year = True else: is_leap_year = False if is_leap_year and int(month)>2: return days+int(day)+1 else: return days+int(day)
day-of-the-year
Python - Easy Solution
mdshahbaz204
1
77
day of the year
1,154
0.501
Easy
17,834
https://leetcode.com/problems/day-of-the-year/discuss/1225256/Python3-simple-and-easy-to-understandable-solution
class Solution: def dayOfYear(self, date: str) -> int: year, mon, day = map(int, date.split('-')) days = 0 def is_leap(year): if year % 4 == 0 or (year % 100 == 0 and year % 400 == 0): return True return False leap = is_leap(year) for i in range(1,mon): if i in [1,3,5,7,8,10]: days += 31 elif i in [4,6,9,11]: days += 30 else: days += 28 days += day if leap: if mon > 2: return days + 1 return days
day-of-the-year
Python3 simple and easy to understandable solution
EklavyaJoshi
1
79
day of the year
1,154
0.501
Easy
17,835
https://leetcode.com/problems/day-of-the-year/discuss/1225256/Python3-simple-and-easy-to-understandable-solution
class Solution: def dayOfYear(self, date: str) -> int: year, mon, day = map(int, date.split('-')) days = 0 def is_leap(year): if year % 4 == 0 or (year % 100 == 0 and year % 400 == 0): return True return False leap = is_leap(year) months = [31,28,31,30,31,30,31,31,30,31,30] days = sum(months[:mon-1]) + day if leap: if mon > 2: return days + 1 return days
day-of-the-year
Python3 simple and easy to understandable solution
EklavyaJoshi
1
79
day of the year
1,154
0.501
Easy
17,836
https://leetcode.com/problems/day-of-the-year/discuss/2753832/1154.-Day-of-the-Year-or-Python3-or-Time-and-Space-Complexity-O(1)-or-Python
class Solution(object): def dayOfYear(self, date): """ :type date: str :rtype: int """ month=int(date[5:7]) day=int(date[8:]) year=int(date[:4]) total=0 # here loop doesn't affect the time complexity because it runs for only 12 times or might be less for i in range(1,month): if i<=7: # odd months like 1,3,5 and 7 are of 31 days if i%2!=0: total+=31 # Finding leap year elif year%4==0 and i==2: if year%100==0: if year%400==0: total+=29 else: total+=28 else: total+=29 elif year%4!=0 and i==2: total+=28 # End of finding leap year else: total+=30 else: # even months like 8,10 and 12 are of 31 days if i%2==0: total+=31 else: total+=30 return total+day
day-of-the-year
1154. Day of the Year | Python3 | Time and Space Complexity O(1) | Python
Khalilullah_Nohri
0
3
day of the year
1,154
0.501
Easy
17,837
https://leetcode.com/problems/day-of-the-year/discuss/2600506/Efficient-Python-Six-liner-Solution
class Solution: def dayOfYear(self, date: str) -> int: numDaysPassed = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] year, month, day = int(date[0:4]), int(date[5:7]), int(date[8:10]) if year % 4 == 0 and month > 2: if year % 100 != 0 or year % 400 == 0: return numDaysPassed[month - 1] + day + 1 return numDaysPassed[month - 1] + day
day-of-the-year
Efficient Python Six-liner Solution
kcstar
0
26
day of the year
1,154
0.501
Easy
17,838
https://leetcode.com/problems/day-of-the-year/discuss/2447862/python-solution
class Solution: def dayOfYear(self, date: str) -> int: ans = 0 d = date.split("-") year = int(d[0]) if year%100==0: if year%400==0: c = 1 else: c = 0 else: if year%4==0: c = 1 else: c = 0 d = d[1:] if c == 1: dy = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] ans = dy[int(d[0])-1] + int(d[1]) return ans if c == 0: dy = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] ans = dy[int(d[0])-1] + int(d[1]) return ans
day-of-the-year
python solution
rohansardar
0
41
day of the year
1,154
0.501
Easy
17,839
https://leetcode.com/problems/day-of-the-year/discuss/2427697/Checking-leap-year-with-dictionary-and-string-slicing-Python
class Solution: def dayOfYear(self, date: str) -> int: mth = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} def helper(year): if (year % 400 == 0) and (year % 100 == 0): return True elif (year % 4 ==0) and (year % 100 != 0): return True return False dd = date.split('-') year = int(dd[0]) month = int(dd[1]) dt = int(dd[2]) s = sum(list(mth[k] for k in range(1, month))) if month > 2: s = s + 1 if helper(year) else s return dt + s
day-of-the-year
Checking leap year with dictionary and string slicing Python
ankurbhambri
0
19
day of the year
1,154
0.501
Easy
17,840
https://leetcode.com/problems/day-of-the-year/discuss/2407150/Python-3-lines-no-libraries-97-Faster
class Solution: def dayOfYear(self, date: str) -> int: year, month, day = map(int, date.split('-')) leap = year % 400 == 0 or year % 100 != 0 and year % 4 == 0 return sum((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[:month-1]) + day + (month > 2) * leap
day-of-the-year
Python 3-lines no libraries 97% Faster
blest
0
31
day of the year
1,154
0.501
Easy
17,841
https://leetcode.com/problems/day-of-the-year/discuss/2395424/python-leap-year-definition
class Solution: def dayOfYear(self, date: str) -> int: d={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31} year=int(date[:4]) if year%4==0: if year%100==0: if year%400==0: d[2]=29 else: d[2]=29 month=int(date[5:7]) day=int(date[8:]) ans=0 for i in range(1,month+1): ans+=d[i] return ans-(d[month]-day)
day-of-the-year
python - leap year definition
sunakshi132
0
27
day of the year
1,154
0.501
Easy
17,842
https://leetcode.com/problems/day-of-the-year/discuss/2045929/Python-oneliner
class Solution: def dayOfYear(self, date: str) -> int: import time return time.strptime(date, '%Y-%m-%d')[7]
day-of-the-year
Python oneliner
StikS32
0
73
day of the year
1,154
0.501
Easy
17,843
https://leetcode.com/problems/day-of-the-year/discuss/1913838/Python-solution-faster-than-99.84
class Solution: def dayOfYear(self, date: str) -> int: date = date.split("-") y = int(date[0]) m = int(date[1]) d = int(date[2]) leap = False if y % 400 == 0 or (y % 4 == 0 and y % 100 != 0): leap = True res = 0 for i in range(1, m): if i in [1, 3, 5, 7, 8, 10, 12]: res += 31 elif i == 2: if leap == True: res += 29 else: res += 28 else: res += 30 res += d return res
day-of-the-year
Python solution faster than 99.84%
alishak1999
0
100
day of the year
1,154
0.501
Easy
17,844
https://leetcode.com/problems/day-of-the-year/discuss/1889234/Python-Simple-and-clean!
class Solution: def dayOfYear(self, date): months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] y, m, d = map(int, date.split("-")) months[1] += int((y % 4 == 0 and y % 100 != 0) or y % 400 == 0) return sum(months[:m-1]) + d
day-of-the-year
Python - Simple and clean!
domthedeveloper
0
67
day of the year
1,154
0.501
Easy
17,845
https://leetcode.com/problems/day-of-the-year/discuss/1814415/python-3-simple-solution-95-speed-90-memory
class Solution: def dayOfYear(self, date: str) -> int: year, month, day = map(int, date.split('-')) leap = year % 400 == 0 or (year % 4 == 0 and year % 100) prefix = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] return day + prefix[month-1] + (leap and month > 2)
day-of-the-year
python 3, simple solution, 95% speed, 90% memory
dereky4
0
127
day of the year
1,154
0.501
Easy
17,846
https://leetcode.com/problems/day-of-the-year/discuss/1800963/1-Line-Python-Solution-oror-90-Faster-oror-Memory-less-than-93
class Solution: def dayOfYear(self, date1: str) -> int: return date.fromisoformat(date1).strftime('%j').lstrip('0')
day-of-the-year
1-Line Python Solution || 90% Faster || Memory less than 93%
Taha-C
0
57
day of the year
1,154
0.501
Easy
17,847
https://leetcode.com/problems/day-of-the-year/discuss/1800963/1-Line-Python-Solution-oror-90-Faster-oror-Memory-less-than-93
class Solution: def dayOfYear(self, date1: str) -> int: return date.fromisoformat(date1).timetuple().tm_yday
day-of-the-year
1-Line Python Solution || 90% Faster || Memory less than 93%
Taha-C
0
57
day of the year
1,154
0.501
Easy
17,848
https://leetcode.com/problems/day-of-the-year/discuss/1536153/python3-one-line-solution
class Solution: def dayOfYear(self, date: str) -> int: return int(datetime.date.fromisoformat(date).strftime('%j'))
day-of-the-year
python3 one line solution
G0udini
0
126
day of the year
1,154
0.501
Easy
17,849
https://leetcode.com/problems/day-of-the-year/discuss/1426515/Python3-No-Library-Faster-Than-92.66-Memory-Less-Than-95.87
class Solution: def dayOfYear(self, date: str) -> int: daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def leap(year): return 1 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else 0 month, days = date[5:7], 0 for i in range(1, int(month)): days += daysInMonth[i - 1] if int(month) > 2: if leap(int(date[:4])): days += 1 return days + int(date[-2:])
day-of-the-year
Python3 No Library, Faster Than 92.66%, Memory Less Than 95.87%
Hejita
0
68
day of the year
1,154
0.501
Easy
17,850
https://leetcode.com/problems/day-of-the-year/discuss/990190/Python-or-Add-days-per-Month
class Solution: def is_leap(self, year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def dayOfYear(self, date: str) -> int: year, month, day = map(int, date.split('-')) months_to_days = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] months_to_days[2] += self.is_leap(year) day_of_year = sum(months_to_days[i] for i in range(1, month)) + day return day_of_year
day-of-the-year
Python | Add days per Month
leeteatsleep
0
99
day of the year
1,154
0.501
Easy
17,851
https://leetcode.com/problems/day-of-the-year/discuss/356179/Python-3
class Solution: di = {1:0, 2:31, 3:59, 4:90, 5:120, 6:151, 7:181, 8:212, 9:243, 10:273, 11:304, 12:334} def dayOfYear(self, date: str) -> int: y, m, d = [int(i) for i in date.split("-")] a = self.di[m] + int(d) if (m > 2) and ((not y % 4) and (y % 100 or not y % 400)): a += 1 return a
day-of-the-year
Python 3
slight_edge
0
173
day of the year
1,154
0.501
Easy
17,852
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/822515/Python-3-or-DP-or-Explanation
class Solution: def numRollsToTarget(self, d: int, f: int, target: int) -> int: if d*f < target: return 0 # Handle special case, it speed things up, but not necessary elif d*f == target: return 1 # Handle special case, it speed things up, but not necessary mod = int(10**9 + 7) dp = [[0] * (target+1) for _ in range(d+1)] for j in range(1, min(f+1, target+1)): dp[1][j] = 1 for i in range(2, d+1): for j in range(1, target+1): for k in range(1, f+1): if j - k >= 0: dp[i][j] += dp[i-1][j-k] dp[i][j] %= mod return dp[-1][-1]
number-of-dice-rolls-with-target-sum
Python 3 | DP | Explanation
idontknoooo
12
1,400
number of dice rolls with target sum
1,155
0.536
Medium
17,853
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/1781091/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: modulo = 10**9+7 @lru_cache(None) def dp(dice_left: int, target_left: int) -> int: if dice_left == 0: if target_left == 0: return 1 return 0 res = 0 for i in range(1, k+1): res += dp(dice_left-1, target_left-i) res %= modulo return res % modulo return dp(n, target)
number-of-dice-rolls-with-target-sum
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
5
435
number of dice rolls with target sum
1,155
0.536
Medium
17,854
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/1781091/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: modulo = 10**9+7 dp = [[0]*(target+1) for _ in range(n+1)] dp[0][0] = 1 for dice_left in range(1, n+1): for target_left in range(1, target+1): for i in range(1, min(k, target_left)+1): dp[dice_left][target_left] += dp[dice_left-1][target_left-i] dp[dice_left][target_left] %= modulo return dp[n][target]
number-of-dice-rolls-with-target-sum
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
5
435
number of dice rolls with target sum
1,155
0.536
Medium
17,855
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2652613/Python3!-As-short-as-it-gets!-T%3A96-O(n*target)
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: MOD = 1000 * 1000 * 1000 + 7 dp = defaultdict(int) dp[0] = 1 for c in range(n): sm = defaultdict(int) for i in range(target+1): sm[i] = sm[i-1] + dp[i] for i in range(target+1): dp[i] = (sm[i-1] - sm[i-k-1]) % MOD return dp[target]
number-of-dice-rolls-with-target-sum
😎Python3! As short as it gets! [T:96%] O(n*target)
aminjun
4
194
number of dice rolls with target sum
1,155
0.536
Medium
17,856
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648317/Python3-Math-Solution-or-Beats-98-and-98
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: # set up the variables t = target - n ret = 0 l = 0 m = 10**9 + 7 # polynomial multiplication while l*k <= t: r = t - l*k # find the correct power of the second term # first coefficient | second coefficient ret = (ret + ((-1)**l) * comb(n,l) * comb(r+n-1,n-1)) % m l += 1 return ret
number-of-dice-rolls-with-target-sum
Python3 Math Solution | Beats 98% and 98%
FlyawayTester85
3
173
number of dice rolls with target sum
1,155
0.536
Medium
17,857
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/1473889/PyPy3-Recursion-with-memoization-w-comments
class Solution: def __init__(self): self.t = dict() # Used for Memoization return def numRollsToTarget(self, d: int, f: int, target: int) -> int: # Base Case: Check if the current target is achievable by # the current number of dice given f faces if d*f < target: return 0 # Base Case: Check when dice is equal to 1, can the # target be achieved by the given f faces if d==1: if 0 < target <= f: return 1 else: return 0 # Make key key = (d, target) # For the current no. of dices, check all possible ways # the to achieve target, only if the key doesn't exist if key not in self.t: # Init count = 0 # For each possible value of face, subtract the face # value from the target and then call again the same # function with one less dice. for i in range(1,f+1): count += self.numRollsToTarget(d-1, f, target-i) # Memoization self.t[key] = count return self.t[key] % ((10**9)+7) # return the current value
number-of-dice-rolls-with-target-sum
[Py/Py3] Recursion with memoization w/ comments
ssshukla26
3
360
number of dice rolls with target sum
1,155
0.536
Medium
17,858
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649429/86.7-Faster-Solution-oror-DP
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: mod = 10**9+7 dp = [[0]*(target + 1) for _ in range(n + 1)] dp[0][0] = 1 if target < 1 or target > n*k: return 0 for x in range(1, n + 1): for y in range(1, k + 1): for z in range(y, target + 1): dp[x][z] = (dp[x][z] + dp[x-1][z-y]) % mod return dp[-1][-1]
number-of-dice-rolls-with-target-sum
86.7% Faster Solution || DP
namanxk
2
75
number of dice rolls with target sum
1,155
0.536
Medium
17,859
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648600/python-dp-solution
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: def func(i,n,k,tr,dic): if i==n and tr==0: return 1 if i>=n or tr<=0: return 0 if (i,tr) in dic: return dic[(i,tr)] sm=0 for j in range(1,k+1): # print(i+1,tr-j) sm+=func(i+1,n,k,tr-j,dic) dic[(i,tr)]=sm return sm return func(0,n,k,target,{})%1000000007
number-of-dice-rolls-with-target-sum
python dp solution
shubham_1307
2
33
number of dice rolls with target sum
1,155
0.536
Medium
17,860
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/1645657/Python3-%3A-DP-95-faster
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: @lru_cache(maxsize=None) def recur(n, t): if t <= 0 or t > n*k: return 0 if n==1: if t <=k: return 1 else: return 0 count = 0 for i in range(1, k+1): count+=recur(n-1, t-i) return count return recur(n,target) % ((10**9) + 7)
number-of-dice-rolls-with-target-sum
Python3 : DP , 95% faster
user8266H
2
266
number of dice rolls with target sum
1,155
0.536
Medium
17,861
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2651298/python3-short-solution-using-%40cache
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: @cache def check(t,s): if t==0 and s==target: return 1 elif t==0: return 0 return sum([check(t-1,s+i) for i in range(1,k+1)]) return check(n,0)%(10**9+7) #using dictionary for memoization dp={} def check(t,s): if t==0 and s==target: return 1 elif t==0: return 0 if (t,s) in dp: return dp[(t,s)] dp[(t,s)]=sum([check(t-1,s+i) for i in range(1,k+1)]) return dp[(t,s)] return check(n,0)%(10**9+7)
number-of-dice-rolls-with-target-sum
python3 short solution using @cache
benon
1
87
number of dice rolls with target sum
1,155
0.536
Medium
17,862
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2650096/Python-DP-Solution-with-Time%3A-O(n-*-k-*-target)-Space%3A-O(target)
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: prev = [0] # number of ways to get targets [0, 1 ... target] with the ( current number of dice - 1 ) prev.extend([1 if i <= k else 0 for i in range(1, target+1)]) # when the number of dice is one for r in range(1, n): curr = [0] # number of ways to get targets [0, 1 ... target] with the current number of dice for i in range(1, target+1): start = (i - k) if (i - k) >= 0 else 0 curr.append(sum(prev[start:i])) prev = curr return prev[-1] % 1000000007
number-of-dice-rolls-with-target-sum
[Python] DP Solution with Time: O(n * k * target), Space: O(target)
sreenithishb
1
23
number of dice rolls with target sum
1,155
0.536
Medium
17,863
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649856/Detailed-Explanation-of-Bottom-up-DP
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: if target > n*k: return 0 dp = [[0 for _ in range(target+1)] for _ in range(n+1)] #build up from lower dice roll to higher dice roll #one additional dice with each layer: rolls values [1,k] #add ways for each value dp[curr_row-1][target-roll_val] to get dp[curr_row][curr_val] for i in range(1,min(k+1,target+1)): dp[1][i] = 1 #initiate with single dice rolls for roll in range(2,n+1): #fill in dp table for val in range(1,target+1): for dice_val in range(1,k+1): if val-dice_val > 0: dp[roll][val] += dp[roll-1][val-dice_val] else: break return dp[-1][-1] % (10**9 + 7)
number-of-dice-rolls-with-target-sum
Detailed Explanation of Bottom-up DP
jooern
1
12
number of dice rolls with target sum
1,155
0.536
Medium
17,864
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649620/Detailed-Solution-or-Python-or-Beats-93
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: if target<n or target>k*n: return 0 if n==1: return 1 MOD = (10**9+7) def helper(n,k,t,d, count): if t<n or t>k*n: return 0 if t==0 and n==0: count+=1 return count if (n, k, t) not in d: for i in range(1,k+1): count += helper(n-1,k,t-i,d, 0) d[(n,k,t)] = count return d[(n,k,t)] d = {} return helper(n,k,target,d, 0)%MOD
number-of-dice-rolls-with-target-sum
Detailed Solution | Python | Beats 93%
N8mare
1
19
number of dice rolls with target sum
1,155
0.536
Medium
17,865
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649552/simple-memoization-solution-to-understand
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: self.memo = {} def solve(target,dices): if((target,dices) in self.memo): return self.memo[(target,dices)] if(target == 0 and dices == 0): return 1 if(target == 0): return 0 if(dices < 1): return 0 ans = 0 for i in range(1,k+1): if(target >= i): ans += solve(target-i,dices-1) self.memo[(target,dices)] = ans return ans return solve(target,n) % (7 + 10**9)
number-of-dice-rolls-with-target-sum
simple memoization solution to understand
jagdishpawar8105
1
55
number of dice rolls with target sum
1,155
0.536
Medium
17,866
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649420/O(target*n*k)-using-Memorize-Dynamic-Programming
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: """ x1 + x2 + ... + xn = target 1<=xi<=k dp[target][6] = sum(dp[target-xi][5]) with 1<=xi<=k and target-xi>=0 """ # print("n, k, target:", n, k, target) mod = 10**9 + 7 dp = [[None] * n for _ in range(target+1)] def fsol(vsum, ndice): if dp[vsum][ndice-1] is None: # print("+ ", (vsum, ndice), dp[vsum][ndice-1]) if vsum==0: dp[vsum][ndice-1] = 0 elif ndice==1: dp[vsum][ndice-1] = 1 if 1<=vsum and vsum<=k else 0 else: total = 0 for ki in range(1, k+1): if vsum-ki>=0: total = (total + fsol(vsum-ki, ndice-1))%mod dp[vsum][ndice-1] = total pass return dp[vsum][ndice-1]%mod ans = fsol(target, n)%mod # print("ans:", ans) # print("=" * 20, "\n") return ans
number-of-dice-rolls-with-target-sum
O(target*n*k) using Memorize Dynamic Programming
dntai
1
20
number of dice rolls with target sum
1,155
0.536
Medium
17,867
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648642/Easy-Solution-oror-DP-oror-PYTHON
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: @lru_cache(None) def dp(remain, summ): if remain == 0: if summ == target: return 1 return 0 total = 0 for i in range(1, k + 1): total += dp(remain - 1, summ + i) return total return dp(n, 0) % ((10**9) + 7)
number-of-dice-rolls-with-target-sum
✔️✔️✔️ Easy Solution || DP || PYTHON
T5691
1
61
number of dice rolls with target sum
1,155
0.536
Medium
17,868
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648364/Python3-solution-using-memoization
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: memo = defaultdict(int) return self.roll(n, k, target, memo) def roll(self, n, k, target, memo): if n == 0 and target == 0: return 1 if target < 0 or n == 0: return 0 if (n, target) in memo: return memo[(n, target)] for i in range(1, k + 1): memo[(n, target)] += self.roll(n - 1, k, target - i, memo) return memo[(n, target)] % (10**9 + 7)
number-of-dice-rolls-with-target-sum
Python3 solution using memoization
Yoxbox
1
56
number of dice rolls with target sum
1,155
0.536
Medium
17,869
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648359/Python-Memoization
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: cache ={} def helper(index,target): key = "{}-{}".format(index,target) if key in cache: return cache[key] if index == n: if target == 0: return 1 return 0 count = 0 for i in range(1,k+1): if i <= target: count += helper(index+1,target-i) cache[key] = count return cache[key] return helper(0,target) % (pow(10,9)+7)
number-of-dice-rolls-with-target-sum
Python Memoization
gurucharandandyala
1
37
number of dice rolls with target sum
1,155
0.536
Medium
17,870
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648334/Python3-or-Simple-Bottom-Up-DP-or-O(n-*-k-*-target)
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: dp = [[0] * (target + 1) for _ in range(n + 1)] dp[0][0] = 1 for dice in range(1, n + 1): for tgt in range(target + 1): dp[dice][tgt] = sum(dp[dice - 1][tgt - roll] for roll in range(1, min(tgt, k) + 1)) return dp[n][target] % (10**9 + 7)
number-of-dice-rolls-with-target-sum
Python3 | Simple Bottom-Up DP | O(n * k * target)
ryangrayson
1
25
number of dice rolls with target sum
1,155
0.536
Medium
17,871
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648305/Simple-Top-Down-Python3-w-Cache
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: @cache def ways(dice, tgt): if tgt < 0: return 0 if dice == 0: return tgt == 0 return sum(ways(dice - 1, tgt - roll) for roll in range(1, k+1)) return ways(n, target) % (10**9 + 7)
number-of-dice-rolls-with-target-sum
Simple Top-Down Python3 w/ Cache
ryangrayson
1
13
number of dice rolls with target sum
1,155
0.536
Medium
17,872
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2054954/Python-2-lines-recursive
class Solution: @lru_cache(None) def numRollsToTarget(self, n: int, k: int, target: int) -> int: if not n: return target == 0 tot = 0 for i in range(1, k+1): tot += self.numRollsToTarget(n-1, k, target-i) return tot % (pow(10, 9) + 7)
number-of-dice-rolls-with-target-sum
Python 2 lines recursive
SmittyWerbenjagermanjensen
1
175
number of dice rolls with target sum
1,155
0.536
Medium
17,873
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2054954/Python-2-lines-recursive
class Solution: MOD = pow(10, 9) + 7 @lru_cache(None) def numRollsToTarget(self, n: int, k: int, target: int) -> int: if not n: return target == 0 return sum(self.numRollsToTarget(n-1, k, target-i) for i in range(1, k+1)) % self.MOD
number-of-dice-rolls-with-target-sum
Python 2 lines recursive
SmittyWerbenjagermanjensen
1
175
number of dice rolls with target sum
1,155
0.536
Medium
17,874
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2054954/Python-2-lines-recursive
class Solution: MOD = pow(10, 9) + 7 @lru_cache(None) def numRollsToTarget(self, n: int, k: int, target: int) -> int: return target == 0 if not n else sum(self.numRollsToTarget(n-1, k, target-i) for i in range(1, k+1)) % self.MOD
number-of-dice-rolls-with-target-sum
Python 2 lines recursive
SmittyWerbenjagermanjensen
1
175
number of dice rolls with target sum
1,155
0.536
Medium
17,875
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/1529520/python-bottom-up-DP-easy-understandable-solution-O(d*target)
class Solution: def numRollsToTarget(self, d: int, f: int, target: int) -> int: mod = 10**9 + 7 dp = [[0 for _ in range(target+1)] for _ in range(d+1)] dp[0][0] = 1 prev = 0 for i in range(1, d+1): # for j in range(i, target+1): # z = 0 # for k in range(1, min(f+1, j+1)): # z = (z + dp[i-1][j-k]) % mod # dp[i][j] = z pre = 0 for a in range(i, min(f+1, target+1)): pre = (pre + dp[i-1][a-1]) % mod dp[i][a] = pre for b in range(f+1, target+1): pre = (pre + dp[i-1][b-1] - dp[i-1][b-f-1]) % mod dp[i][b] = pre return dp[d][target]
number-of-dice-rolls-with-target-sum
python bottom up DP easy understandable solution --O(d*target)
ashish_chiks
1
185
number of dice rolls with target sum
1,155
0.536
Medium
17,876
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2827558/Python3-Commented-and-Concise-DP-Solution-(with-Memoization)
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: # reset = the cache self.cache = dict() # call the function return self.dp_numRollsToTarget(n, k, target) def dp_numRollsToTarget(self, n: int, k: int, target: int) -> int: # could do it recursively by decreasing the target and the # number of dices # check whether the number of dices left is zero or our target # is smaller than zero (end condition) if target < 0 or n < 0: return 0 # check whether we hit target with the right amount of dices elif target == 0 and n == 0: return 1 # check the cache if (n, k, target) in self.cache: return self.cache[(n, k, target)] # now go deeper result = 0 for face in range(1, k+1): result += self.dp_numRollsToTarget(n-1, k, target-face) # update the cache self.cache[(n, k, target)] = result # return the result return result % 1_000_000_007
number-of-dice-rolls-with-target-sum
[Python3] - Commented and Concise DP-Solution (with Memoization)
Lucew
0
1
number of dice rolls with target sum
1,155
0.536
Medium
17,877
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2816046/From-recursion-to-memoized-to-space-optimized-bottom-up-DP
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: MOD = 10**9+7 def dfs(dice,total): if target < 0: return 0 if dice == 0: return 1 if total == target else 0 tmp = 0 for j in range(1,k+1): tmp += dfs(dice-1,total+j)%MOD return tmp%MOD return dfs(n,0)%MOD
number-of-dice-rolls-with-target-sum
From recursion to memoized to space optimized bottom up DP
shriyansnaik
0
1
number of dice rolls with target sum
1,155
0.536
Medium
17,878
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2816046/From-recursion-to-memoized-to-space-optimized-bottom-up-DP
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: MOD = 10**9+7 dp = [[0]*(target+1) for _ in range(n+1)] dp[0][0] = 1 for dice in range(1,n+1): for target in range(target + 1): tmp = 0 for j in range(1,k+1): if target - j >= 0: tmp += dp[dice-1][target-j]%MOD dp[dice][target] = tmp%MOD return dp[n][target]%MOD
number-of-dice-rolls-with-target-sum
From recursion to memoized to space optimized bottom up DP
shriyansnaik
0
1
number of dice rolls with target sum
1,155
0.536
Medium
17,879
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2816046/From-recursion-to-memoized-to-space-optimized-bottom-up-DP
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: MOD = 10**9+7 prev = [0]*(target+1) cur = [0]*(target+1) prev[0] = 1 for dice in range(1,n+1): for target in range(target + 1): tmp = 0 for j in range(1,k+1): if target - j >= 0: tmp += prev[target-j]%MOD cur[target] = tmp%MOD prev = cur[:] return prev[target]%MOD
number-of-dice-rolls-with-target-sum
From recursion to memoized to space optimized bottom up DP
shriyansnaik
0
1
number of dice rolls with target sum
1,155
0.536
Medium
17,880
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2790119/Python-(Simple-Dynamic-Programming)
class Solution: def numRollsToTarget(self, n, k, target): dp = [[0 for _ in range(target+1)] for _ in range(n+1)] dp[0][0] = 1 for i in range(1,n+1): for j in range(1,target+1): dp[i][j] = sum(dp[i-1][j-l] for l in range(1,k+1) if j-l >= 0) return dp[-1][-1]%(10**9+7)
number-of-dice-rolls-with-target-sum
Python (Simple Dynamic Programming)
rnotappl
0
2
number of dice rolls with target sum
1,155
0.536
Medium
17,881
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2704329/Simple-Python-DP-solution
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: @cache def helper(n, target): if n == 1: return 1 if target <= k else 0 total = 0 for i in range(1, min(k + 1, target)): total += helper(n - 1, target - i) return total return helper(n, target) % (10**9 + 7)
number-of-dice-rolls-with-target-sum
Simple Python DP solution
wmf410
0
12
number of dice rolls with target sum
1,155
0.536
Medium
17,882
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2662517/inclusion-exclusion
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: total = comb(target - 1, n - 1) positive = False full_count = 1 while True: remaining = target - full_count * k if remaining <= 0: break total += comb(n, full_count) * comb(remaining - 1, n - 1) if positive else comb(n, full_count) * comb(remaining - 1, n - 1) * -1 total = total % (10**9 + 7) full_count += 1 positive = ~positive return total % (10**9 + 7)
number-of-dice-rolls-with-target-sum
inclusion exclusion
n88k
0
2
number of dice rolls with target sum
1,155
0.536
Medium
17,883
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2658220/Solution-based-on-exact-formula-beats-98
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: if target<n or target>n*k: return 0 p=10**9+7 def a(m, n): ans=1 for i in range(n): ans=ans*(m-i)%p return ans def g(n): ans=1 for i in range(1, n): ans=ans*i%p return ans f=pow(g(n), -1, p) # def c(m, n): # ans=1 # for i in range(n): # ans=ans*(m-i)//(i+1) # return ans%p ans=0 sgn=1 i=0 target-=1 comb=1 while target>=n-1: # ans=(ans+sgn*c(n, i)*c(target, n-1))%p # ans=(ans+sgn*c(n, i)*a(target, n-1)*f)%p ans=(ans+sgn*comb*a(target, n-1)*f)%p comb=comb*(n-i)//(i+1) i+=1 target-=k sgn=-sgn return ans
number-of-dice-rolls-with-target-sum
Solution based on exact formula, beats 98%
mbeceanu
0
17
number of dice rolls with target sum
1,155
0.536
Medium
17,884
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2652744/Python-Terrible-One-Line-That-Works*-(assuming-you-are-using-a-super-computer)-TLE
class Solution: def numRollsToTarget(self, n: int, k: int, t: int) -> int: return Counter(map(sum, itertools.product(range(1, min(k + 1, t - n + 1)), repeat=n)))[t] % (10**9 + 7)
number-of-dice-rolls-with-target-sum
Python Terrible One Line That Works* (assuming you are using a super computer) TLE
cswartzell
0
16
number of dice rolls with target sum
1,155
0.536
Medium
17,885
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2652736/Solution-of-constant-space-(and-almost-for-time)-complexity
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: import math if n * k < target: # edge case guard return 0 answer = 0 for p in range((target-1) // k + 1): # the number of dices larger than k answer += (-1) ** p * math.comb(n, p) * math.comb(target - p*k - 1, n - 1) answer %= 10 ** 9 + 7 return answer
number-of-dice-rolls-with-target-sum
Solution of constant space (and almost for time) complexity
owen8877
0
9
number of dice rolls with target sum
1,155
0.536
Medium
17,886
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2652566/Python-3-recursive-solution-faster-and-uses-less-memory-than-98
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: if target<n or target>n*k: return 0 p=10**9+7 target+=1-n lst=[1 for i in range(k)] if target>=k: lst+=[0]*(target-k) for i in range(1, n): s=0 new_lst=[0]*target for j in range(target): s+=lst[j] if j>=k: s-=lst[j-k] s%=p new_lst[j]=s lst=new_lst return lst[target-1]
number-of-dice-rolls-with-target-sum
Python 3 recursive solution, faster and uses less memory than 98%
mbeceanu
0
7
number of dice rolls with target sum
1,155
0.536
Medium
17,887
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2651984/Python3-Solution
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: MOD = 10**9+7 dp=[[0 for j in range(target+1)] for i in range(n)] for i in range(len(dp)): for j in range(len(dp[0])): if i==0 and j<=k and j!=0: dp[i][j]=1 elif i==0 and j>k: dp[i][j]=0 else: if(j<=k): a=0 else: a=j-k dp[i][j]=sum(dp[i-1][a:j]) return dp[-1][-1]%MOD
number-of-dice-rolls-with-target-sum
Python3 Solution
creativerahuly
0
146
number of dice rolls with target sum
1,155
0.536
Medium
17,888
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2651831/Python-DP-or-O(N-*-Target)
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: mxn=10**9 + 7 dp=[[0 for i in range(target+1)] for j in range(n+1)] dp[0][0]=1 for i in range(n+1): for sm in range(1,target+1): if sm>k: dp[i][sm]=(dp[i][sm] + dp[i-1][sm-1]-dp[i-1][sm-k-1])%mxn else: dp[i][sm]=(dp[i][sm] + dp[i-1][sm-1])%mxn dp[i][sm]=(dp[i][sm]+dp[i][sm-1])%mxn return (dp[n][target]-dp[n][target-1])%mxn
number-of-dice-rolls-with-target-sum
Python DP | O(N * Target)
shivanshsahu753
0
251
number of dice rolls with target sum
1,155
0.536
Medium
17,889
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2651816/Python-(Faster-than-81)-or-Top-Bottom-DP-solution
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: mod = (10 ** 9) + 7 dp = [[-1] * (target + 1) for _ in range(n + 1)] def countWays(remain, target): if remain == 0: if target == 0: return 1 else: return 0 if target < 0: return 0 if dp[remain][target] != -1: return dp[remain][target] ways = 0 for i in range(1, k + 1): ways += countWays(remain - 1, target - i) ways %= mod dp[remain][target] = ways return ways return countWays(n, target)
number-of-dice-rolls-with-target-sum
Python (Faster than 81%) | Top-Bottom DP solution
KevinJM17
0
6
number of dice rolls with target sum
1,155
0.536
Medium
17,890
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2651684/HELP!!!-help!!!-PYTHON3
class Solution: # tar==n ans=1 # tar=n+1 ans=n # tar=n+2 ans=n*(n+1)/1*2 def numRollsToTarget(self, n: int, k: int, target: int) -> int: ans=1 for i in range(0,target-n): ans*=((n+i)/(i+1)) # print(ans) ans=ans%(10**9 + 7) return int(ans)
number-of-dice-rolls-with-target-sum
HELP!!! help!!! PYTHON3
DG-Problemsolver
0
67
number of dice rolls with target sum
1,155
0.536
Medium
17,891
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2651501/Python-solution
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: dp={} def check(t,s): if t==0 and s==target: return 1 elif t==0: return 0 if (t,s) in dp: return dp[(t,s)] dp[(t,s)]=sum([check(t-1,s+i) for i in range(1,k+1)]) return dp[(t,s)] return check(n,0)%(10**9+7)
number-of-dice-rolls-with-target-sum
Python solution
yashkumarjha
0
11
number of dice rolls with target sum
1,155
0.536
Medium
17,892
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2651359/Naive-memoization-solution
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: @functools.cache def NRTT(n, k, t): if n == 0: if t == 0: return 1 else: return 0 if t <= 0: return 0 ret = 0 for i in range(1, min(k,t)+1): print(i) ret += NRTT(n-1, k, t-i) ret %= 1000000007 return ret return NRTT(n,k,target)
number-of-dice-rolls-with-target-sum
Naive memoization solution
b08902128
0
3
number of dice rolls with target sum
1,155
0.536
Medium
17,893
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2651283/Python-Faster-than-93-and-memory-better-than-94
class Solution: def __init__(self): self.mod = 10**9+7 self.memo = dict() def numRollsToTarget(self, n: int, k: int, target: int) -> int: if n==1: return 1 if 0<target<=k else 0 if (n, target) in self.memo: return self.memo[(n, target)] n1 = n//2 n2 = n-n1 n_possible = 0 for i in range(n1, k*n1+1): if target-i < n2 or target-i > k*n2: continue n_possible += (self.numRollsToTarget(n1, k, i) * self.numRollsToTarget(n2, k, target-i))%self.mod n_possible %= self.mod self.memo[(n, target)] = n_possible return n_possible
number-of-dice-rolls-with-target-sum
[Python] Faster than 93% and memory better than 94%
kaushalya
0
13
number of dice rolls with target sum
1,155
0.536
Medium
17,894
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2651066/Python-oror-DP
class Solution: def __init__(self): self.dp = {} self.p = 10**9 + 7 def numRollsToTarget(self, n: int, k: int, target: int) -> int: if target < n or target > k*n: return 0 if target == 0: return 1 if n == 0 else 0 key = (n, k, target) if key not in self.dp: ans = 0 for i in range(1, k+1): ans = (ans%self.p + self.numRollsToTarget(n - 1, k , target - i)%self.p)%self.p self.dp[key] = ans return ans else: return self.dp[key]
number-of-dice-rolls-with-target-sum
Python || DP
Rahul_Kantwa
0
9
number of dice rolls with target sum
1,155
0.536
Medium
17,895
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2650421/Dp-using-memoization-python3-or-O(n*target)-time-and-space
class Solution: # O(n*target) time, # O(n*target) space, # Approach: dp top-down, memoization def numRollsToTarget(self, n: int, k: int, target: int) -> int: memo = {} MOD = (10**9)+7 def findCombinations(depth: int, rem: int) -> int: if depth == n: if rem == 0: return 1 return 0 if rem <= 0: return 0 if (depth, rem) in memo: return memo[(depth, rem)] combinations = 0 for i in range(1, k+1): combinations += findCombinations(depth+1, rem-i) memo[(depth, rem)] = (combinations%MOD) return memo[(depth, rem)] return findCombinations(0, target)
number-of-dice-rolls-with-target-sum
Dp using memoization python3 | O(n*target) time and space
destifo
0
56
number of dice rolls with target sum
1,155
0.536
Medium
17,896
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2650378/Python-or-The-Magic-of-Generating-Functions!
class Solution: def numRollsToTarget(self, n: int, k: int, t: int) -> int: p = 10**9 + 7 # We seek the sum of all binomial coefficients such that # ik + n + j = t. The index i ranges from 0 to n, inclusive. # The index j = t − ik − n is at most t - n. ans = 0 for i in range (0, n+1): j = t - n - i * k if j >= 0: prod = (self.binom(n, i, p) * self.binom(n + j - 1, j, p)) % p if i % 2: prod = (prod * (p - 1)) % p ans = (ans + prod) % p return ans # Compute the binomial coefficient n C r modulo p, where # p is prime. def binom(self, n, r, p): prod = 1 for i in range(r): prod = (prod * (n - i) * self.inv(i + 1, p)) % p return prod # Use the Euclidean algorithm to find the inverse of x (mod p). def inv(self, x, p): return self.bezout(x, p)[0] % p def bezout(self, a, b): if b == 0: return (1, 0) u, v = self.bezout (b, a % b) return (v, u - (a // b) * v)
number-of-dice-rolls-with-target-sum
Python | The Magic of Generating Functions!
on_danse_encore_on_rit_encore
0
12
number of dice rolls with target sum
1,155
0.536
Medium
17,897
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2650348/Python-simple-DP-solution
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: max = (10**9) + 7 @lru_cache(None) def dp(dice, cur): if dice <= 0: return 1 if cur == 0 else 0 ways = 0 for i in range(1, k+1): ways += dp(dice-1, cur-i) return ways return dp(n, target) % max
number-of-dice-rolls-with-target-sum
Python simple DP solution
danielturato
0
7
number of dice rolls with target sum
1,155
0.536
Medium
17,898
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2650329/Python-or-DP-or-95-Space-Optimized-Solution-or
class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: module = 10**9 + 7 dp = [ [0]*(target+1) for _ in range(n) ] return self.f(0, target, n, k, module, dp) def f(self, ind, target, n, k, module, dp): if ind == n-1: # return 1 if valid way else 0.. return int(target >= 1 and target <= k) if dp[ind][target]: return dp[ind][target] ways = 0 for x in range(1, k+1): # can pick num from dice.. if x <= target: ways = ( ways + self.f(ind+1, target-x, n, k, module, dp) )%module else: # cant pick num from dice.. break dp[ind][target] = ways return dp[ind][target]
number-of-dice-rolls-with-target-sum
Python | DP | 95% Space Optimized Solution |
quarnstric_
0
7
number of dice rolls with target sum
1,155
0.536
Medium
17,899