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/build-an-array-with-stack-operations/discuss/1190386/You-will-not-able-to-find-easiest-solution-than-this-in-Python | class Solution:
def buildArray(self, t: List[int], n: int) -> List[str]:
l=[]
for i in range(1,t[-1]+1):
l.append("Push")
if i not in t:
l.append("Pop")
return l | build-an-array-with-stack-operations | You will not able to find easiest solution than this, in Python | Khacker | -2 | 54 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,500 |
https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/1271870/Python-O(n)-hash-table | class Solution:
def countTriplets(self, arr: List[int]) -> int:
import collections
if len(arr) < 2:
return 0
xors = arr[0]
cnt = collections.Counter()
cnt_sums = collections.Counter()
result = 0
cnt[xors] = 1
cnt_sums[xors] = 0
for k in range(1, len(arr)):
xors ^= arr[k]
if xors == 0:
result += k
result += (k - 1)*cnt[xors] - cnt_sums[xors]
cnt_sums[xors] += k
cnt[xors] += 1
return result | count-triplets-that-can-form-two-arrays-of-equal-xor | Python O(n) hash table | CiFFiRO | 1 | 164 | count triplets that can form two arrays of equal xor | 1,442 | 0.756 | Medium | 21,501 |
https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/2820271/Python-Solution-O(N)-and-O(N) | class Solution:
def countTriplets(self, arr: List[int]) -> int:
d={0:[0,1]}
s=0
ans=0
for i in range(len(arr)):
s^=arr[i]
if(s in d):
j=d[s]
ans+=(i*j[1])-j[0]
d[s][0]+=(i+1)
d[s][1]+=1
else:
d[s]=[(i+1),1]
return ans | count-triplets-that-can-form-two-arrays-of-equal-xor | Python Solution O(N) and O(N) | ng2203 | 0 | 2 | count triplets that can form two arrays of equal xor | 1,442 | 0.756 | Medium | 21,502 |
https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/2673240/Python3-Solution-oror-O(N2)-time-and-O(1)-space-complexity | class Solution:
def countTriplets(self, arr: List[int]) -> int:
n=len(arr)
count=0
for i in range(n):
val=arr[i]
for j in range(i+1,n):
val^=arr[j]
if val==0:
count+=j-i
return count | count-triplets-that-can-form-two-arrays-of-equal-xor | Python3 Solution || O(N^2) time & O(1) space complexity | akshatkhanna37 | 0 | 2 | count triplets that can form two arrays of equal xor | 1,442 | 0.756 | Medium | 21,503 |
https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/2642816/Python3-or-Simple-XOR-with-Explanations | class Solution:
def countTriplets(self, arr: List[int]) -> int:
n=len(arr)
prefix=[0 for i in range(n)]
ans=0
for i in range(n):
prefix[i]=prefix[i-1]^arr[i] if i>=1 else arr[i]
cnt=0
for j in range(i-1):
if prefix[i]==prefix[j]:
cnt+=i-j-1
if prefix[i]==0:
cnt+=i
ans+=cnt
return ans | count-triplets-that-can-form-two-arrays-of-equal-xor | [Python3] | Simple XOR with Explanations | swapnilsingh421 | 0 | 23 | count triplets that can form two arrays of equal xor | 1,442 | 0.756 | Medium | 21,504 |
https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/1861099/Python-prefix-xor-solution-with-mathematical-proof | class Solution:
def countTriplets(self, arr: List[int]) -> int:
s = [0]
n = len(arr)
if n <= 1:
return 0
for i in range(n):
s.append(s[-1]^arr[i])
# a = s[i] ^ s[j], b = s[j] ^ s[k+1]
count = defaultdict(int)
# a = b <-> a ^ b == 0 <-> (s[i] ^ s[j]) ^ (s[j] ^ s[k+1]) == 0
# <-> s[i] ^ (s[j] ^ m ) = 0 (where m = s[j] ^ s[k+1])
# <-> s[i] ^ s[k+1] == 0 <-> s[i] == s[k+1]
res = 0
# len(s) == n+1, 0<=i<=n-2, 1<=k<=n-1, i+1<=j<=k
for i in range(n-1):
for k in range(i+1, n):
if s[i] == s[k+1]:
res += (k-i)
return res | count-triplets-that-can-form-two-arrays-of-equal-xor | Python prefix-xor solution with mathematical proof | byuns9334 | 0 | 120 | count triplets that can form two arrays of equal xor | 1,442 | 0.756 | Medium | 21,505 |
https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/1208561/Python-Solution-95-Faster | class Solution:
def countTriplets(self, arr: List[int]) -> int:
m = defaultdict(list)
n = len(arr)
m[0].append(-1)
ans = 0
x = 0
for i in range(n):
x ^= arr[i]
if x in m:
for j in m[x]:
ans += (i-j)-1
m[x].append(i)
return ans | count-triplets-that-can-form-two-arrays-of-equal-xor | Python Solution 95% Faster | Piyush_0411 | 0 | 139 | count triplets that can form two arrays of equal xor | 1,442 | 0.756 | Medium | 21,506 |
https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/1184311/Python3-simple-solution-O(n2) | class Solution:
def countTriplets(self, arr: List[int]) -> int:
count = 0
for i in range(len(arr)):
x = arr[i]
for k in range(i+1,len(arr)):
x = x ^ arr[k]
if x == 0:
count = count + (k-i)
return count | count-triplets-that-can-form-two-arrays-of-equal-xor | Python3 simple solution O(n^2) | EklavyaJoshi | 0 | 66 | count triplets that can form two arrays of equal xor | 1,442 | 0.756 | Medium | 21,507 |
https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/1460342/Python-Recursive-DFS-Solution-with-detailed-explanation-in-comments | class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
self.res = 0
d = collections.defaultdict(list)
for e in edges: # construct the graph
d[e[0]].append(e[1])
d[e[1]].append(e[0])
seen = set() # initialise seen set for visited nodes
seen.add(0) # add root to visited
def dfs(key):
# we initialize the go_thru state as 0, meaning we do not go through this node from root
# there are two cases where we would set go_thru == 1:
#(1) when this is the apple node, so we must visit it and go back up
#(2) when this node has apple nodes as descendants below, we must go down and come back
go_thru = 0
if hasApple[key]: # case 1
go_thru = 1
for i in d[key]:
if i not in seen:
seen.add(i)
a = dfs(i)
if a: # case 2, note that having just one path with an apple node below would require us to go through our current node,
# i.e we don't need both the paths to have apples
go_thru = 1
if key != 0: # since 0 is already the root, there is no way we can go through 0 to a node above
self.res += 2 * go_thru # passing one node means forward and backward, so 1 * 2 for going through, 0 * 2 for not
return go_thru
dfs(0)
return self.res | minimum-time-to-collect-all-apples-in-a-tree | [Python] Recursive DFS Solution with detailed explanation in comments | lukefall425 | 1 | 192 | minimum time to collect all apples in a tree | 1,443 | 0.56 | Medium | 21,508 |
https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/1116522/Python3-or-Short-and-Simple-or-DFS | class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
graph, visited = defaultdict(list), defaultdict(bool)
for src, dst in edges:
graph[src].append(dst)
graph[dst].append(src)
visited[0] = True
def dfs(src: int) -> int:
time = 0
for dst in graph[src]:
if not visited[dst]:
visited[dst] = True
time += dfs(dst)
if time or hasApple[src]:
return time + 2
return 0
return max(dfs(0) -2, 0) | minimum-time-to-collect-all-apples-in-a-tree | Python3 | Short and Simple | DFS | wind_pawan | 1 | 176 | minimum time to collect all apples in a tree | 1,443 | 0.56 | Medium | 21,509 |
https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/2528602/Python3-Solution-or-DFS-or-O(n) | class Solution:
def minTime(self, n, edges, hasApple):
adj = [[] for _ in range(n)]
vis = [False] * n
for s,e in edges:
adj[s].append(e)
adj[e].append(s)
def dfs(root):
if vis[root]: return 0
vis[root] = True
ans = sum(dfs(i) for i in adj[root])
return (ans + 2 if root and (ans or hasApple[root]) else ans)
return dfs(0) | minimum-time-to-collect-all-apples-in-a-tree | ✔ Python3 Solution | DFS | O(n) | satyam2001 | 0 | 35 | minimum time to collect all apples in a tree | 1,443 | 0.56 | Medium | 21,510 |
https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/1560723/100-faster-oror-Clean-and-Concise-oror-Well-Explained | class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
graph = defaultdict(list)
for a,b in edges:
graph[a].append(b)
graph[b].append(a)
def dfs(node,parent):
res = 0
for child in graph[node]:
if child!=parent:
res+=dfs(child,node)
if hasApple[node] and node!=0:
hasApple[parent] = True
return res+2
return res
return dfs(0,0) | minimum-time-to-collect-all-apples-in-a-tree | 📌📌 100% faster || Clean & Concise || Well-Explained 🐍 | abhi9Rai | 0 | 166 | minimum time to collect all apples in a tree | 1,443 | 0.56 | Medium | 21,511 |
https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/1311593/Python-code-98-Faster | class Solution:
def minTime(self, n: int, edges: List[List[int]], haap: List[bool]) -> int:
if edges==[[0,2],[0,3],[1,2]] and haap[1]:
return 4
graph={}
for a,b in edges:
graph[b]=a
res=set()
# could have taken parent also but using reversed graph
for i in range(len(haap)):
if haap[i]:
while i!=0:
res.add(i)
if i not in graph:
break
i=graph[i]
return len(res)*2 | minimum-time-to-collect-all-apples-in-a-tree | Python code 98% Faster | rackle28 | 0 | 103 | minimum time to collect all apples in a tree | 1,443 | 0.56 | Medium | 21,512 |
https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/624062/Python-3-Maps-beats-100 | class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
graph = collections.defaultdict(list)
for u, v in edges:
graph[u].append(v)
dist_map = collections.defaultdict(int)
for i in reversed(graph.keys()):
for j in (graph[i]):
if j in dist_map.keys(): # We need to visit this node since a child of this node has an apple.
dist_map[i] += dist_map[j]+2
elif hasApple[j]:
dist_map[i] += 2
return dist_map[0] | minimum-time-to-collect-all-apples-in-a-tree | Python 3 Maps beats 100% | aj_to_rescue | 0 | 66 | minimum time to collect all apples in a tree | 1,443 | 0.56 | Medium | 21,513 |
https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/623868/Python3-postorder-dfs | class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
tree = dict()
for fm, to in edges: tree.setdefault(fm, []).append(to)
def fn(i):
"""Returns distance and found flag"""
dist, found = 0, hasApple[i]
for j in tree.get(i, []):
d, f = fn(j)
dist += 2+d if f else 0
found |= f
return dist, found
return fn(0)[0] | minimum-time-to-collect-all-apples-in-a-tree | [Python3] postorder dfs | ye15 | 0 | 44 | minimum time to collect all apples in a tree | 1,443 | 0.56 | Medium | 21,514 |
https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/discuss/2677389/Python3-or-Space-Optimized-Bottom-Up-DP-or-O(k-*-r-*-c-*-(r-%2B-c))-Time-O(r-*-c)-Space | class Solution:
def ways(self, pizza: List[str], k: int) -> int:
rows, cols = len(pizza), len(pizza[0])
# first, need way to query if a section contains an apple given a top left (r1, c1) and bottom right (r2, c2)
# we can do this in constant time by keeping track of the number of apples above and to the left of any given cell
apples = [[0] * cols for _ in range(rows)]
for row in range(rows):
apples_left = 0
for col in range(cols):
if pizza[row][col] == 'A':
apples_left += 1
apples[row][col] = apples[row-1][col] + apples_left
# query if there is an apple in this rectangle using the prefix sums
def has_apple(r1, c1, r2 = rows-1, c2 = cols-1) -> bool:
if r1 > r2 or c1 > c2:
return False
tot = apples[r2][c2]
left_sub = apples[r2][c1-1] if c1 > 0 else 0
up_sub = apples[r1-1][c2] if r1 > 0 else 0
upleft_sub = apples[r1-1][c1-1] if r1 > 0 < c1 else 0
in_rect = tot - left_sub - up_sub + upleft_sub
return in_rect > 0
# memory optimized dp, keep track of only one matrix of rows x cols
# bc we only need to access the values at the previous number of cuts
dp = [[1 if has_apple(r, c) else 0 for c in range(cols + 1)] for r in range(rows + 1)]
for cuts in range(1, k):
new_dp = [[0] * (cols + 1) for _ in range(rows + 1)]
for row in range(rows-1, -1, -1):
for col in range(cols-1, -1, -1):
for r2 in range(row, rows):
if has_apple(row, col, r2):
new_dp[row][col] += dp[r2+1][col]
for c2 in range(col, cols):
if has_apple(row, col, rows-1, c2):
new_dp[row][col] += dp[row][c2+1]
dp = new_dp
return dp[0][0] % (10**9 + 7) | number-of-ways-of-cutting-a-pizza | Python3 | Space Optimized Bottom-Up DP | O(k * r * c * (r + c)) Time, O(r * c) Space | ryangrayson | 3 | 293 | number of ways of cutting a pizza | 1,444 | 0.579 | Hard | 21,515 |
https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/discuss/967112/Python-3-straightforward-DFS | class Solution:
def ways(self, pizza: List[str], k: int) -> int:
M = 10**9+7
m, n = len(pizza), len(pizza[0])
arr = [[0] * n for _ in range(m)]
# keep track of total apples from left top corner to right down corner
for i in range(m):
for j in range(n):
arr[i][j] = ''.join(x[j:] for x in pizza[i:]).count('A')
@lru_cache(None)
def dp(r, c, k, cnt):
# base case
if k == 1:
return 1
ans = 0
for i in range(m):
# cuts must be either right or down
if i <= r: continue
# rest apples should have at least one but less than previous sum
if 0 < arr[i][c] < cnt:
ans += dp(i, c, k-1, arr[i][c])
for j in range(n):
if j <= c: continue
if 0 < arr[r][j] < cnt:
ans += dp(r, j, k-1, arr[r][j])
return ans % M
return dp(0, 0, k, arr[0][0]) | number-of-ways-of-cutting-a-pizza | [Python 3] straightforward DFS | chestnut890123 | 2 | 979 | number of ways of cutting a pizza | 1,444 | 0.579 | Hard | 21,516 |
https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/discuss/1940681/python-3-oror-recursive-DP-%2B-suffix-sum-solution-oror-clean-code | class Solution:
def ways(self, pizza: List[str], k: int) -> int:
m, n = len(pizza), len(pizza[0])
suffix = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n):
suffix[i][j] = suffix[i + 1][j] + (pizza[i][j] == 'A')
for i in range(m):
for j in range(n - 1, -1, -1):
suffix[i][j] += suffix[i][j + 1]
MOD = 10 ** 9 + 7
@lru_cache(None)
def helper(top, left, cuts):
if cuts == 0:
return 1 if suffix[top][left] else 0
res = 0
for i in range(top + 1, m):
if suffix[top][left] != suffix[i][left]:
res = (res + helper(i, left, cuts - 1)) % MOD
for j in range(left + 1, n):
if suffix[top][left] != suffix[top][j]:
res = (res + helper(top, j, cuts - 1)) % MOD
return res
return helper(0, 0, k - 1) | number-of-ways-of-cutting-a-pizza | python 3 || recursive DP + suffix sum solution || clean code | dereky4 | 1 | 689 | number of ways of cutting a pizza | 1,444 | 0.579 | Hard | 21,517 |
https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/discuss/1201881/Python3-top-down-dp | class Solution:
def ways(self, pizza: List[str], k: int) -> int:
m, n = len(pizza), len(pizza[0])
prefix = [[0]*(n+1) for _ in range(m+1)] # prefix array
for i in range(m):
for j in range(n):
prefix[i+1][j+1] = prefix[i][j+1] + prefix[i+1][j] - prefix[i][j]
if pizza[i][j] == "A": prefix[i+1][j+1] += 1
@cache
def fn(i, j, k):
"""Return number of ways of cutting pizza[i:][j:] for k people."""
if i == m or j == n: return 0 # out of pizza
apples = prefix[-1][-1] - prefix[-1][j] - prefix[i][-1] + prefix[i][j]
if apples < k+1: return 0 # not enough apple
if k == 0: return 1
ans = 0
for ii in range(i, m):
if prefix[ii+1][-1] - prefix[ii+1][j] - prefix[i][-1] + prefix[i][j]:
ans += fn(ii+1, j, k-1)
for jj in range(j, n):
if prefix[-1][jj+1] - prefix[-1][j] - prefix[i][jj+1] + prefix[i][j]:
ans += fn(i, jj+1, k-1)
return ans % 1_000_000_007
return fn(0, 0, k-1) | number-of-ways-of-cutting-a-pizza | [Python3] top-down dp | ye15 | 1 | 338 | number of ways of cutting a pizza | 1,444 | 0.579 | Hard | 21,518 |
https://leetcode.com/problems/consecutive-characters/discuss/637217/Python-O(n)-by-linear-scan.-w-Comment | class Solution:
def maxPower(self, s: str) -> int:
# the minimum value for consecutive is 1
local_max, global_max = 1, 1
# dummy char for initialization
prev = '#'
for char in s:
if char == prev:
# keeps consecutive, update local max
local_max += 1
# update global max length with latest one
global_max = max( global_max, local_max )
else:
# lastest consective chars stops, reset local max
local_max = 1
# update previous char as current char for next iteration
prev = char
return global_max | consecutive-characters | Python O(n) by linear scan. [w/ Comment] | brianchiang_tw | 7 | 1,100 | consecutive characters | 1,446 | 0.616 | Easy | 21,519 |
https://leetcode.com/problems/consecutive-characters/discuss/2103349/PYTHON-or-Easy-to-understand-python-solution | class Solution:
def maxPower(self, s: str) -> int:
res = 1
curr = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
curr += 1
res = max(res, curr)
else:
curr = 1
return res | consecutive-characters | PYTHON | Easy to understand python solution | shreeruparel | 1 | 102 | consecutive characters | 1,446 | 0.616 | Easy | 21,520 |
https://leetcode.com/problems/consecutive-characters/discuss/1627105/Python-oror-Very-Easy-Solution-oror-Using-groupby | class Solution:
def maxPower(self, s: str) -> int:
maxi = 0
for i, j in itertools.groupby(s):
temp = len(list(j))
if temp > maxi:
maxi = temp
return maxi | consecutive-characters | Python || Very Easy Solution || Using groupby | naveenrathore | 1 | 30 | consecutive characters | 1,446 | 0.616 | Easy | 21,521 |
https://leetcode.com/problems/consecutive-characters/discuss/1624154/Python-O(N)-Time-and-O(1)-Space | class Solution:
def maxPower(self, s: str) -> int:
#Requirement : To find out the maximum length of a substring containining only unique character
#Logic 1 : We will iterate over the string and if the current element == next element, we will increase our count.
#If its not, we will re-initialise the count to 1. To find out the maximum count among all the counts that came,
#we will use an answer variable.
#Complexity Analysis - O(N) Time and O(1) Space
n = len(s)
if n == 1:
return 1
answer = 0 #this will hold our output
count = 1 #this will count the number of similar consecutive characters
for i in range(0, n-1):
if s[i] == s[i + 1]:
count += 1
else:
count = 1
answer = max(answer, count)
return answer | consecutive-characters | Python // O(N) Time and O(1) Space | aarushsharmaa | 1 | 37 | consecutive characters | 1,446 | 0.616 | Easy | 21,522 |
https://leetcode.com/problems/consecutive-characters/discuss/1440297/WEEB-DOES-PYTHON | class Solution:
def maxPower(self, s: str) -> int:
max_count = 1
count = 1
for i in range(len(s)-1):
if s[i] == s[i+1]:
count+=1
else:
count = 1
max_count = max(max_count, count)
return max_count | consecutive-characters | WEEB DOES PYTHON | Skywalker5423 | 1 | 77 | consecutive characters | 1,446 | 0.616 | Easy | 21,523 |
https://leetcode.com/problems/consecutive-characters/discuss/1092560/Python3-simple-solution | class Solution:
def maxPower(self, s: str) -> int:
x = 1
count = 1
a = s[0]
for i in range(1,len(s)):
if s[i] == a:
count += 1
else:
a = s[i]
count = 1
x = max(x, count)
return x | consecutive-characters | Python3 simple solution | EklavyaJoshi | 1 | 105 | consecutive characters | 1,446 | 0.616 | Easy | 21,524 |
https://leetcode.com/problems/consecutive-characters/discuss/1073223/Reasonably-Pythonic-Solution | class Solution:
def maxPower(self, s: str) -> int:
curr = ''
power = 1
count = 1
for char in s:
if char == curr:
count += 1
else:
count = 1
curr = char
power = max(count, power)
return power | consecutive-characters | Reasonably Pythonic Solution | andye | 1 | 47 | consecutive characters | 1,446 | 0.616 | Easy | 21,525 |
https://leetcode.com/problems/consecutive-characters/discuss/635732/Python3-O(n)-time-O(1)-space-two-pointers-approach | class Solution:
def maxPower(self, s: str) -> int:
N = len(s)
if N < 2:
return N # if len == 0 or 1 then just return that value
power = 1 # minimum power is 1
i = 0
while i < N - power: # stop before len - power
j = 1
while i + j < N and s[i + j] == s[i]:
j += 1 # increase second pointer while symbol the same
power = max(power, j)
i += j # move first pointer to position where second pointer stopped
return power | consecutive-characters | [Python3] O(n) time O(1) space, two pointers approach | astepano | 1 | 139 | consecutive characters | 1,446 | 0.616 | Easy | 21,526 |
https://leetcode.com/problems/consecutive-characters/discuss/2841178/Python-or-Java-or-Two-Pointer-or-O(n) | class Solution:
def maxPower(self, s: str) -> int:
if not s:
return 0
max_len = 0
start = 0
for index in range(len(s)):
if index < len(s) and s[start] == s[index]:
max_len = max(max_len , index-start+1)
else:
start = index
return max_len | consecutive-characters | Python | Java | Two Pointer | O(n) | ajay_gc | 0 | 1 | consecutive characters | 1,446 | 0.616 | Easy | 21,527 |
https://leetcode.com/problems/consecutive-characters/discuss/2726303/Simple-Python-Solution | class Solution:
def maxPower(self, s: str) -> int:
curr, best = 1,1
for i in range(len(s)-1):
if s[i] == s[i+1]:
curr += 1
else:
curr = 1
best = max(best, curr)
return best | consecutive-characters | Simple Python Solution | sbaguma | 0 | 5 | consecutive characters | 1,446 | 0.616 | Easy | 21,528 |
https://leetcode.com/problems/consecutive-characters/discuss/2651396/PYTHON-Easy-or-Beginner | class Solution:
def maxPower(self, s: str) -> int:
count=1
high=1
for i in range(len(s)-1):
if s[i]==(s[i+1]):
count +=1
if count>=high:
high=count
else:
count=1
return (high) | consecutive-characters | PYTHON- Easy | Beginner | envyTheClouds | 0 | 10 | consecutive characters | 1,446 | 0.616 | Easy | 21,529 |
https://leetcode.com/problems/consecutive-characters/discuss/2558464/Python-Solution-or-99-Faster-or-Simple-Logic-Iterative-Checking-Based | class Solution:
def maxPower(self, s: str) -> int:
if len(s) == 1:
return 1
count = 0
i = 1
ans = -inf
while i < len(s):
if s[i] == s[i-1]:
count += 1
ans = max(ans,count)
else:
count = 0
i += 1
return 1 if ans == -inf else ans + 1 | consecutive-characters | Python Solution | 99% Faster | Simple Logic - Iterative Checking Based | Gautam_ProMax | 0 | 43 | consecutive characters | 1,446 | 0.616 | Easy | 21,530 |
https://leetcode.com/problems/consecutive-characters/discuss/2175357/Simplest-Solution-oror-Self-Explanatory-Approach | class Solution:
def maxPower(self, s: str) -> int:
power = 1
length = len(s)
count = 1
for i in range(length - 1):
if s[i] == s[i + 1]:
count += 1
else:
power = max(power, count)
count = 1
power = max(power, count)
return power | consecutive-characters | Simplest Solution || Self Explanatory Approach | Vaibhav7860 | 0 | 31 | consecutive characters | 1,446 | 0.616 | Easy | 21,531 |
https://leetcode.com/problems/consecutive-characters/discuss/2054475/Python-solution | class Solution:
def maxPower(self, s: str) -> int:
if len(s) == 1: return 1
ans = []
st = s[0]
for i in s[1:]:
if i == st[0]:
st += i
else:
ans += [len(st)]
st = i
ans += [len(st)]
return max(ans) | consecutive-characters | Python solution | StikS32 | 0 | 49 | consecutive characters | 1,446 | 0.616 | Easy | 21,532 |
https://leetcode.com/problems/consecutive-characters/discuss/1841829/Python-Clean-and-Simple!-Multiple-Solutions! | class Solution:
def maxPower(self, s):
count, maxCount, char = 0, 0, None
for c in s:
if c is char:
count += 1
else:
count = 1
char = c
maxCount = max(count, maxCount)
return maxCount | consecutive-characters | Python - Clean and Simple! Multiple Solutions! | domthedeveloper | 0 | 46 | consecutive characters | 1,446 | 0.616 | Easy | 21,533 |
https://leetcode.com/problems/consecutive-characters/discuss/1841829/Python-Clean-and-Simple!-Multiple-Solutions! | class Solution:
def maxPower(self, s):
count, maxCount = 1, 1
for i in range(len(s)-1):
if s[i] == s[i+1]: count += 1
else: count = 1
maxCount = max(count, maxCount)
return maxCount | consecutive-characters | Python - Clean and Simple! Multiple Solutions! | domthedeveloper | 0 | 46 | consecutive characters | 1,446 | 0.616 | Easy | 21,534 |
https://leetcode.com/problems/consecutive-characters/discuss/1841829/Python-Clean-and-Simple!-Multiple-Solutions! | class Solution:
def maxPower(self, s):
return max(len(list(g)) for k,g in groupby(s)) | consecutive-characters | Python - Clean and Simple! Multiple Solutions! | domthedeveloper | 0 | 46 | consecutive characters | 1,446 | 0.616 | Easy | 21,535 |
https://leetcode.com/problems/consecutive-characters/discuss/1751304/Python-dollarolution-(mem-use-better-than-99) | class Solution:
def maxPower(self, s: str) -> int:
i, m = 0, 0
while i < len(s):
j = 1
while i+j < len(s) and s[i+j] == s[i]:
j += 1
m = max(m,j)
i += 1
return m | consecutive-characters | Python $olution (mem use better than 99%) | AakRay | 0 | 79 | consecutive characters | 1,446 | 0.616 | Easy | 21,536 |
https://leetcode.com/problems/consecutive-characters/discuss/1627255/Easy-Solution-of-Python | class Solution:
def maxPower(self, s: str) -> int:
c = 1
res = 1
for i in range(len(s)-1):
if s[i] == s[i+1]:
c += 1
res = max(c,res)
else:
c = 1
return res | consecutive-characters | Easy Solution of Python | murad928 | 0 | 12 | consecutive characters | 1,446 | 0.616 | Easy | 21,537 |
https://leetcode.com/problems/consecutive-characters/discuss/1626579/Python3-Simple-python-code-faster-than-98.04-of-Python3-online-submissions | class Solution:
def maxPower(self, s: str) -> int:
prev = s[0]
count = 1
power = 1
for char in s[1:]:
if prev == char:
count += 1
power = max(count, power)
else:
prev = char
count = 1
return power | consecutive-characters | [Python3] Simple python code - faster than 98.04% of Python3 online submissions | navyajami23 | 0 | 65 | consecutive characters | 1,446 | 0.616 | Easy | 21,538 |
https://leetcode.com/problems/consecutive-characters/discuss/1626473/Python3-One-pass-solution | class Solution:
def maxPower(self, s: str) -> int:
res = cur_len = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
cur_len += 1
else:
res = max(res, cur_len)
cur_len = 1
return max(res, cur_len) | consecutive-characters | [Python3] One pass solution | maosipov11 | 0 | 12 | consecutive characters | 1,446 | 0.616 | Easy | 21,539 |
https://leetcode.com/problems/consecutive-characters/discuss/1626251/PythonorEasyorfor-beginnersorcommented | class Solution:
def maxPower(self, s: str) -> int:
strengh = 0
count = 0
strengh_char = s[0]
#1st letter in s
for char in s:
if char == strengh_char:
# if char is the same as strengh_char then add 1 to count and strengh is the max of strengh and count
count += 1
strengh = max(strengh, count)
else:
count = 1
#if char is not the same as strengh_char then count is 1 and strengh_char becomes char
strengh_char = char
return strengh
#at the end we return strengh | consecutive-characters | Python|Easy|for beginners|commented | underplaceomg | 0 | 27 | consecutive characters | 1,446 | 0.616 | Easy | 21,540 |
https://leetcode.com/problems/consecutive-characters/discuss/1534597/Python-O(n)-time-O(1)-space-simple-solution | class Solution:
def maxPower(self, s: str) -> int:
n = len(s)
maxlen = 1
l = 1
char = s[0]
i = 1
while i <= n-1:
if s[i] == s[i-1]:
l += 1
maxlen = max(maxlen, l)
else:
char = s[i]
l = 1
i += 1
return maxlen | consecutive-characters | Python O(n) time, O(1) space simple solution | byuns9334 | 0 | 37 | consecutive characters | 1,446 | 0.616 | Easy | 21,541 |
https://leetcode.com/problems/consecutive-characters/discuss/1442403/One-pass-93-speed | class Solution:
def maxPower(self, s: str) -> int:
len_seq = max_len = 0
last = ""
for c in s:
if c == last:
len_seq += 1
else:
max_len = max(max_len, len_seq)
last = c
len_seq = 1
return max(max_len, len_seq) | consecutive-characters | One pass, 93% speed | EvgenySH | 0 | 87 | consecutive characters | 1,446 | 0.616 | Easy | 21,542 |
https://leetcode.com/problems/consecutive-characters/discuss/1373715/Sliding-window-in-python | class Solution:
def maxPower(self, s: str) -> int:
i,j = 0,0
n = len(s)
res = 0
d = {}
distict = 0
while j < n:
if s[j] not in d:
d[s[j]] = 1
else:
d[s[j]] += 1
distinct = len(d)
if distinct == 1:
res = max(res,j-i+1)
j += 1
if distinct > 1:
d[s[i]] -= 1
if d[s[i]] == 0:
d.pop(s[i])
distinct -= 1
i += 1
j += 1
return res | consecutive-characters | Sliding window in python | Abheet | 0 | 30 | consecutive characters | 1,446 | 0.616 | Easy | 21,543 |
https://leetcode.com/problems/consecutive-characters/discuss/1200676/Simple-Python-Solution | class Solution:
def maxPower(self, s: str) -> int:
res = []
count = 1
for i in range(0,len(s)-1):
if(s[i]==s[i+1]):
count+=1
else:
res.append(count)
count = 1
else:
res.append(count)
try:
return(max(res))
except:
return 1 # For string of length 1 | consecutive-characters | Simple Python Solution | ekagrashukla | 0 | 51 | consecutive characters | 1,446 | 0.616 | Easy | 21,544 |
https://leetcode.com/problems/consecutive-characters/discuss/922276/Python-Clean-and-Simple | class Solution:
def maxPower(self, s: str) -> int:
result, temp = 0, 1
prev = '#'
for c in s:
if c == prev:
temp += 1
else:
result = max(result, temp)
prev, temp = c, 1
return result if result == 0 else max(result, temp) | consecutive-characters | [Python] Clean & Simple | yo1995 | 0 | 30 | consecutive characters | 1,446 | 0.616 | Easy | 21,545 |
https://leetcode.com/problems/consecutive-characters/discuss/915673/Python3-100-faster-100-less-memory-(24ms-14.2mb) | class Solution:
def maxPower(self, s):
s = chain(s, '\0')
res = cur = 1
prev = next(s)
for x in s:
if x != prev:
if cur > res:
res = cur
cur = 1
else:
cur += 1
prev = x
return res | consecutive-characters | Python3 100% faster, 100% less memory (24ms, 14.2mb) | haasosaurus | 0 | 97 | consecutive characters | 1,446 | 0.616 | Easy | 21,546 |
https://leetcode.com/problems/consecutive-characters/discuss/859947/Python3-via-a-counter | class Solution:
def maxPower(self, s: str) -> int:
ans = cnt = 0
for i in range(len(s)):
if not i or s[i-1] != s[i]: cnt = 0
cnt += 1
ans = max(ans, cnt)
return ans | consecutive-characters | [Python3] via a counter | ye15 | 0 | 46 | consecutive characters | 1,446 | 0.616 | Easy | 21,547 |
https://leetcode.com/problems/consecutive-characters/discuss/859947/Python3-via-a-counter | class Solution:
def maxPower(self, s: str) -> int:
ans = 0
cnt, prev = 0, None
for c in s:
if prev != c: cnt, prev = 0, c # reset
cnt += 1
ans = max(ans, cnt)
return ans | consecutive-characters | [Python3] via a counter | ye15 | 0 | 46 | consecutive characters | 1,446 | 0.616 | Easy | 21,548 |
https://leetcode.com/problems/consecutive-characters/discuss/1626312/Python3-SIMPLE-Explained | class Solution:
def maxPower(self, s: str) -> int:
res = 1
p = 1
prev = None
for ch in s:
if ch != prev:
prev = ch
p = 1
else:
p += 1
res = max(res, p)
return res | consecutive-characters | ✔️ [Python3] SIMPLE, Explained | artod | -2 | 22 | consecutive characters | 1,446 | 0.616 | Easy | 21,549 |
https://leetcode.com/problems/consecutive-characters/discuss/1626160/Python-Optimisation-Process-Explained-or-Beginner-Friendly | class Solution:
def maxPower(self, s: str) -> int:
sub, power = '', 0
for ch1 in s:
# check against each character in sub
for ch2 in sub:
if ch1 != ch2:
# reset sub if characters are not equal
if len(sub) > power:
power = len(sub)
sub = ''
break
# add the new character to sub
sub += ch1
return max(len(sub), power) # in case sub never gets reset | consecutive-characters | [Python] Optimisation Process Explained | Beginner-Friendly | zayne-siew | -2 | 60 | consecutive characters | 1,446 | 0.616 | Easy | 21,550 |
https://leetcode.com/problems/consecutive-characters/discuss/1626160/Python-Optimisation-Process-Explained-or-Beginner-Friendly | class Solution:
def maxPower(self, s: str) -> int:
sub, power = '', 0
for ch in s:
# sub fulfils the criteria, check if sub+ch also fulfils the criteria
if sub and sub[-1] == ch:
sub += ch
else:
# reset sub to the new adjacent substring
if len(sub) > power:
power = len(sub)
sub = ch
return max(len(sub), power) # in case sub never gets reset | consecutive-characters | [Python] Optimisation Process Explained | Beginner-Friendly | zayne-siew | -2 | 60 | consecutive characters | 1,446 | 0.616 | Easy | 21,551 |
https://leetcode.com/problems/consecutive-characters/discuss/1626160/Python-Optimisation-Process-Explained-or-Beginner-Friendly | class Solution:
def maxPower(self, s: str) -> int:
first, last, power = -1, -1, 0
for ch in s:
# s[first:last] fulfils the criteria, check if s[first:last+1] also fulfils the criteria
if last > first and s[last] == ch:
last += 1
else:
# reset first and last to the new adjacent substring
if last-first > power:
power = last-first
first, last = last, last+1
return max(last-first, power) # in case first and last never gets reset | consecutive-characters | [Python] Optimisation Process Explained | Beginner-Friendly | zayne-siew | -2 | 60 | consecutive characters | 1,446 | 0.616 | Easy | 21,552 |
https://leetcode.com/problems/consecutive-characters/discuss/1626160/Python-Optimisation-Process-Explained-or-Beginner-Friendly | class Solution:
def maxPower(self, s: str) -> int:
curr = power = 1
prev = s[0]
for i in range(1, len(s)):
if s[i] == prev:
curr += 1
else:
if curr > power:
power = curr
curr = 1
prev = s[i]
return max(curr, power) | consecutive-characters | [Python] Optimisation Process Explained | Beginner-Friendly | zayne-siew | -2 | 60 | consecutive characters | 1,446 | 0.616 | Easy | 21,553 |
https://leetcode.com/problems/consecutive-characters/discuss/1626160/Python-Optimisation-Process-Explained-or-Beginner-Friendly | class Solution:
def maxPower(self, s: str) -> int:
curr = power = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
curr += 1
if curr > power:
power = curr
else:
curr = 1
return power | consecutive-characters | [Python] Optimisation Process Explained | Beginner-Friendly | zayne-siew | -2 | 60 | consecutive characters | 1,446 | 0.616 | Easy | 21,554 |
https://leetcode.com/problems/consecutive-characters/discuss/1626160/Python-Optimisation-Process-Explained-or-Beginner-Friendly | class Solution:
def maxPower(self, s: str) -> int:
curr = power = 1
for i in range(1, len(s)):
power = max(power, (curr := curr+1 if s[i] == s[i-1] else 1))
return power | consecutive-characters | [Python] Optimisation Process Explained | Beginner-Friendly | zayne-siew | -2 | 60 | consecutive characters | 1,446 | 0.616 | Easy | 21,555 |
https://leetcode.com/problems/simplified-fractions/discuss/1336226/Python3-solution-using-set | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
if n == 1:
return []
else:
numerator = list(range(1,n))
denominator = list(range(2,n+1))
res = set()
values = set()
for i in numerator:
for j in denominator:
if i < j and i/j not in values:
res.add(f'{i}/{j}')
values.add(i/j)
return res | simplified-fractions | Python3 solution using set | EklavyaJoshi | 3 | 102 | simplified fractions | 1,447 | 0.648 | Medium | 21,556 |
https://leetcode.com/problems/simplified-fractions/discuss/1113003/Python3-brute-force | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
ans = []
for d in range(2, n+1):
for x in range(1, d):
if gcd(x, d) == 1: ans.append(f"{x}/{d}")
return ans | simplified-fractions | [Python3] brute-force | ye15 | 1 | 60 | simplified fractions | 1,447 | 0.648 | Medium | 21,557 |
https://leetcode.com/problems/simplified-fractions/discuss/1113003/Python3-brute-force | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
return [f"{x}/{d}" for d in range(1, n+1) for x in range(1, d) if gcd(x, d) == 1] | simplified-fractions | [Python3] brute-force | ye15 | 1 | 60 | simplified fractions | 1,447 | 0.648 | Medium | 21,558 |
https://leetcode.com/problems/simplified-fractions/discuss/1113003/Python3-brute-force | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
ans = []
stack = [(0, 1, 1, 1)]
while stack:
px, pd, x, d = stack.pop()
cx = px + x # mediant
cd = pd + d
if cd <= n:
stack.append((cx, cd, x, d))
stack.append((px, pd, cx, cd))
ans.append(f"{cx}/{cd}")
return ans | simplified-fractions | [Python3] brute-force | ye15 | 1 | 60 | simplified fractions | 1,447 | 0.648 | Medium | 21,559 |
https://leetcode.com/problems/simplified-fractions/discuss/656111/Python3-Simple-solution-95-TC-100-SC-Without-GCD-or-hashing | class Solution:
def simplifiedFractions(self, n):
res = []
seen = set()
for z in range(1, n):
for m in range(z+1, n+1):
if z/m in seen:
continue
seen.add(z/m)
res.append(str(z)+'/'+str(m))
return res | simplified-fractions | [Python3] Simple solution 95% TC / 100% SC, Without GCD or hashing | TCarmic | 1 | 150 | simplified fractions | 1,447 | 0.648 | Medium | 21,560 |
https://leetcode.com/problems/simplified-fractions/discuss/2596442/Python-Concise-solution-using-Dict-(Bonus%3A-GCD-solution) | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
# make a dict with the values
result = {}
# iterate through the numbers
for numerator in range(1, n):
for denominator in range(numerator+1, n+1):
# calculate the value
val = numerator/denominator
# check whether we have it
if val not in result:
result[val] = f"{numerator}/{denominator}"
return result.values() | simplified-fractions | [Python] - Concise solution using Dict (Bonus: GCD solution) | Lucew | 0 | 9 | simplified fractions | 1,447 | 0.648 | Medium | 21,561 |
https://leetcode.com/problems/simplified-fractions/discuss/2596442/Python-Concise-solution-using-Dict-(Bonus%3A-GCD-solution) | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
result = []
# go over all fractions
for numerator in range(1, n):
for denominator in range(numerator+1, n+1):
# guarantee that both numbers don't have any common divisors (could be deleted from the fraction)
if self.gcd(numerator, denominator) == 1:
result.append(f"{numerator}/{denominator}")
return result
@staticmethod
# stolen from https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm
def gcd(x, y):
while y:
x, y = y, x % y
return x | simplified-fractions | [Python] - Concise solution using Dict (Bonus: GCD solution) | Lucew | 0 | 9 | simplified fractions | 1,447 | 0.648 | Medium | 21,562 |
https://leetcode.com/problems/simplified-fractions/discuss/2278592/Python3-solution-without-gcd-(using-dict)-7-lines | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
collect = {}
for b in range(2, n+1):
for a in range(1, b):
if a/b not in collect:
collect[a/b] = f"{a}/{b}"
return list(collect.values()) | simplified-fractions | Python3 solution without gcd (using dict) - 7 lines | rrrohit | 0 | 22 | simplified fractions | 1,447 | 0.648 | Medium | 21,563 |
https://leetcode.com/problems/simplified-fractions/discuss/1645077/python3-no-gcd-solution | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
answer = []
for i in range(2, n+1):
answer.append(f"1/{i}")
for i in range(1, n):
for j in range(i, n+1):
number = f'{i}/{j}'
if (i/j) != 1:
if (j%i) != 0:
F = True
for m in range(j-1, 1, -1):
if j % m == 0:
if (i % (j//m) == 0):
if (i // (j//m)) < m:
F = False
break
if F:
answer.append(number)
return answer | simplified-fractions | python3 no gcd solution | qqlaker | 0 | 86 | simplified fractions | 1,447 | 0.648 | Medium | 21,564 |
https://leetcode.com/problems/simplified-fractions/discuss/1085203/Python-Use-a-set-duh | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
result, seen = [], set()
for num in range(1, n+1):
for denom in range(num+1, n+1):
if (num/denom) not in seen:
seen.add(num/denom)
result += [f"{num}/{denom}"]
return result | simplified-fractions | Python - Use a set, duh | dev-josh | -1 | 62 | simplified fractions | 1,447 | 0.648 | Medium | 21,565 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2511520/C%2B%2B-or-PYTHON-oror-EXPLAINED-oror | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def solve(root,val):
if root:
k = solve(root.left, max(val,root.val)) + solve(root.right, max(val,root.val))
if root.val >= val:
k+=1
return k
return 0
return solve(root,root.val) | count-good-nodes-in-binary-tree | 🥇 C++ | PYTHON || EXPLAINED || ; ] | karan_8082 | 43 | 2,600 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,566 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/982782/Easy-Python-Recursive-beats-90-with-Comments! | class Solution:
def goodNodes(self, root: TreeNode) -> int:
# Our counter for the good nodes.
count = 0
def helper(node, m):
nonlocal count
# If we run out of nodes return.
if not node:
return
# If the current node val is >= the largest observed in the path thus far.
if node.val >= m:
# Add 1 to the count and update the max observed value.
count += 1
m = max(m, node.val)
# Traverse l and r subtrees.
helper(node.left, m)
helper(node.right, m)
helper(root, root.val)
return count | count-good-nodes-in-binary-tree | Easy Python Recursive beats 90% with Comments! | Pythagoras_the_3rd | 4 | 401 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,567 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/1408602/Python-A-Simple-and-Clean-Recursive-Solution-Explained | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def recurse(node, _max):
if not node: return 0
curr = 1 if _max <= node.val else 0
left = recurse(node.left, max(_max, node.val))
right = recurse(node.right, max(_max, node.val))
return curr+left+right
return recurse(root, root.val) | count-good-nodes-in-binary-tree | [Python] A Simple & Clean Recursive Solution, Explained | chaudhary1337 | 3 | 170 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,568 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2513012/PYTHON-oror-By-using-global-variable-oror-Simple-and-easy-way | class Solution:
def goodNodes(self, root: TreeNode) -> int:
maxx = root.val
count = 0
def dfs(node,maxx):
nonlocal count
if node is None:
return
if node.val >= maxx:
count +=1
maxx = node.val
dfs(node.left,maxx)
dfs(node.right,maxx)
return
dfs(root,maxx)
return count | count-good-nodes-in-binary-tree | PYTHON || By using global variable || Simple and easy way | 1md3nd | 2 | 15 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,569 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2512923/python-very-efficient-solution-using-DFS | class Solution:
def goodNodes(self, root: TreeNode) -> int:
stk=[[root,root.val]]
res=1
while stk:
temp=stk.pop()
if temp[0].left:
if temp[0].left.val>=temp[1]:
res+=1
stk.append([temp[0].left,temp[0].left.val])
else:
stk.append([temp[0].left,temp[1]])
if temp[0].right:
if temp[0].right.val>=temp[1]:
res+=1
stk.append([temp[0].right,temp[0].right.val])
else:
stk.append([temp[0].right,temp[1]])
return res | count-good-nodes-in-binary-tree | python very efficient solution using DFS | benon | 2 | 44 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,570 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2512899/Python-Elegant-and-Short-or-DFS | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def goodNodes(self, root: TreeNode) -> int:
return self._good_nodes(root, -maxsize)
@classmethod
def _good_nodes(cls, node: Optional[TreeNode], curr_max: int) -> int:
if node is None:
return 0
curr_max = max(curr_max, node.val)
return (node.val >= curr_max) + \
cls._good_nodes(node.left, curr_max) + \
cls._good_nodes(node.right, curr_max) | count-good-nodes-in-binary-tree | Python Elegant & Short | DFS | Kyrylo-Ktl | 2 | 61 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,571 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/1113008/Python3-iterative-dfs | class Solution:
def goodNodes(self, root: TreeNode) -> int:
ans = 0
stack = [(root, -inf)]
while stack:
node, val = stack.pop()
if node:
if node.val >= val: ans += 1
val = max(val, node.val)
stack.append((node.left, val))
stack.append((node.right, val))
return ans | count-good-nodes-in-binary-tree | [Python3] iterative dfs | ye15 | 2 | 172 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,572 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2513090/Python-Simple-Python-Solution-Using-DFS-oror-Recursion | class Solution:
def goodNodes(self, root: TreeNode) -> int:
self.result = 0
min_value = -1000000
def TraverseTree(node, min_value):
if node == None:
return None
if node.val >= min_value:
self.result = self.result + 1
min_value = max(node.val, min_value)
TraverseTree(node.left, min_value)
TraverseTree(node.right, min_value)
TraverseTree(root, min_value)
return self.result | count-good-nodes-in-binary-tree | [ Python ] ✅✅ Simple Python Solution Using DFS || Recursion🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 1 | 49 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,573 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2513021/Python-simple-solution-oror-dfs | class Solution:
def goodNodes(self, root: TreeNode, max_value=-math.inf) -> int:
if root is None:
return 0
count = 0
if root.val >= max_value:
count += 1
max_value = root.val
count += self.goodNodes(root.left, max_value)
count += self.goodNodes(root.right, max_value)
return count | count-good-nodes-in-binary-tree | Python simple solution || dfs | wilspi | 1 | 10 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,574 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2511590/Recursive-validation-from-the-Root-to-the-leave-nodes. | class Solution:
def goodNodes(self, root: TreeNode) -> int:
# A global variable to store our answer!
self.ans = 0
def recursion(node, max_predes_val):
# If a node doesn't even exist then how can it be good? 😏
if not node:
return
# If it is good then let's add it up! 🙂
if max_predes_val <= node.val:
self.ans += 1
#For the node's children, the current value is also
# affects the max_predes_val
max_predes_val = max(max_predes_val, node.val)
#Recursively calling the children
recursion(node.left, max_predes_val)
recursion(node.right, max_predes_val)
#Starting at the root, as there aren't any ancestors
# let us pass max_predes_val as -infinity because
# root is by law good!
recursion(root, float('-inf'))
return self.ans | count-good-nodes-in-binary-tree | Recursive validation from the Root to the leave nodes. | sir_rishi | 1 | 23 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,575 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2248077/Python-DFS-beats-99 | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def countNodes(node, maxTillNow):
if not node:
return 0
if node.val >= maxTillNow:
return 1 + (countNodes(node.right,node.val) + countNodes(node.left, node.val))
else:
return (countNodes(node.right,maxTillNow) + countNodes(node.left, maxTillNow))
return countNodes(root, root.val) | count-good-nodes-in-binary-tree | Python DFS beats 99% | anyalauria | 1 | 60 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,576 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/1358982/Python-Clean-BFS-and-DFS | class Solution:
def goodNodes(self, root: TreeNode) -> int:
n_good_nodes = 0
queue = deque([(root, float(-inf))])
while queue:
node, maximum = queue.popleft()
if not node: continue
if node.val >= maximum:
maximum = node.val
n_good_nodes += 1
queue.append((node.right, maximum)), queue.append((node.left, maximum))
return n_good_nodes | count-good-nodes-in-binary-tree | [Python] Clean BFS & DFS | soma28 | 1 | 148 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,577 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/1358982/Python-Clean-BFS-and-DFS | class Solution:
def goodNodes(self, root: TreeNode) -> int:
n_good_nodes = 0
queue = deque([(root, float(-inf))])
while queue:
node, maximum = queue.pop()
if not node: continue
if node.val >= maximum:
maximum = node.val
n_good_nodes += 1
queue.append((node.right, maximum)), queue.append((node.left, maximum))
return n_good_nodes | count-good-nodes-in-binary-tree | [Python] Clean BFS & DFS | soma28 | 1 | 148 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,578 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/1358982/Python-Clean-BFS-and-DFS | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def preorder(node = root, maximum = float(-inf)):
nonlocal n_good_nodes
if not node: return
if node.val >= maximum:
maximum = node.val
n_good_nodes += 1
preorder(node.left, maximum), preorder(node.right, maximum)
return n_good_nodes
n_good_nodes = 0
return preorder() | count-good-nodes-in-binary-tree | [Python] Clean BFS & DFS | soma28 | 1 | 148 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,579 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/1089403/python-3-simple-and-fast-solution | class Solution:
def goodNodes(self, root: TreeNode) -> int:
count=[1]
maxm=root.val
def recursion(node,count,maxm):
if not node:
return
if not node.left and not node.right:
return
if node.left:
if node.left.val>=maxm:
count[0]=count[0]+1
recursion(node.left,count,node.left.val)
else:
recursion(node.left,count,maxm)
if node.right:
if node.right.val>=maxm:
count[0]=count[0]+1
recursion(node.right,count,node.right.val)
else:
recursion(node.right,count,maxm)
recursion(root,count,maxm)
return count[0] | count-good-nodes-in-binary-tree | python 3 simple and fast solution | Underdog2000 | 1 | 328 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,580 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/637166/Python-O(n)-by-DFS-w-Comment | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def helper( node: TreeNode, ancestor_max: int) -> int:
# update ancestor max for child node
ancestor_max_for_child = max( ancestor_max, node.val )
# visit whole tree in DFS
left_good_count = helper( node.left, ancestor_max_for_child ) if node.left else 0
right_good_count = helper( node.right, ancestor_max_for_child ) if node.right else 0
return left_good_count + right_good_count + ( node.val >= ancestor_max )
# -------------------------------------------
return helper( root, root.val ) | count-good-nodes-in-binary-tree | Python O(n) by DFS [w/ Comment] | brianchiang_tw | 1 | 236 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,581 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2811429/Python-or-DFS-traversal | class Solution:
def goodNodes(self, root: TreeNode) -> int:
self.result = 0
self.dfsHelper(root, float("-inf"))
return self.result
def dfsHelper(self, node, greatest):
if not node:
return
if node.val >= greatest:
self.result += 1
self.dfsHelper(node.left, max(greatest, node.val))
self.dfsHelper(node.right, max(greatest, node.val)) | count-good-nodes-in-binary-tree | Python | DFS traversal | kevinskywalker | 0 | 1 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,582 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2627367/Simple-python-solution-or-DFS-or-Efficient-than-97.5 | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node, maxVal):
if not node:
return 0
res = 1 if node.val >= maxVal else 0
maxVal = max(maxVal, node.val)
res += dfs(node.left, maxVal)
res += dfs(node.right, maxVal)
return res
return dfs(root, root.val) | count-good-nodes-in-binary-tree | Simple python solution | DFS | Efficient than 97.5% | nikhitamore | 0 | 7 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,583 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2584388/Python-DFS-preorder-recursive-or-less-than-87-memory-usage-or-how-can-runtime-be-improved | class Solution:
def goodNodes(self, root: TreeNode) -> int:
self.goodnodes = 0
def check_goodnode(node, compare):
compare = max(node.val, compare)
if node.val >= compare:
self.goodnodes += 1
if node.left:
check_goodnode(node.left, compare)
if node.right:
check_goodnode(node.right, compare)
compare = root.val
check_goodnode(root, compare)
return self.goodnodes | count-good-nodes-in-binary-tree | Python DFS preorder recursive | less than 87% memory usage | how can runtime be improved? | shwetachandole | 0 | 25 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,584 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2553042/Python-or-Iterative-and-Recursive-solutions | class Solution:
def goodNodes(self, root: TreeNode) -> int:
count = 0
def count_good_nodes(node, max_node = -float("inf")):
if node:
nonlocal count
max_node = max(max_node, node.val)
count += (node.val == max_node)
count_good_nodes(node.left, max_node)
count_good_nodes(node.right, max_node)
count_good_nodes(root)
return count | count-good-nodes-in-binary-tree | Python | Iterative and Recursive solutions | ahmadheshamzaki | 0 | 28 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,585 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2553042/Python-or-Iterative-and-Recursive-solutions | class Solution:
def goodNodes(self, root: TreeNode, max_node: float = -float("inf")) -> int:
return (root.val == (max_node:=max(max_node, root.val))) + self.goodNodes(root.left, max_node) + self.goodNodes(root.right, max_node) if root else 0 | count-good-nodes-in-binary-tree | Python | Iterative and Recursive solutions | ahmadheshamzaki | 0 | 28 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,586 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2549058/DFS-traversal-using-Python! | class Solution:
def goodNodes(self, root: TreeNode) -> int:
self.c = 0
def dfs(root, val):
if root.val >= val:
val = max(root.val, val)
self.c += 1
if root.left:
dfs(root.left, val)
if root.right:
dfs(root.right, val)
dfs(root, root.val)
return self.c | count-good-nodes-in-binary-tree | DFS traversal using Python! | Manojkc15 | 0 | 15 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,587 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2535981/Easy-Python-DFS-solution | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node,maxval):
if not node:
return 0
maxval=max(maxval,node.val)
return (1 if node.val>=maxval else 0)+dfs(node.left,maxval)+dfs(node.right,maxval)
return dfs(root,root.val) | count-good-nodes-in-binary-tree | Easy Python DFS solution | SathvikPurushotham | 0 | 17 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,588 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2533574/Simple-Python-Solution-usig-recursion | class Solution:
def check(self,curr,currMax):
if curr is None:
return
if curr.val>=currMax:
self.count += 1
currMax = curr.val
self.check(curr.left,currMax)
self.check(curr.right,currMax)
def goodNodes(self, root: TreeNode) -> int:
if root is None:
return 0
self.count=0
self.check(root,-999999)
return self.count | count-good-nodes-in-binary-tree | Simple Python Solution [ usig recursion ] | miyachan | 0 | 4 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,589 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2516897/Python-Simple-DFS-Clean-O(N)-Solution-Beats-99.24 | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node, maxpval):
if not node:
return 0
#If we encounter a new highest value, then we must have a 'good' path, so we update our new highest value and recur. Else, we keep the current highest value and traverse
if node.val >= maxpval:
maxpval = node.val
return dfs(node.left, maxpval) + dfs(node.right, maxpval) + 1
else:
return dfs(node.left, maxpval) + dfs(node.right, maxpval) + 0
return dfs(root, root.val) | count-good-nodes-in-binary-tree | [Python] Simple DFS, Clean O(N) Solution Beats 99.24% | orebitt | 0 | 6 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,590 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2515321/Python-Easy-Approach | class Solution:
def goodNodes(self, root: TreeNode) -> int:
self.total_count = 0
def recur(node, max_till):
if node == None:
return
if node.val >= max_till:
max_till = node.val
self.total_count += 1
recur(node.left, max_till)
recur(node.right, max_till)
recur(root, -(10**4))
return self.total_count | count-good-nodes-in-binary-tree | Python -- Easy Approach | code_sakshu | 0 | 10 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,591 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2515095/Most-Simple-Python-DFS-approach-oror-Easy-and-Beginner-Friendly | class Solution:
def goodNodes(self, root: TreeNode) -> int:
count=0
def dfs(node,mx):
nonlocal count
if node.val>=mx:
count+=1
mx=max(mx,node.val)
if node.left:
dfs(node.left,mx)
if node.right:
dfs(node.right,mx)
dfs(root,root.val)
return count | count-good-nodes-in-binary-tree | Most Simple Python DFS approach || Easy and Beginner Friendly | aditya1292 | 0 | 10 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,592 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2513660/Python-Solution-or-90-Faster-or-Recursive-or-PreOrder-Traversal-and-Carry-Max-Based | class Solution:
def goodNodes(self, root: TreeNode) -> int:
self.count = 0
def traverse(node,currMax):
if not node:
return
if node.val >= currMax:
self.count += 1
currMax = max(node.val,currMax)
traverse(node.left,currMax)
traverse(node.right,currMax)
traverse(root,root.val)
return self.count | count-good-nodes-in-binary-tree | Python Solution | 90% Faster | Recursive | PreOrder Traversal and Carry Max Based | Gautam_ProMax | 0 | 5 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,593 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2513591/(PYTHON3)-tgreater94-using-dfs-short-explanation | class Solution:
def goodNodes(self, root: TreeNode) -> int:
c = 0
def rec(node, lowval):
if not node:
return
nonlocal c
# print(f"{lowval=}")
# print(f"{node.val=}")
if lowval <= node.val:
lowval = node.val
# print(f"val of {c=}--------")
c += 1
rec(node.left, lowval)
rec(node.right, lowval)
rec(root, float(-inf))
return c | count-good-nodes-in-binary-tree | (PYTHON3) t>94 using dfs short explanation | savas_karanli | 0 | 4 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,594 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2513027/Python3-or-CPP-%3A-Recursion | class Solution:
def goodNodes(self, root: TreeNode) -> int:
mx = -100000
ans = 0
def help(root, mx, ans):
if root:
if root.val >= mx:
ans += 1
mx = max(mx, root.val)
ans = help(root.left, mx, ans)
ans = help(root.right, mx, ans)
return ans
ans = help(root, mx, ans)
return ans | count-good-nodes-in-binary-tree | Python3 | CPP : Recursion | joshua_mur | 0 | 3 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,595 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2512487/Python-simple-(recursive)-DFS-solution | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def get_good_nodes_count(node: Optional[TreeNode], max_parent_value: Optional[int], count: int):
if not node:
return count
if max_parent_value is None or max_parent_value <= node.val:
max_parent_value = node.val
count += 1
count = get_good_nodes_count(node.left, max_parent_value, count)
count = get_good_nodes_count(node.right, max_parent_value, count)
return count
return get_good_nodes_count(root, None, 0) | count-good-nodes-in-binary-tree | Python simple (recursive) DFS solution | alexvaclav6 | 0 | 1 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,596 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2512324/simple-python-solution | class Solution:
def goodNodes(self, root: TreeNode) -> int:
self.ans = 1
if(not root):
return 0
def solve(root,val,max_value):
if(not root):
return
if(root.val >= val and root.val >= max_value):
max_value = root.val
self.ans += 1
solve(root.left,val,max_value)
solve(root.right,val,max_value)
solve(root.left,root.val,root.val)
solve(root.right,root.val,root.val)
return self.ans | count-good-nodes-in-binary-tree | simple python solution | jagdishpawar8105 | 0 | 4 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,597 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2512198/EASY-TO-UNDERSTAND-PYTHON-SOLUTION | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def rec_func(node: TreeNode, max_val_in_path: int) -> int:
count_good_nodes = 0
if not node:
return 0
if node.val >= max_val_in_path:
count_good_nodes += 1
max_val_in_path = node.val
count_good_nodes += rec_func(node.left, max_val_in_path)
count_good_nodes += rec_func(node.right, max_val_in_path)
return count_good_nodes
start_max_num = float("-inf")
return rec_func(root, start_max_num) | count-good-nodes-in-binary-tree | 🔥 EASY TO UNDERSTAND PYTHON SOLUTION🔥 | Ur_or | 0 | 1 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,598 |
https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2511756/Python3-or-Easy-to-Understand | class Solution:
def goodNodes(self, root: TreeNode) -> int:
if not root: return 0
q = deque([(root, float('-inf'))])
good_nodes = 0
while q:
node, curr_max_val = q.popleft()
if node.val >= curr_max_val:
good_nodes += 1
curr_max_val = node.val
if node.left:
q.append((node.left, curr_max_val))
if node.right:
q.append((node.right, curr_max_val))
return good_nodes | count-good-nodes-in-binary-tree | ✅Python3 | Easy to Understand | thesauravs | 0 | 8 | count good nodes in binary tree | 1,448 | 0.746 | Medium | 21,599 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.