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/total-appeal-of-a-string/discuss/1997496/Easy-One-Pass-Python-Solution | class Solution:
def appealSum(self, s: str) -> int:
a=[-1]*26
cnt=0
res=0
for i in range(len(s)):
val=ord(s[i])-ord('a')
cnt+=(i-a[val])
# idea is to store last visited index of the char
a[val]=i
res+=cnt
return res | total-appeal-of-a-string | Easy One Pass Python Solution | _shubham28 | 0 | 34 | total appeal of a string | 2,262 | 0.583 | Hard | 31,300 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1997348/5-liner-simple-Python-solution-with-O(N)-time-O(1)-space | class Solution:
def appealSum(self, s: str) -> int:
n, ans, lasPos = len(s), 0, {chr(ord('a')+i): -1 for i in range(26)}
for i, char in enumerate(s):
ans += (i-lasPos[char])*(n-i)
lasPos[char] = i
return ans | total-appeal-of-a-string | 5-liner simple Python solution with O(N) time O(1) space | luyangg | 0 | 29 | total appeal of a string | 2,262 | 0.583 | Hard | 31,301 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1997241/Python-3-solution-easy-to-understand-(at-least-for-myself) | class Solution:
def appealSum(self, s: str) -> int:
seen_char_at_idx = defaultdict(int)
total_appeal = 0
prev_round_added = 0
for idx in range(len(s)):
appeal_supposed_to_add = idx + 1
this_round_adding = prev_round_added + appeal_supposed_to_add
if s[idx] in seen_char_at_idx:
this_round_adding -= seen_char_at_idx[s[idx]] + 1
total_appeal += this_round_adding
prev_round_added = this_round_adding
seen_char_at_idx[s[idx]] = idx # refreshing last seen index
return total_appeal | total-appeal-of-a-string | Python 3 solution, easy to understand (at least for myself) | steve8625 | 0 | 32 | total appeal of a string | 2,262 | 0.583 | Hard | 31,302 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2017786/Compare-with-2-previous | class Solution:
def largestGoodInteger(self, n: str) -> str:
return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else "" for i in range(2, len(n))) | largest-3-same-digit-number-in-string | Compare with 2 previous | votrubac | 51 | 2,300 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,303 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2017809/Python-O(1)-Space-Solution-beats-~90 | class Solution:
def largestGoodInteger(self, num: str) -> str:
res = ''
cnt = 1
for i in range(1, len(num)):
if num[i] == num[i-1]:
cnt+=1
else:
cnt = 1
if cnt == 3:
res = max(res, num[i] * 3)
return res | largest-3-same-digit-number-in-string | ✅ Python O(1) Space Solution beats ~90% | constantine786 | 7 | 569 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,304 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2385105/python-easy-straightforward | class Solution:
def largestGoodInteger(self, num: str) -> str:
num = "0"+num+"0"
i=0
l=len(num)
max_=-1
for i in range(1,l-1):
if num[i]==num[i-1]==num[i+1]:
max_=max(int(num[i]),max_)
if max_==-1:
return ""
return str(max_)*3 | largest-3-same-digit-number-in-string | python easy - straightforward | sunakshi132 | 1 | 53 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,305 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2276113/Simple-Python3-Solution-or-Brute-force-approach-or-O(3)-Space-or-O(n)-Time-or-Faster-than-97.58 | class Solution:
def largestGoodInteger(self, num: str) -> str:
ss = 0
res=''
for i in set(num):
if i*3 in num:
if ss <= int(i):
ss = int(i)
res=i*3
return res | largest-3-same-digit-number-in-string | Simple Python3 Solution | Brute force approach | O(3) Space | O(n) Time | Faster than 97.58% | RatnaPriya | 1 | 45 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,306 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2017780/Python3-1-line | class Solution:
def largestGoodInteger(self, num: str) -> str:
return next((x*3 for x in "9876543210" if x*3 in num), "") | largest-3-same-digit-number-in-string | [Python3] 1-line | ye15 | 1 | 45 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,307 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2847348/Python-simple-for-loop-%2B-set()-beat-97.68-runtime | class Solution:
def largestGoodInteger(self, num: str) -> str:
for x in sorted(set(num), reverse=True):
if x*3 in num:
return x*3
return '' | largest-3-same-digit-number-in-string | Python simple for loop + set() beat 97.68% runtime | Molot84 | 0 | 1 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,308 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2804751/PYTHON-100-EASY-TO-UNDERSTANDSIMPLECLEAN | class Solution:
def largestGoodInteger(self, num: str) -> str:
validNumbers = []
s=num
x=[i for i in s]
for i in range(len(s)):
if i >= 2:
if s[i] == s[i-1] and s[i-1] == s[i-2]:
validNumbers.append(s[i])
sort = sorted(validNumbers)
if len(validNumbers) > 0: return sort[-1]*3
else: return "" | largest-3-same-digit-number-in-string | 🔥PYTHON 100% EASY TO UNDERSTAND/SIMPLE/CLEAN🔥 | YuviGill | 0 | 3 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,309 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2665352/Sliding-Window-Approach-With-Optimization | class Solution:
def largestGoodInteger(self, num: str) -> str:
if len(num) == 3:
return num if num[0] == num[1] == num[2] else ""
largest, i = -1, 0
while i + 2 < len(num):
digit1 = int(num[i])
if digit1 <= largest:
i += 1
continue
digit2 = int(num[i + 1])
if digit1 == digit2:
if digit2 == int(num[i + 2]):
largest = digit1
if largest == 9:
return str(999)
i += 3
else:
i += 2
else:
i += 1
return str(largest) * 3 if largest != -1 else "" | largest-3-same-digit-number-in-string | Sliding Window Approach With Optimization | kcstar | 0 | 5 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,310 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2608270/Python-Simple-Python-Solution-Using-Slicing | class Solution:
def largestGoodInteger(self, num: str) -> str:
result = []
for i in range(len(num)-2):
substring = num[i:i+3]
first_num = substring[0]
if substring.count(first_num) == 3:
result.append(int(substring))
if len(result) == 0:
return ''
else:
result = str(sorted(result)[-1])
if result == '0':
return '000'
else:
return result | largest-3-same-digit-number-in-string | [ Python ] ✅✅ Simple Python Solution Using Slicing 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 12 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,311 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2581531/Python-85-Faster-Easy-to-follow | class Solution:
def largestGoodInteger(self, num: str) -> str:
#output value
ovalue = ""
#iterate through the list except final two values, idx for index
for idx,n in enumerate(num[:-2]):
#if n*3 == the 3 next characters in string, update ovalue
if n*3 == num[idx]+num[idx+1]+num[idx+2]:
#check if ovalue has been set yet to account for blank value
if ovalue == "":
ovalue = n*3
else:
#Check if new value is greater than the previous value
if int(ovalue) < int(n*3):
ovalue = n*3
return(ovalue) | largest-3-same-digit-number-in-string | Python 85% Faster, Easy to follow | ovidaure | 0 | 19 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,312 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2261781/Python-Solution | class Solution:
def largestGoodInteger(self, num: str) -> str:
for n in [str(i) * 3 for i in range(9, -1, -1)] + ['']:
if n in num:
return n | largest-3-same-digit-number-in-string | Python Solution | hgalytoby | 0 | 31 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,313 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2116194/Python-Easy-to-understand-Solution | class Solution:
def largestGoodInteger(self, num: str) -> str:
list1 = list(num)
n = len(list1)
x = []
j = -1
for i in range(n - 2):
if list1[i] == list1[i + 1] and list1[i] == list1[i + 2]:
j = j + 1
x.append(int(list1[i]))
good_max = ""
if len(x) == 0:
return ""
else:
good_max_int = 0
good_max_int = max(x)
num_max = ""
num_max = str(good_max_int)
good_max = num_max + num_max + num_max
return good_max | largest-3-same-digit-number-in-string | ✅Python Easy-to-understand Solution | chuhonghao01 | 0 | 20 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,314 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2108543/Compare-with-previous | class Solution:
def largestGoodInteger(self, num: str) -> str:
result = ""
for idx in range(2, len(num)):
if num[idx] == num[idx-1] == num[idx-2] and num[idx] * 3 > result:
result = num[idx] * 3
return result | largest-3-same-digit-number-in-string | Compare with previous | demas | 0 | 12 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,315 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2098415/Python-easy-and-intuitive-solution-for-beginners | class Solution:
def largestGoodInteger(self, num: str) -> str:
good = []
for i in range(len(num)):
if len(set(num[i:i+3])) == 1 and len(num[i:i+3]) == 3:
good.append(num[i:i+3])
if good == []:
return ""
return max(good) | largest-3-same-digit-number-in-string | Python easy and intuitive solution for beginners | alishak1999 | 0 | 21 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,316 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2078213/Make-use-of-%22Largest%22-3-Same-Digit-Number | class Solution:
def largestGoodInteger(self, num: str) -> str:
for i in range(9,-1,-1):
if (str(i)*3) in num:
return str(i)*3
return "" | largest-3-same-digit-number-in-string | Make use of "Largest" 3-Same-Digit Number | rushi_javiya | 0 | 37 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,317 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2044299/Python-Solution-Fast-Easy-to-Understand-No-Memory-Used | class Solution:
def largestGoodInteger(self, num: str) -> str:
mx = -1
for i in range(len(str(num)) - 2):
if num[i] == num[i + 1] == num[i + 2]:
mx = max(mx, int(num[i] + num[i + 1] + num[i + 2]))
if mx == 0:
return "000"
return str(mx) if mx != -1 else "" | largest-3-same-digit-number-in-string | Python Solution, Fast , Easy to Understand, No Memory Used | Hejita | 0 | 43 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,318 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2033130/Python-solution | class Solution:
def largestGoodInteger(self, num: str) -> str:
for i in range(9,-1,-1):
if str(i)*3 in num:
return str(i)*3
else:
return '' | largest-3-same-digit-number-in-string | Python solution | StikS32 | 0 | 26 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,319 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2027782/python-3-oror-very-simple-solution-oror-O(n)O(1) | class Solution:
def largestGoodInteger(self, num: str) -> str:
res = ''
for i in range(2, len(num)):
if num[i - 2] == num[i - 1] == num[i]:
res = max(res, num[i] * 3)
return res | largest-3-same-digit-number-in-string | python 3 || very simple solution || O(n)/O(1) | dereky4 | 0 | 30 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,320 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2021611/(27-ms)100.00-Python3-fast | class Solution:
def largestGoodInteger(self, num: str) -> str:
no = [str(x)*3 for x in range(10)]
found = [x for x in no if x in num]
if found != []:
return max(found)
else:
return "" | largest-3-same-digit-number-in-string | (27 ms)100.00% Python3-fast | bishtabhinavsingh | 0 | 16 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,321 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2020856/Python-Clean-and-Simple! | class Solution:
def largestGoodInteger(self, num):
largest = None
for i in range(2,len(num)):
subset = num[i-2:i+1]
a, b, c = subset
if a == b == c:
if not largest: largest = subset
else: largest = max(subset,largest)
return largest if largest else "" | largest-3-same-digit-number-in-string | Python - Clean and Simple! | domthedeveloper | 0 | 21 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,322 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2019544/Python3-nested-if | class Solution:
def largestGoodInteger(self, num: str) -> str:
same = []
same2 = []
for i in range(len(num)):
if i + 1 < len(num):
if num[i] == num[i + 1]:
if i + 2 < len(num):
if num[i] == num[i + 2]:
if num[i] not in same:
same.append(num[i])
if len(same) != 0:
maxN = max(same)
for i in range(3):
same2.append(maxN)
else:
same2 = ""
return ''.join(same2) | largest-3-same-digit-number-in-string | [Python3] nested if | Shiyinq | 0 | 8 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,323 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2018390/Easy-Python-Solution-with-substring-oror-O(n) | class Solution:
def largestGoodInteger(self, num: str) -> str:
c=float("-inf")
k=0
for i in range(len(num)-2):
sr=""
sr+=num[i]+num[i+1]+num[i+2]
if len(set(sr))==1:
c=max(c,int(sr))
k+=1
if k>0:
if c==0:
return str(c)*3
return str(c)
return "" | largest-3-same-digit-number-in-string | Easy Python Solution with substring || O(n) | a_dityamishra | 0 | 17 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,324 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2018376/python-two-ASCII-solutions-(Time-Olen(str)-space-O1-) | class Solution:
def largestGoodInteger(self, num: str) -> str:
table = [0]*10
for i in range (2,len(num)) :
id = ord(num[i]) - 48
if table[id] == 0 and num[i-2] == num[i-1] == num[i] :
table[id] = 1
for i in range(9, -1, -1):
if table[i] == 1 :
return chr(i+48)*3
return "" | largest-3-same-digit-number-in-string | python - two ASCII solutions (Time Olen(str), space O1 ) | ZX007java | 0 | 7 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,325 |
https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2018376/python-two-ASCII-solutions-(Time-Olen(str)-space-O1-) | class Solution:
def largestGoodInteger(self, num: str) -> str:
letter = ""
i = 0
while i != len(num) :
j = i + 1
while j != len(num) and num[i] == num[j]: j += 1
if j - i > 2 and letter < num[i] : letter = num[i]
i = j
return letter * 3 | largest-3-same-digit-number-in-string | python - two ASCII solutions (Time Olen(str), space O1 ) | ZX007java | 0 | 7 | largest 3 same digit number in string | 2,264 | 0.59 | Easy | 31,326 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2017794/Python3-post-order-dfs | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
def fn(node):
nonlocal ans
if not node: return 0, 0
ls, ln = fn(node.left)
rs, rn = fn(node.right)
s = node.val + ls + rs
n = 1 + ln + rn
if s//n == node.val: ans += 1
return s, n
ans = 0
fn(root)
return ans | count-nodes-equal-to-average-of-subtree | [Python3] post-order dfs | ye15 | 6 | 266 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,327 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2017794/Python3-post-order-dfs | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
ans = 0
mp = {None: (0, 0)}
node, stack = root, []
prev = None
while node or stack:
if node:
stack.append(node)
node = node.left
else:
node = stack[-1]
if node.right and node.right != prev: node = node.right
else:
stack.pop()
ls, lc = mp[node.left]
rs, rc = mp[node.right]
sm, cnt = ls + node.val + rs, lc + 1 + rc
mp[node] = (sm, cnt)
if sm//cnt == node.val: ans += 1
prev = node
node = None
return ans | count-nodes-equal-to-average-of-subtree | [Python3] post-order dfs | ye15 | 6 | 266 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,328 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2024264/Python3-two-detailed-solutions | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if not node:
return (0,0,0)
left, right = dfs(node.left), dfs(node.right)
subtree_sum = left[0]+right[0]+node.val
nodes_in_subtree = left[1]+right[1]+1
nodes_eq_to_avg = left[2]+right[2]+(subtree_sum//nodes_in_subtree == node.val)
return (subtree_sum, nodes_in_subtree, nodes_eq_to_avg)
return dfs(root)[2] | count-nodes-equal-to-average-of-subtree | Python3 two detailed solutions | mxmb | 1 | 70 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,329 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2022185/Recursive-solution-with-global-var-93-speed | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
count = 0
def traverse(node: TreeNode) -> tuple:
nonlocal count
if not node:
return 0, 0
sum_left, count_left = traverse(node.left)
sum_right, count_right = traverse(node.right)
sum_total = sum_left + sum_right + node.val
count_total = count_left + count_right + 1
count += node.val == sum_total // count_total
return sum_total, count_total
traverse(root)
return count | count-nodes-equal-to-average-of-subtree | Recursive solution with global var, 93% speed | EvgenySH | 1 | 21 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,330 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2695857/Python3-Simple-Solution | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
self.res = 0
def DFS(r):
if r:
vLeft, cLeft = DFS(r.left)
vRight, cRight = DFS(r.right)
value = vLeft + vRight + r.val
nodes = cLeft + cRight + 1
if r.val == value // nodes:
self.res += 1
return value, nodes
else:
return 0, 0
DFS(root)
return self.res | count-nodes-equal-to-average-of-subtree | Python3 Simple Solution | mediocre-coder | 0 | 3 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,331 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2585342/Python-or-Recursive-postorder | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
successCount = 0
def countSum(node: Optional[TreeNode] = root) -> (int, int):
nonlocal successCount
subtreeNodeCount = 1; subtreeSum = node.val
for child in [node.left, node.right]:
if child is not None:
nodeCount, nodeSum = countSum(child)
subtreeNodeCount += nodeCount
subtreeSum += nodeSum
if node.val == subtreeSum // subtreeNodeCount:
successCount += 1
return (subtreeNodeCount, subtreeSum)
countSum()
return successCount | count-nodes-equal-to-average-of-subtree | Python | Recursive postorder | sr_vrd | 0 | 14 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,332 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2337224/Python-clean-dfs-solution | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
res = 0
def dfs(node):
nonlocal res
if not node:
return 0, 0
elif not node.left and not node.right:
res += 1
return node.val, 1
sum_left, num_left = dfs(node.left)
sum_right, num_right = dfs(node.right)
sum_node = sum_left + node.val + sum_right
num_node = num_left + 1 + num_right
if sum_node // num_node == node.val:
res += 1
return sum_node, num_node
dfs(root)
return res | count-nodes-equal-to-average-of-subtree | Python clean dfs solution | byuns9334 | 0 | 45 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,333 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2317687/Python-Solution | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
ans = [0]
def solve(root):
if root is None:
return [0, 0]
lc, ls = solve(root.left)
rc, rs = solve(root.right)
tc = lc + rc + 1
ts = ls + rs + root.val
if ts//tc == root.val:
ans[0] += 1
return [tc, ts]
solve(root)
return ans[0] | count-nodes-equal-to-average-of-subtree | Python Solution | Anvesh9652 | 0 | 14 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,334 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2047154/Python3-Solution-with-using-dfs | class Solution:
def __init__(self):
self.res = 0
def traversal(self, node):
if not node:
return (0, 0)
lv, lc = self.traversal(node.left)
rv, rc = self.traversal(node.right)
_sum = lv + rv + node.val
_cnt = lc + rc + 1
if _sum // _cnt == node.val:
self.res += 1
return (_sum, _cnt)
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
self.traversal(root)
return self.res | count-nodes-equal-to-average-of-subtree | [Python3] Solution with using dfs | maosipov11 | 0 | 12 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,335 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2034775/Python-solution | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
global_result_counter = 0
def average_walk(root):
nonlocal global_result_counter
if not root:
return 0, 0
if not root.left and not root.right:
global_result_counter += 1
return root.val, 1
sum_left, counter_left = average_walk(root.left)
sum_right, counter_right = average_walk(root.right)
subtree_sum = sum_left + sum_right + root.val
counter = counter_left + counter_right + 1
if subtree_sum // counter == root.val:
global_result_counter += 1
return subtree_sum, counter
average_walk(root)
return global_result_counter | count-nodes-equal-to-average-of-subtree | Python solution | n_inferno | 0 | 27 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,336 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2018523/python-easy-postorder-recursive-solution | class Solution:
answer = 0
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
def post_order(node):
if node == None :
return (0, 0, 0)
summ_subtree , tot = node.val, 1
summ_subtree_l, tot_l, ans_l = post_order(node.left)
summ_subtree_r, tot_r, ans_r = post_order(node.right)
summ_subtree += summ_subtree_l + summ_subtree_r
tot += tot_l + tot_r
ans = ans_l + ans_r
if node.val == summ_subtree // tot:
ans += 1
return (summ_subtree, tot, ans)
return post_order(root)[2] | count-nodes-equal-to-average-of-subtree | python - easy postorder recursive solution | ZX007java | 0 | 19 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,337 |
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2017893/Python-Solution-Beats-~100 | class Solution:
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
res = 0
def averageOfSubtreeInner(node):
nonlocal res
if not node:
return (0, 0)
l_cnt, l_sum = averageOfSubtreeInner(node.left)
r_cnt, r_sum = averageOfSubtreeInner(node.right)
tot_sum = l_sum + r_sum + node.val
tot_cnt = 1 + l_cnt + r_cnt
avg = tot_sum//tot_cnt
if avg == node.val:
res+=1
return (tot_cnt, tot_sum)
averageOfSubtreeInner(root)
return res | count-nodes-equal-to-average-of-subtree | ✅ Python Solution Beats ~100 % | constantine786 | 0 | 16 | count nodes equal to average of subtree | 2,265 | 0.856 | Medium | 31,338 |
https://leetcode.com/problems/count-number-of-texts/discuss/2017834/Python3-group-by-group | class Solution:
def countTexts(self, pressedKeys: str) -> int:
MOD = 1_000_000_007
@cache
def fn(n, k):
"""Return number of possible text of n repeated k times."""
if n < 0: return 0
if n == 0: return 1
ans = 0
for x in range(1, k+1): ans = (ans + fn(n-x, k)) % MOD
return ans
ans = 1
for key, grp in groupby(pressedKeys):
if key in "79": k = 4
else: k = 3
ans = (ans * fn(len(list(grp)), k)) % MOD
return ans | count-number-of-texts | [Python3] group-by-group | ye15 | 8 | 371 | count number of texts | 2,266 | 0.473 | Medium | 31,339 |
https://leetcode.com/problems/count-number-of-texts/discuss/2017834/Python3-group-by-group | class Solution:
def countTexts(self, pressedKeys: str) -> int:
dp = [0] * (len(pressedKeys)+1)
dp[0] = 1
for i, ch in enumerate(pressedKeys):
dp[i+1] = dp[i]
if i and pressedKeys[i-1] == ch:
dp[i+1] += dp[i-1]
if i >= 2 and pressedKeys[i-2] == ch:
dp[i+1] += dp[i-2]
if i >= 3 and pressedKeys[i-3] == ch and ch in "79": dp[i+1] += dp[i-3]
dp[i+1] %= 1_000_000_007
return dp[-1] | count-number-of-texts | [Python3] group-by-group | ye15 | 8 | 371 | count number of texts | 2,266 | 0.473 | Medium | 31,340 |
https://leetcode.com/problems/count-number-of-texts/discuss/2797745/Python-(Simple-Dynamic-Programming) | class Solution:
def countTexts(self, pressedKeys):
n = len(pressedKeys)
dp = [0]*(n+1)
dp[0], dp[1] = 1, 1
for i in range(2,n+1):
dp[i] += dp[i-1]
if i > 1 and pressedKeys[i-1] == pressedKeys[i-2]:
dp[i] += dp[i-2]
if i > 2 and pressedKeys[i-1] == pressedKeys[i-2] == pressedKeys[i-3]:
dp[i] += dp[i-3]
if pressedKeys[i-1] == "7" or pressedKeys[i-1] == "9":
if i > 3 and pressedKeys[i-1] == pressedKeys[i-2] == pressedKeys[i-3] == pressedKeys[i-4]:
dp[i] += dp[i-4]
return dp[-1]%(10**9+7) | count-number-of-texts | Python (Simple Dynamic Programming) | rnotappl | 0 | 3 | count number of texts | 2,266 | 0.473 | Medium | 31,341 |
https://leetcode.com/problems/count-number-of-texts/discuss/2647472/DP-memoization-python3-soln-or-How-to-pass-MLE | class Solution:
# O(n) time,
# O(n) space,
# Approach: dp top-down, memoization
def countTexts(self, pressedKeys: str) -> int:
key_ch = {2: 3, 3: 3, 4: 3, 5: 3, 6: 3, 7: 4, 8: 3, 9: 4}
memo = {}
MOD = (10**9) + 7
def findDecodings(num, count):
if (count, num) in memo:
return memo[(count, num)]
branches = key_ch[num]
tot = 0
for i in range(1, branches+1):
if i < count:
tot += findDecodings(num, count-i)
if i == count:
tot += 1
memo[(count, num)] = (tot%MOD)
return tot
ways = 1
window = []
for ch in pressedKeys:
if not window:
window = [ch, 1]
continue
if window[0] == ch:
window[1] +=1
else:
num = window[0]
num = int(num)
count = window[1]
decodings = findDecodings(num, count)
ways *= decodings
ways %= MOD
window = [ch, 1]
num = window[0]
num = int(num)
count = window[1]
decodings = findDecodings(num, count)
ways *= decodings
ways %= MOD
return ways | count-number-of-texts | DP memoization python3 soln | How to pass MLE | destifo | 0 | 12 | count number of texts | 2,266 | 0.473 | Medium | 31,342 |
https://leetcode.com/problems/count-number-of-texts/discuss/2020357/Python-O(N)-oror-Simple-Solution-oror-DP | class Solution:
def countTexts(self, s: str) -> int:
n = len(s)
dp = [0] * (n+1)
dp[0] = 1
for i in range(1,n+1):
c = s[i-1]
count = 3
if c in '7,9':count += 1
for j in range(i-1,max(-1,i-count-1),-1):
if s[j] != c:break
dp[i] += dp[j]
dp[i] %= (10**9+7)
return dp[n] | count-number-of-texts | [Python] O(N) || Simple Solution || DP | abhijeetmallick29 | 0 | 18 | count number of texts | 2,266 | 0.473 | Medium | 31,343 |
https://leetcode.com/problems/count-number-of-texts/discuss/2019825/Python-3-Top-down-DP | class Solution:
def countTexts(self, s: str) -> int:
M = 10 ** 9 + 7
c1, c2 = {}, {}
# 'three letters'
def dp(n):
if n in c1:
return c1[n]
if n <= 3:
c1[n] = pow(2, n-1)
else:
c1[n] = sum(dp(n - i) for i in range(1, 4)) % M # could combine first three letters ('a', 'b', 'c')
return c1[n]
# 'four letters'
def dp2(n):
if n in c2:
return c2[n]
if n <= 4:
c2[n] = pow(2, n-1)
else:
c2[n] = sum(dp2(n - i) for i in range(1, 5)) % M # could combine first four letters ('p', 'q', 'r', 's')
return c2[n]
ans = 1
for a, b in groupby(s):
cnt = len(list(b))
if a not in '79':
ans *= dp(cnt)
else:
ans *= dp2(cnt)
ans %= M
return ans | count-number-of-texts | [Python 3] Top down DP | chestnut890123 | 0 | 28 | count number of texts | 2,266 | 0.473 | Medium | 31,344 |
https://leetcode.com/problems/count-number-of-texts/discuss/2017906/Python3-O(n)-DP-Solution | class Solution:
def countTexts(self, pressedKeys: str) -> int:
res = 0
grid = [0]*(len(pressedKeys)+1)
grid[0] = 1
set1 = {'2', '3', '4', '5', '6', '8'}
for t in range(1,len(grid)):
target = pressedKeys[t-1]
res = grid[t-1]
if target in set1:
if t >= 2 and pressedKeys[t-2] == target:
res += grid[t-2]
if t >= 3 and pressedKeys[t-2] == target and pressedKeys[t-3] == target:
res += grid[t-3]
else:
if t >= 2 and pressedKeys[t-2] == target:
res += grid[t-2]
if t >= 3 and pressedKeys[t-2] == target and pressedKeys[t-3] == target:
res += grid[t-3]
if t >= 4 and pressedKeys[t-2] == target and pressedKeys[t-3] == target and pressedKeys[t-4] == target:
res += grid[t-4]
grid[t] = res % (10**9 + 7)
return grid[-1] % (10**9 + 7) | count-number-of-texts | Python3 O(n) DP Solution | xxHRxx | 0 | 35 | count number of texts | 2,266 | 0.473 | Medium | 31,345 |
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2018005/Python-Simple-MemoisationCaching | class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
m = len(grid)
n = len(grid[0])
@lru_cache(maxsize=None)
def hasValidPathInner(x, y, cnt):
# cnt variable would act as a counter to track
# the balance of parantheses sequence
if x == m or y == n or cnt < 0:
return False
# logic to check the balance of sequence
cnt += 1 if grid[x][y] == '(' else -1
# if balanced and end of grid, return True
if x == m - 1 and y == n - 1 and not cnt:
return True
return hasValidPathInner(x + 1, y, cnt) or hasValidPathInner(x, y + 1, cnt)
return hasValidPathInner(0, 0, 0) | check-if-there-is-a-valid-parentheses-string-path | ✅ Python Simple Memoisation/Caching | constantine786 | 13 | 405 | check if there is a valid parentheses string path | 2,267 | 0.38 | Hard | 31,346 |
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2017845/Python3-DP | class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
@cache
def fn(i, j, v):
"""Return True if value of v at (i, j) is possible."""
if i == m-1 and j == n-1: return v == 0
for ii, jj in (i+1, j), (i, j+1):
if 0 <= ii < m and 0 <= jj < n:
if grid[ii][jj] == '(': vv = v+1
else: vv = v-1
if 0 <= vv <= min(ii+jj+1, m+n-ii-jj) and fn(ii, jj, vv): return True
return False
return fn(0, 0, 1) | check-if-there-is-a-valid-parentheses-string-path | [Python3] DP | ye15 | 1 | 64 | check if there is a valid parentheses string path | 2,267 | 0.38 | Hard | 31,347 |
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2032255/python-3-oror-simple-recursive-memoization | class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
@lru_cache(None)
def helper(i, j, score):
if i == m or j == n:
return False
if i == m - 1 and j == n - 1:
return score == 1 and grid[i][j] == ')'
if grid[i][j] == '(':
return helper(i + 1, j, score + 1) or helper(i, j + 1, score + 1)
if score == 0:
return False
return helper(i + 1, j, score - 1) or helper(i, j + 1, score - 1)
return helper(0, 0, 0) | check-if-there-is-a-valid-parentheses-string-path | python 3 || simple recursive memoization | dereky4 | 0 | 65 | check if there is a valid parentheses string path | 2,267 | 0.38 | Hard | 31,348 |
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2025540/One-pass-over-all-cells-88-speed | class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
rows, cols = len(grid), len(grid[0])
if ((rows + cols - 1) % 2 or grid[0][0] == ")"
or grid[rows - 1][cols - 1] == "("):
return False
opened = [[set() for _ in range(cols)] for _ in range(rows)]
opened[0][0].add(1)
row = 0
for col in range(1, cols):
if grid[row][col] == "(":
opened[row][col].update(n + 1 for n in opened[row][col - 1])
else:
opened[row][col].update(n - 1 for n in opened[row][col - 1]
if n > 0)
col = 0
for row in range(1, rows):
if grid[row][col] == "(":
opened[row][col].update(n + 1 for n in opened[row - 1][col])
else:
opened[row][col].update(n - 1 for n in opened[row - 1][col]
if n > 0)
for row in range(1, rows):
for col in range(1, cols):
opened[row - 1][col].update(opened[row][col - 1])
if grid[row][col] == "(":
opened[row][col].update(n + 1 for n in
opened[row - 1][col])
else:
opened[row][col].update(n - 1 for n in
opened[row - 1][col] if n > 0)
return 0 in opened[rows - 1][cols - 1] | check-if-there-is-a-valid-parentheses-string-path | One pass over all cells, 88% speed | EvgenySH | 0 | 31 | check if there is a valid parentheses string path | 2,267 | 0.38 | Hard | 31,349 |
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2020643/Python-3-DP-with-pruning | class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
if grid[0][0] == ')' or (m + n - 1) % 2: return False
@lru_cache(None)
def dp(x, y, ops):
# if unpaired close bracket or remaining cannot match open brackets
if ops < 0 or ops > (m + n - 1) // 2: return False
if x == m - 1 and y == n - 1:
return not ops
for dx, dy in [(0, 1), (1, 0)]:
nx, ny = x + dx, y + dy
if not(0 <= nx < m and 0 <= ny < n): continue
tmp = 1 if grid[nx][ny] == '(' else -1
if dp(nx, ny, ops + tmp):
return True
return False
return dp(0, 0, 1) | check-if-there-is-a-valid-parentheses-string-path | [Python 3] DP with pruning | chestnut890123 | 0 | 32 | check if there is a valid parentheses string path | 2,267 | 0.38 | Hard | 31,350 |
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2019761/2267-%3A-Simple-Solution-in-3-easy-steps | class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
@cache
def dfs(i,j,o,c) :
if c > o :
return
if self.result == True :
return
if (0 <= i < m) and (0 <= j < n) :
if grid[i][j] == '(' :
o += 1
else :
c += 1
if i == m-1 and j == n-1 and o == c :
self.result = True
return
dfs(i+1,j,o,c)
dfs(i,j+1,o,c)
self.result = False
m,n = len(grid),len(grid[0])
dfs(0,0,0,0)
return self.result | check-if-there-is-a-valid-parentheses-string-path | 2267 : Simple Solution in 3 easy steps | Manideep8 | 0 | 37 | check if there is a valid parentheses string path | 2,267 | 0.38 | Hard | 31,351 |
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2018156/Python-or-Memoization-with-LRU-Cache | class Solution:
@lru_cache(maxsize=None)
def helper(self, i, j, left_count):
if i >= len(self.grid) or j >= len(self.grid[0]): return False
left_count += 1 if self.grid[i][j] == '(' else -1
if left_count < 0: return False
if i == len(self.grid) - 1 and j == len(self.grid[0]) - 1 and left_count == 0: return True
return self.helper(i + 1, j, left_count) or self.helper(i, j + 1, left_count)
def hasValidPath(self, grid: List[List[str]]) -> bool:
self.grid = grid
return self.helper(0, 0, 0) | check-if-there-is-a-valid-parentheses-string-path | Python | Memoization with LRU Cache | leeteatsleep | 0 | 28 | check if there is a valid parentheses string path | 2,267 | 0.38 | Hard | 31,352 |
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2017992/python-simple-DFS-with-cache | class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
if grid[0][0] == ")":
return False
dirs = [[0,1],[1,0]]
@cache
def helper(x, y, remain):
if x == m - 1 and y == n - 1:
if grid[x][y] == ")" and remain == 1:
return True
else:
return False
res = False
if grid[x][y] == "(":
remain += 1
elif grid[x][y] == ")":
if remain == 0:
return False
else:
remain -= 1
for dx, dy in dirs:
nx, ny = x + dx, y + dy
if nx >= m or ny >= n:
continue
if helper(nx, ny, remain):
return True
return False
return helper(0, 0, 0) | check-if-there-is-a-valid-parentheses-string-path | [python] simple DFS with cache | icomplexray | 0 | 18 | check if there is a valid parentheses string path | 2,267 | 0.38 | Hard | 31,353 |
https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2017829/Python3-DFS-with-memorization-Solution | class Solution:
def hasValidPath(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
if grid[0][0] == ')': return False
else:
@lru_cache(None)
def helper(x, y, acc):
if x == m-1 and y == n-1:
if grid[x][y] == ')':
if acc == 1: return True
else: return False
else:
if grid[x][y] == ')':
if acc == 0: return False
else:
if x < m-1:
res = helper(x+1, y, acc-1)
if res: return True
if y < n-1:
res = helper(x, y+1, acc-1)
if res: return True
return False
else:
acc += 1
if x < m-1:
res = helper(x+1, y, acc)
if res: return True
if y < n-1:
res = helper(x, y+1, acc)
if res: return True
return False
return helper(0, 0, 0) | check-if-there-is-a-valid-parentheses-string-path | Python3 DFS with memorization Solution | xxHRxx | 0 | 23 | check if there is a valid parentheses string path | 2,267 | 0.38 | Hard | 31,354 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2611592/Python-Elegant-and-Short-or-Sliding-window-or-O(log10(n))-time-or-O(1)-memory | class Solution:
"""
Time: O(log10(n)*k)
Memory: O(log10(n))
"""
def divisorSubstrings(self, num: int, k: int) -> int:
str_num = str(num)
return sum(
num % int(str_num[i - k:i]) == 0
for i in range(k, len(str_num) + 1)
if int(str_num[i - k:i]) != 0
) | find-the-k-beauty-of-a-number | Python Elegant & Short | Sliding window | O(log10(n)) time | O(1) memory | Kyrylo-Ktl | 3 | 211 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,355 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2611592/Python-Elegant-and-Short-or-Sliding-window-or-O(log10(n))-time-or-O(1)-memory | class Solution:
"""
Time: O(log10(n))
Memory: O(1)
"""
def divisorSubstrings(self, num: int, k: int) -> int:
power = 10 ** (k - 1)
tmp, window = divmod(num, 10 * power)
count = int(window and not num % window)
while tmp:
tmp, digit = divmod(tmp, 10)
window = digit * power + window // 10
count += window and not num % window
return count | find-the-k-beauty-of-a-number | Python Elegant & Short | Sliding window | O(log10(n)) time | O(1) memory | Kyrylo-Ktl | 3 | 211 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,356 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2805819/Sliding-window-approach-faster-greater-63.32 | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
num_str = str(num)
temp = ''
w_s, c = 0, 0
for w_e in range(len(num_str)):
r_c = num_str[w_s:w_e+1]
temp = r_c
if len(temp) == k:
if int(temp) != 0 and num % int(temp) == 0:
c += 1
w_s += 1
return c | find-the-k-beauty-of-a-number | Sliding window approach, faster > 63.32% | samratM | 0 | 2 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,357 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2799615/Simple-Python-O(n)-time-and-O(1)-space-solution | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
count = 0
i = 0
while i< len(str(num))-k+1:
subs = int(str(num)[i:i+k])
if subs!=0:
if num%subs==0:
count+=1
i+=1
return count | find-the-k-beauty-of-a-number | Simple Python O(n) time and O(1) space solution | Rajeev_varma008 | 0 | 4 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,358 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2796921/Python-easy-solution | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
c=0
num_str=str(num)
for i in range(len(num_str)-k+1):
tmp=int(num_str[i:i+k])
if tmp!=0:
if num % tmp==0:
c+=1
return c | find-the-k-beauty-of-a-number | Python easy solution | ankansharma1998 | 0 | 2 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,359 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2795685/Numeric-Sliding-Window-or-Time-Complexity%3A-O(n-k%2B1)-or-Beats-99.93 | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
str_num = str(num)
n = len(str_num)
i = 0
cnt = 0
if n == 1:
if num % num == 0:
cnt +=1
return cnt
while i < n-k+1:
try:
if num % int(str_num[i:i+k]) == 0:
cnt += 1
except:
i+=1
continue
i+=1
return cnt | find-the-k-beauty-of-a-number | Numeric Sliding Window | Time Complexity: O(n-k+1) | Beats 99.93% | ShabbirMarfatiya | 0 | 5 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,360 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2601883/Easy-Solution-Python3 | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
ans = 0;
for x in range(len(str(num))):
substr = str(num)[x:x+k:];
if len(substr) < k: break;
elif int(substr) == 0: continue;
ans += num % int(substr) == 0;
return ans; | find-the-k-beauty-of-a-number | Easy Solution Python3 | zeyf | 0 | 46 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,361 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2574490/Python-Solution-or-Simply-or-Numeric-or-Faster-than-91 | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
ans = 0
k = int("1"+"0"*k)
tmp_n = num
while tmp_n*10 >= k :
sub = tmp_n % k
if sub != 0 and num % sub == 0:
ans += 1
tmp_n //= 10
return ans | find-the-k-beauty-of-a-number | Python Solution | Simply | Numeric | Faster than 91% | ckayfok | 0 | 9 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,362 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2553523/Python-Simple-Python-Solution | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
result = 0
new_num = str(num)
for i in range(len(new_num)-k+1):
sub_num = int(new_num[i:i+k])
if sub_num != 0 and num % sub_num == 0:
result = result + 1
return result | find-the-k-beauty-of-a-number | [ Python ] ✅✅ Simple Python Solution 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 17 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,363 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2499287/Python-or-Sliding-Window | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
i=j=0
s=str(num)
n=len(s)
temp=''
ans=0
while j<n:
temp=temp+s[j]
if j-i+1<k:
j+=1
elif j-i+1==k:
x=int(temp)
if x>0 and num%x==0:
ans+=1
temp=temp[1:]
i+=1
j+=1
return ans | find-the-k-beauty-of-a-number | Python | Sliding Window | ayushigupta2409 | 0 | 26 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,364 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2419406/Python-3-Easy-Solution | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
l=str(num)
count=0
for i in range(len(l)-k+1):
l1=int(l[i:i+k])
if( l1!=0 and num%int(l1)==0):
count+=1
return count | find-the-k-beauty-of-a-number | Python 3 Easy Solution | mrigank2303239 | 0 | 8 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,365 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2416156/Python-oror-91-Faster-oror-Easy-to-understand | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
kb = 0
snum = str(num)
for i in range(len(snum)):
if int(snum[i:i+k]) == 0:
continue
if i+k<=len(snum) and num%int(snum[i:i+k])==0:
kb += 1
return kb | find-the-k-beauty-of-a-number | Python || 91% Faster || Easy to understand | Srijan_Dixit | 0 | 20 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,366 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2404247/Python3-Fast | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
num=str(num)
l=len(num)
if k==l:
return 1
ans=0
for i in range(0,l-k+1):
x=int(num[i:i+k])
if (x!=0) and (int(num)%x==0) :
ans+=1
return ans | find-the-k-beauty-of-a-number | [Python3] Fast | sunakshi132 | 0 | 14 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,367 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2393573/Python-Solution-or-Classic-Sliding-Window-or-Convert-Divide-Check | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
numS = str(num)
count = 0
for end in range(len(numS)-k+1):
denom = int(numS[end:end+k])
if denom != 0:
count += 1 if (num % denom) == 0 else 0
return count | find-the-k-beauty-of-a-number | Python Solution | Classic Sliding Window | Convert / Divide / Check | Gautam_ProMax | 0 | 11 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,368 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2375071/Python-Sliding-window | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
'''Returns the Beauty of a number'''
num = str(num)
count = 0
for i in range(len(num)-k+1):
if int(str(num)[i:i+k]) !=0: # To avoid Divide by Zero Error
if int(num)% int(str(num)[i:i+k]) ==0:
count+=1
return count | find-the-k-beauty-of-a-number | Python Sliding window | aditya_maskar | 0 | 8 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,369 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2333857/Easy-python-31ms-faster-than-93.51-using-array-method | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
st = str(num)
n, count, a = len(str(num)), 0, []
for i in range(0, n):
if len(st[i:k+i]) == k:
a.append((st[i:k+i]))
for i in a:
if int(i) != 0 and num % int(i) == 0 :
count+=1
return count | find-the-k-beauty-of-a-number | Easy python 31ms faster than 93.51% using array method | amit0693 | 0 | 18 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,370 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2304516/Python3-or-Sliding-Window-Using-String | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
#sliding window technique!
L, R = 0, 0
counter = 0
ans = 0
string = str(num)
cur_string = ""
while R < len(string):
#process right element first!
cur_string += string[R]
counter += 1
#stopping condition!
while counter == k and cur_string != "":
#if cur_string is ever 0, don't do it cause it can never be a valid divisor!
if(int(cur_string) == 0):
cur_string = cur_string[1:]
counter -= 1
L += 1
break
if(num % int(cur_string)==0):
ans += 1
#Shrink sliding window!
cur_string = cur_string[1:]
L += 1
counter -= 1
#continue expanding!
R += 1
return ans | find-the-k-beauty-of-a-number | Python3 | Sliding Window Using String | JOON1234 | 0 | 15 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,371 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2277218/Easy-and-Simple-Python3-straightforward-Solution-or-Easy-to-Understand-or-Beginner-Friendly-or-O(n)-Time | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
x = str(num)
ct = 0
n = 0
for i in range(len(x)):
ss = x[i:i+k]
if len(ss) == k and int(ss) != 0:
n = int(ss)
if num % n == 0:
ct += 1
return(ct)class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
x = str(num)
ct = 0
n = 0
for i in range(len(x)):
ss = x[i:i+k]
if len(ss) == k and int(ss) != 0:
n = int(ss)
if num % n == 0:
ct += 1
return(ct) | find-the-k-beauty-of-a-number | Easy & Simple Python3 straightforward Solution | Easy to Understand | Beginner-Friendly | O(n) Time | RatnaPriya | 0 | 16 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,372 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2246510/Beginner-Friendly-Solution-oror-20ms-Faster-Than-100-oror-Python | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
k_count = 0
str_num = str(num)
for i in range(len(str_num) + 1 - k):
# For readability, assign a variable to int(str_num[i:i + k]).
sub_int = int(str_num[i:i + k])
# Python code is read from left to right. So, the line below checks to see if
# sub_int is zero first to avoid a zero-division error at the modulus operation.
if sub_int != 0 and num % sub_int == 0:
k_count += 1
return k_count | find-the-k-beauty-of-a-number | Beginner Friendly Solution || 20ms, Faster Than 100% || Python | cool-huip | 0 | 31 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,373 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2186550/Python-Solution-97.89-faster-O(n-k%2B1)-Time-Complexity | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
c=0
for i in range(len(str(num))-k+1):
try:
if num%int(str(num)[i:i+k])==0 :
c+=1
except:
pass
return c | find-the-k-beauty-of-a-number | Python Solution 97.89% faster O(n-k+1) Time Complexity | Kunalbmd | 0 | 25 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,374 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2148632/Python3-scan | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
s = str(num)
ans = div = 0
for i in range(len(s)-k+1):
div = int(s[i:i+k])
if div and num % div == 0: ans += 1
return ans | find-the-k-beauty-of-a-number | [Python3] scan | ye15 | 0 | 13 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,375 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2116193/Python-Easy-to-understand-Solution | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
ans = 0
res = [int(x) for x in str(num)]
n = len(res)
m = n - k + 1
for i in range(m):
test = 0
test_sum = 0
for j in range(k):
test = res[i + j] * 10 ** (k - 1 - j)
test_sum = test_sum + test
if test_sum == 0:
continue
if num % test_sum == 0:
ans = ans + 1
return ans | find-the-k-beauty-of-a-number | ✅Python Easy-to-understand Solution | chuhonghao01 | 0 | 25 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,376 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2098391/Python-easy-solution-faster-than-98.5 | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
res = 0
num_str = str(num)
for i in range(len(num_str)):
divisor = num_str[i:i+k]
if len(divisor) == k and int(divisor) != 0 and num % int(divisor) == 0:
res += 1
return res | find-the-k-beauty-of-a-number | Python easy solution faster than 98.5% | alishak1999 | 0 | 41 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,377 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2047839/O(N)-faster-than-~96 | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
count = 0
tmp = str(num)
for i in range(len(tmp) - k + 1):
n = int(tmp[i:i + k])
if n and not num % n:
count += 1
return count | find-the-k-beauty-of-a-number | O(N) faster than ~96% | andrewnerdimo | 0 | 33 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,378 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2044521/Python-Easy-To-Understand-Solution-Faster-Than-100 | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
s, cnt = str(num), 0
for i in range(len(s) - k + 1):
temp = int(s[i : i + k])
if temp != 0 and num % temp == 0:
cnt += 1
return cnt | find-the-k-beauty-of-a-number | Python Easy To Understand Solution, Faster Than 100% | Hejita | 0 | 30 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,379 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2040779/Sliding-window-easy-python | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
# Sliding window approach
# We maintain the window size==k ,
# And check it should not be zer and a divisor of original num string
# In this way keep incrementing count
count=0
new=str(num)
l=len(new)
for i in range(l-k+1):
new1=new[i:i+k]
if int(new1)==0:
continue
elif num%int(new1)==0:
count+=1
return count | find-the-k-beauty-of-a-number | Sliding window, easy python | Aniket_liar07 | 0 | 60 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,380 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2039276/Python-2-Liner-beats-100 | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
number = str(num)
return sum(1 for i in range(len(number)-k+1) if int(number[i:i+k]) and num % int(number[i:i+k]) == 0) | find-the-k-beauty-of-a-number | ✅ Python 2 Liner beats 100% | constantine786 | 0 | 20 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,381 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2038640/Python-solution | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
substr = k
ans = 0
s = str(num)
while substr <= len(str(num)):
if not int(s[substr-k:substr]):
substr += 1
continue
if num%int(s[substr-k:substr]) == 0:
print(int(s[substr-k:substr]))
ans += 1
substr += 1
return ans | find-the-k-beauty-of-a-number | Python solution | StikS32 | 0 | 14 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,382 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2038627/Easy-Python-Solution | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
c=0
s=str(num)
for i in range(len(s)):
if int(s[i:i+k])!=0 and len(s[i:i+k])==k and int(s)%int(s[i:i+k])==0:
c+=1
return c | find-the-k-beauty-of-a-number | Easy Python Solution | a_dityamishra | 0 | 30 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,383 |
https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2038180/Python-Simple-O(n*k)-Solution | class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
num_str = str(num)
n = len(num_str)
count = 0
for i in range(n - k + 1):
sub_num = int(num_str[i:i+k])
if sub_num == 0 or num % sub_num != 0:
continue
count += 1
return count | find-the-k-beauty-of-a-number | [Python] Simple O(n*k) Solution | andrenbrandao | 0 | 14 | find the k beauty of a number | 2,269 | 0.567 | Easy | 31,384 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2038567/Prefix-Sum | class Solution:
def waysToSplitArray(self, n: List[int]) -> int:
n = list(accumulate(n))
return sum(n[i] >= n[-1] - n[i] for i in range(len(n) - 1)) | number-of-ways-to-split-array | Prefix Sum | votrubac | 14 | 1,100 | number of ways to split array | 2,270 | 0.446 | Medium | 31,385 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2038305/C%2B%2BPython3-Very-Concise-Prefix-Sum-O(1) | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
lsum, rsum, ans = 0, sum(nums), 0
for i in range(len(nums) - 1):
lsum += nums[i]
rsum -= nums[i]
ans += (lsum >= rsum)
return ans | number-of-ways-to-split-array | [C++/Python3] Very Concise Prefix Sum O(1) | Suraj1199 | 3 | 101 | number of ways to split array | 2,270 | 0.446 | Medium | 31,386 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2038636/Python-Solution-oror-O(n) | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
c=0
s=sum(nums)
k=0
for i in range(len(nums)-1):
s=s-nums[i]
c+=nums[i]
if s<=c:
k+=1
return k | number-of-ways-to-split-array | Python Solution || O(n) | a_dityamishra | 1 | 36 | number of ways to split array | 2,270 | 0.446 | Medium | 31,387 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2038271/Python-O(n)-Prefix-Sum-(Left-and-Right-Windows) | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
n = len(nums)
left_window_sum = nums[0]
right_window_sum = sum(nums[1:])
count = 0
split_pos = 0
while split_pos <= n-2:
if left_window_sum >= right_window_sum:
count += 1
split_pos += 1
left_window_sum += nums[split_pos]
right_window_sum -= nums[split_pos]
return count | number-of-ways-to-split-array | [Python] O(n) - Prefix Sum (Left and Right Windows) | andrenbrandao | 1 | 25 | number of ways to split array | 2,270 | 0.446 | Medium | 31,388 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2038107/Python-ITS-JUST-PREFIX-SUM-!!! | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
array = list(accumulate(nums, operator.add))
count=0
end = array[-1]
for i in range (len(array)-1):
left = array[i]-0
right = end - array[i]
if left >= right: count+=1
return count | number-of-ways-to-split-array | ✅ [Python] ITS JUST PREFIX SUM !!! | Jiganesh | 1 | 42 | number of ways to split array | 2,270 | 0.446 | Medium | 31,389 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2805423/Python-easy-to-read-and-understand-or-prefix-sum | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
n = len(nums)
pre, suff = [], []
sums = 0
for num in nums:
sums += num
pre.append(sums)
sums = 0
for num in nums[::-1]:
sums += num
suff.append(sums)
suff = suff[::-1]
res = 0
for i in range(n-1):
if pre[i] >= suff[i+1]:
res += 1
return res | number-of-ways-to-split-array | Python easy to read and understand | prefix-sum | sanial2001 | 0 | 2 | number of ways to split array | 2,270 | 0.446 | Medium | 31,390 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2676593/Python3-Solution-oror-O(N)-Time-and-O(1)-Space-Complexity | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
sumRight=0
for i in nums:
sumRight+=i
sumLeft=0
count=0
for i in nums[0:-1]:
sumLeft+=i
sumRight-=i
if sumLeft>=sumRight:
count+=1
return count | number-of-ways-to-split-array | Python3 Solution || O(N) Time & O(1) Space Complexity | akshatkhanna37 | 0 | 3 | number of ways to split array | 2,270 | 0.446 | Medium | 31,391 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2514612/Don't-know-why-it-is-in-medium-...(Py3) | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
cur=0
s=sum(nums)
c=0
for i in range(len(nums)-1):
cur+=nums[i]
if cur>=s-cur:c+=1
return c | number-of-ways-to-split-array | Don't know why it is in medium ...(Py3) | Xhubham | 0 | 12 | number of ways to split array | 2,270 | 0.446 | Medium | 31,392 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2306628/Prefix-sum-95-faster-Optimal-Solution-O(1)-space-complexity-O(n)-time-complexity | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
res = 0
left , right = 0, sum(nums)
for i in range(len(nums)-1):
left += nums[i]
right -= nums[i]
if left >= right:
res += 1
return res | number-of-ways-to-split-array | Prefix sum - 95% faster, Optimal Solution, O(1)-space complexity, O(n) - time complexity | Nish786 | 0 | 23 | number of ways to split array | 2,270 | 0.446 | Medium | 31,393 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2148633/Python3-prefix-sum | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
ans = prefix = 0
total = sum(nums)
for i, x in enumerate(nums):
prefix += x
if i < len(nums) - 1 and prefix >= total - prefix: ans += 1
return ans | number-of-ways-to-split-array | [Python3] prefix sum | ye15 | 0 | 22 | number of ways to split array | 2,270 | 0.446 | Medium | 31,394 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2116188/Python-Easy-to-understand-Solution | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
nums_sum = sum(nums)
n = len(nums)
ans = 0
left_list = []
left = 0
for i in range(n - 1):
left = left + nums[i]
if 2 * left >= nums_sum:
ans =ans + 1
return ans | number-of-ways-to-split-array | ✅Python Easy-to-understand Solution | chuhonghao01 | 0 | 33 | number of ways to split array | 2,270 | 0.446 | Medium | 31,395 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2093946/Python-97-Fast-or-Simple-Solution-with-comments | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
count = 0
prev_left_sum, prev_right_sum = 0, sum(nums)
for i in range(len(nums)-1):
# evaluate new left and right sum by adding / subtrating i
left_sum, right_sum = prev_left_sum + nums[i], prev_right_sum - nums[i]
# compare if the new left sum >= new right sum
if left_sum >= right_sum: count +=1
# update the previous left / right sum after processing
prev_left_sum, prev_right_sum = left_sum, right_sum
return count | number-of-ways-to-split-array | Python 97% Fast | Simple Solution with comments | Nk0311 | 0 | 49 | number of ways to split array | 2,270 | 0.446 | Medium | 31,396 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2047114/java-python-easy-prefix-sum | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
for i in range (1, len(nums)):
nums[i] += nums[i-1]
spl = 0
for i in range (0, len(nums)-1):
if nums[i] >= nums[-1] - nums[i] : spl += 1
return spl | number-of-ways-to-split-array | java, python - easy prefix sum | ZX007java | 0 | 22 | number of ways to split array | 2,270 | 0.446 | Medium | 31,397 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2046491/Python3%3A-Easy-Time-O(n)-Space-O(1) | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
right_sum = 0
# add all the integers in the list and store it in right_sum
for each in nums:
right_sum = right_sum + each
left_sum = 0
ans = 0
# for each iteration l_sum is added with ith index nums
# also r_sum is subtracted with ith index nums
for i in range(len(nums)-1):
left_sum = left_sum + nums[i]
right_sum = right_sum - nums[i]
if left_sum >= right_sum:
ans = ans + 1
return ans | number-of-ways-to-split-array | Python3: Easy - Time O(n) , Space O(1) | nkrishk | 0 | 15 | number of ways to split array | 2,270 | 0.446 | Medium | 31,398 |
https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2040868/Prefix-sum-oror-Easy-oror-python3 | class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
# We'll doing it using two sum
count=0
l=len(nums)
# Maintains the sum initially
sum1=0
sum2=sum(nums)
for i in range(l-1):
# Keeps on updating sum as we splitting array according to range
sum1+=nums[i]
sum2-=nums[i]
if sum1>=sum2:
# Increment count if follows condition
count+=1
# Return count
return count | number-of-ways-to-split-array | Prefix sum || Easy || python3 | Aniket_liar07 | 0 | 12 | number of ways to split array | 2,270 | 0.446 | Medium | 31,399 |
Subsets and Splits