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/sum-of-square-numbers/discuss/2473291/Python-two-pointer
class Solution: def judgeSquareSum(self, c: int) -> bool: b=int(math.sqrt(c)) i=0 j=b while i<=j: if math.pow(i,2)+math.pow(j,2)==c: return True if math.pow(i,2)+math.pow(j,2)>c: j-=1 elif math.pow(i,2)+math.pow(j,2)...
sum-of-square-numbers
Python two pointer
deepanshu704281
0
26
sum of square numbers
633
0.346
Medium
10,600
https://leetcode.com/problems/sum-of-square-numbers/discuss/2442219/easy-python-code-or-O(N)-or-binary-search-or-two-pointer
class Solution: def binarysearch (self, c): l,r = 0,c while(l<=r): m = (l+r)//2 if m**2 >c: r = m-1 elif m**2 < c: if (m+1)**2 > c: return m else: l = m+1 else: ...
sum-of-square-numbers
easy python code | O(N) | binary search | two pointer
dakash682
0
60
sum of square numbers
633
0.346
Medium
10,601
https://leetcode.com/problems/sum-of-square-numbers/discuss/2389189/Python-Short-Solution-using-SQRT-oror-Documented
class Solution: def judgeSquareSum(self, c: int) -> bool: end = int(sqrt(c)) + 1 # add 1 for inclusive range for b in range(end): # from 0 to sqrt(c) a = sqrt(c-b*b) # put b in equation to find value of a if int(a) == a: # If a is an integer, return True ...
sum-of-square-numbers
[Python] Short Solution using SQRT || Documented
Buntynara
0
35
sum of square numbers
633
0.346
Medium
10,602
https://leetcode.com/problems/sum-of-square-numbers/discuss/1922308/2-Python-Solutions
class Solution: def judgeSquareSum(self, c: int) -> bool: for a in range(int(sqrt(c))+1): b=sqrt(c-a*a) if b==int(b): return True return False
sum-of-square-numbers
2 Python Solutions
Taha-C
0
75
sum of square numbers
633
0.346
Medium
10,603
https://leetcode.com/problems/sum-of-square-numbers/discuss/1922308/2-Python-Solutions
class Solution: def judgeSquareSum(self, c: int) -> bool: l=0 ; r=int(sqrt(c)) while l<=r: s=l**2+r**2 if s>c: r-=1 elif s<c: l+=1 else: return True return False
sum-of-square-numbers
2 Python Solutions
Taha-C
0
75
sum of square numbers
633
0.346
Medium
10,604
https://leetcode.com/problems/sum-of-square-numbers/discuss/1621104/Python3-Solution-oror-O(N))-TIME-O(1)-SPACE-oror-2Sum-Pattern
class Solution: def judgeSquareSum(self, c: int) -> bool: n = int(math.sqrt(c)) start = 0 end = n tSum = start**2 + end**2 while start <= end: #print(start, end) if tSum < c: tSum += 2*start+1 start+=1 elif t...
sum-of-square-numbers
Python3 Solution || O(√N)) TIME , O(1) SPACE || [2Sum Pattern]
henriducard
0
135
sum of square numbers
633
0.346
Medium
10,605
https://leetcode.com/problems/sum-of-square-numbers/discuss/1495485/PYTHON-SOL-BEATS-90-OF-PYTHON-SUBMISSIONS
class Solution: def judgeSquareSum(self, c: int) -> bool: low,high=0,int(c**0.5)+1 while low<=high: tmp=low*low+high*high if tmp==c:return True if tmp>c:high-=1 else:low+=1 return False
sum-of-square-numbers
PYTHON SOL BEATS 90% OF PYTHON SUBMISSIONS
reaper_27
0
235
sum of square numbers
633
0.346
Medium
10,606
https://leetcode.com/problems/sum-of-square-numbers/discuss/1426490/Python-Super-easy-and-naive-solution
class Solution: def judgeSquareSum(self, c: int) -> bool: for i in range(int(sqrt(c)), -1, -1): cur = sqrt(c - pow(i, 2)) if cur == int(cur): return True return False
sum-of-square-numbers
[Python] Super easy and naive solution
cyshih
0
85
sum of square numbers
633
0.346
Medium
10,607
https://leetcode.com/problems/sum-of-square-numbers/discuss/1425842/Python3-two-pointers-solution-with-detailed-comments
class Solution: def judgeSquareSum(self, c: int) -> bool: if int(c**0.5) == c**0.5: # if it is a perfect square itself. return True l = 0 # the left pointer starts from 0 root = (c-l**2)**(0.5) if c-l**2 > 1 else 0 r = int(root) # the right pointer starts from the square ...
sum-of-square-numbers
Python3 - two pointers solution with detailed comments
elainefaith0314
0
41
sum of square numbers
633
0.346
Medium
10,608
https://leetcode.com/problems/sum-of-square-numbers/discuss/1047304/Ultra-Simple-CppPython3-Solution-or-Suggestions-for-optimization-are-welcomed-or
class Solution: def judgeSquareSum(self, c: int) -> bool: if c==0: return 1; i=0 sq1=0 sq2=0 temp=c-i*i while temp>0: temp=c-i*i if temp<0: return 0; ...
sum-of-square-numbers
Ultra Simple Cpp/Python3 Solution | Suggestions for optimization are welcomed |
angiras_rohit
0
68
sum of square numbers
633
0.346
Medium
10,609
https://leetcode.com/problems/sum-of-square-numbers/discuss/458442/Python3-simple-solution-using-a-hash-table
class Solution: def judgeSquareSum(self, c: int) -> bool: sq = int(c**0.5) ht = {} for i in range(sq+1): if i**2 == c or c - i**2 in ht or 2*i**2 == c: return True ht[i**2] = ht.get(i**2,True) return False
sum-of-square-numbers
Python3 simple solution using a hash table
jb07
0
103
sum of square numbers
633
0.346
Medium
10,610
https://leetcode.com/problems/sum-of-square-numbers/discuss/356734/Python3-1-line
class Solution: def judgeSquareSum(self, c: int) -> bool: return any(sqrt(c-x*x).is_integer() for x in range(int(sqrt(c//2)) + 1))
sum-of-square-numbers
[Python3] 1-line
ye15
0
171
sum of square numbers
633
0.346
Medium
10,611
https://leetcode.com/problems/sum-of-square-numbers/discuss/356734/Python3-1-line
class Solution: def judgeSquareSum(self, c: int) -> bool: for x in range(int(sqrt(c//2))+1): xx = sqrt(c - x*x) if xx.is_integer(): return True return False
sum-of-square-numbers
[Python3] 1-line
ye15
0
171
sum of square numbers
633
0.346
Medium
10,612
https://leetcode.com/problems/sum-of-square-numbers/discuss/356734/Python3-1-line
class Solution: def judgeSquareSum(self, c: int) -> bool: # Fermat theorem on sum of two squares x = 2 while x*x <= c: if c % x == 0: mult = 0 while c % x == 0: mult += 1 c //= x if x % 4 =...
sum-of-square-numbers
[Python3] 1-line
ye15
0
171
sum of square numbers
633
0.346
Medium
10,613
https://leetcode.com/problems/exclusive-time-of-functions/discuss/863039/Python-3-or-Clean-Simple-Stack-or-Explanation
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: helper = lambda log: (int(log[0]), log[1], int(log[2])) # to covert id and time to integer logs = [helper(log.split(':')) for log in logs] # convert [string] to [(,,)] ans, s = [0] * n, [] ...
exclusive-time-of-functions
Python 3 | Clean, Simple Stack | Explanation
idontknoooo
15
1,100
exclusive time of functions
636
0.611
Medium
10,614
https://leetcode.com/problems/exclusive-time-of-functions/discuss/1295753/python-or-stack-or-easy-or-O(n)
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: f = [0]*(n) stack=[] for i in logs: ID,pos,time = i.split(':') ID= int(ID) time= int(time) ...
exclusive-time-of-functions
python | stack | easy | O(n)
chikushen99
5
436
exclusive time of functions
636
0.611
Medium
10,615
https://leetcode.com/problems/exclusive-time-of-functions/discuss/651462/python3-solution-using-stack-faster-than-96.75
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: ftimes = [0] * n stack = [] prev_start_time = 0 for log in logs: fid, indicator, ftime = log.split(":") fid, ftime = int(fid), int(ftime) if indica...
exclusive-time-of-functions
python3 solution using stack - faster than 96.75%
darshan_22
5
555
exclusive time of functions
636
0.611
Medium
10,616
https://leetcode.com/problems/exclusive-time-of-functions/discuss/1739360/very-very-simple-solution-or-stacks
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: result = [0]*n stack = [] for i, log in enumerate(logs): curr_fid, curr_event, curr_time = log.split(":") if curr_event == "start": stack.append(log) e...
exclusive-time-of-functions
very very simple solution | stacks
SN009006
4
292
exclusive time of functions
636
0.611
Medium
10,617
https://leetcode.com/problems/exclusive-time-of-functions/discuss/2198027/PythonStackEasy-to-Understand
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: # Store total time of fid res = [0 for _ in range(n)] # stack s = [] # store the current time currt = 0 # iterate through the logs for log in logs: # Get thefid , state a...
exclusive-time-of-functions
[Python][Stack]Easy to Understand]
maverick02
3
112
exclusive time of functions
636
0.611
Medium
10,618
https://leetcode.com/problems/exclusive-time-of-functions/discuss/1452690/PyPy3-Solution-using-stack-w-comments
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: # Init fid = [] ftime = [0] * n prev_ts = 0 # For all logs for log in logs: # Split into, id, type of operation and time # in correct ...
exclusive-time-of-functions
[Py/Py3] Solution using stack w/ comments
ssshukla26
3
185
exclusive time of functions
636
0.611
Medium
10,619
https://leetcode.com/problems/exclusive-time-of-functions/discuss/1826300/O(n)-Python-Faster-than-99.39-easy-to-understand
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: # memory efficient implementation # We basically mark the array at that time stamp as the one starting or ending stk = [] current = -1 res_count = [0 for _ in range(n)] ...
exclusive-time-of-functions
O(n) Python, Faster than 99.39%, easy to understand
rishabhnitc
2
168
exclusive time of functions
636
0.611
Medium
10,620
https://leetcode.com/problems/exclusive-time-of-functions/discuss/1796246/Python-intuitive-approach-with-comments
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: result = [0] * n p_num, _, p_timestamp = logs[0].split(':') stack = [[int(p_num), int(p_timestamp)]] i = 1 while i < len(logs): # c_ variables are current index's log entr...
exclusive-time-of-functions
Python intuitive approach with comments
GeneBelcher
2
142
exclusive time of functions
636
0.611
Medium
10,621
https://leetcode.com/problems/exclusive-time-of-functions/discuss/1567817/O(n)-Simple-Python-with-Detailed-Comments-using-Stacks
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: ans = [0 for _ in range(n)] call_stack = [] #Holds (function_id, index) #We know that each function call will be ended before a new one starts, so there's only two cases, #Either we start a new function, or we e...
exclusive-time-of-functions
O(n) Simple Python with Detailed Comments using Stacks
neurologicalstyle
2
297
exclusive time of functions
636
0.611
Medium
10,622
https://leetcode.com/problems/exclusive-time-of-functions/discuss/360388/Python3-super-clean-functional-programming
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: stack, output = [], [0] * n normalize = lambda k, e, t : \ [int(k), e, int(t) + (1 if e == 'end' else 0)] stack_ops = { 'start' : lambda k : stack.append(k), \ ...
exclusive-time-of-functions
Python3 super clean functional programming
tinlittle
2
232
exclusive time of functions
636
0.611
Medium
10,623
https://leetcode.com/problems/exclusive-time-of-functions/discuss/2445464/Python-simple-solution-with-stack-using-defaultdict
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: output = [0] * n # initialize stack for each function_id record = collections.defaultdict(list) for log in logs: f_id, f_type, ts = log.split(':') #co...
exclusive-time-of-functions
Python, simple solution with stack using defaultdict
nobodynobody1234
1
116
exclusive time of functions
636
0.611
Medium
10,624
https://leetcode.com/problems/exclusive-time-of-functions/discuss/522248/Python3-simple-solution
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: exec_time = [0] * n # fn_heap[n][0]: function id # fn_heap[n][1]: recent start time # fn_heap[n][2]: run time summary fn_heap = [] for log in logs: elem = str(log).split(":") ...
exclusive-time-of-functions
Python3 simple solution
tjucoder
1
177
exclusive time of functions
636
0.611
Medium
10,625
https://leetcode.com/problems/exclusive-time-of-functions/discuss/886997/Python3-10-line-via-a-stack
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: ans = [0]*n stack = [] # stack of fid for log in logs: fid, flag, time = log.split(":") fid, flag, time = int(fid), flag == "end", int(time) if stack: ans[stack[-1]] += time -...
exclusive-time-of-functions
[Python3] 10-line via a stack
ye15
0
144
exclusive time of functions
636
0.611
Medium
10,626
https://leetcode.com/problems/exclusive-time-of-functions/discuss/867491/Python-3-(stack-simple)
class Solution(object): def exclusiveTime(self, n, logs): """ :type n: int :type logs: List[str] :rtype: List[int] """ ans, s = [0] * n, [] for log in logs: i, com, time = log.split(":") i = int(i) time...
exclusive-time-of-functions
Python 3 (stack simple)
ermolushka2
0
118
exclusive time of functions
636
0.611
Medium
10,627
https://leetcode.com/problems/exclusive-time-of-functions/discuss/335873/A-Few-lines-of-Python-beat-95
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: ans = [0] * n stk, start = [], None for log in logs: jid, kw, ts = log.split(':') jid, ts = int(jid), int(ts) if kw == 'start': if stk: ans[s...
exclusive-time-of-functions
A Few lines of Python, beat 95%
bos
0
285
exclusive time of functions
636
0.611
Medium
10,628
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/492462/PythonGo-O(n)-by-level-order-traversal.-w-Explanation
class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: if not root: # Quick response for empty tree return [] traversal_q = [root] average = [] while traversal_q: # co...
average-of-levels-in-binary-tree
Python/Go O(n) by level-order-traversal. [ w/ Explanation ]
brianchiang_tw
10
1,300
average of levels in binary tree
637
0.717
Easy
10,629
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/1874688/Easy-BFS-Recursion-Solution-(greater-90-)-w-beginner-level-interview-notes
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: #starting here, the next ~8 lines are how I do bfs recursively. levels = [] def bfs(node, level): if node: if len(levels) == level: levels.append([]) levels[leve...
average-of-levels-in-binary-tree
Easy BFS Recursion Solution (> 90 %) w/ beginner level interview notes
bwlee13
3
203
average of levels in binary tree
637
0.717
Easy
10,630
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/476325/Python3-simple-BFS-or-96.13-91.67
class Solution(object): def averageOfLevels(self, root): if root is None: return [] lst = [[root]] for elem in lst: record = [] for c in elem: if c.left: record.append(c.left) if c.right: record.append(c.right) ...
average-of-levels-in-binary-tree
Python3 simple BFS | 96.13% 91.67%
dnagy
3
696
average of levels in binary tree
637
0.717
Easy
10,631
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/306920/Python-48-ms-beat-98-with-additional-'count'-variable-(rec-DFS)
class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: if root is not None: output = [] depth = 0 def trav(node, depth): depth += 1 if len(output) < depth: output.append([]) output[depth - 1].append(node.val) if node.left is not None: trav(node.left, depth) i...
average-of-levels-in-binary-tree
Python 48 ms beat 98% with additional 'count' variable (rec DFS)
ht921005
3
484
average of levels in binary tree
637
0.717
Easy
10,632
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2520814/Python-or-Easy-solution-with-stack
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: # Store in a stack the root node and its level (i.e. 0) stack = [(root, 0)] # Dict used to contain values at same tree level level_values = defaultdict(list) # Explore the tr...
average-of-levels-in-binary-tree
[Python] | Easy solution with stack
lcerone
2
28
average of levels in binary tree
637
0.717
Easy
10,633
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2518306/Python-Elegant-and-Short-or-4-lines-BFS-or-Generators
class Solution: """ Time: O(n) Memory: O(n) """ def averageOfLevels(self, root: TreeNode) -> List[float]: queue = deque([root]) averages = [] while queue: level_sum = level_cnt = 0 for _ in range(len(queue)): node = queue.popleft() if node is not None: level_sum += node.val level_...
average-of-levels-in-binary-tree
Python Elegant & Short | 4-lines BFS | Generators
Kyrylo-Ktl
2
80
average of levels in binary tree
637
0.717
Easy
10,634
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/1094550/Python3-solution-for-Average-of-Levels-in-Binary-Tree
class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: q = [] curr = [root] #traverses one level at a time while curr : q.append(curr) curr = [] for node in q[-1] : # q of -1 means basically the most recently add...
average-of-levels-in-binary-tree
Python3 solution for Average of Levels in Binary Tree
avEraGeC0der
2
279
average of levels in binary tree
637
0.717
Easy
10,635
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2517311/python-solution
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: qu, arr = deque([root]), [root.val] while qu: r=len(qu) c=0 for i in range(r): child=qu.popleft() if child.left: qu.append(child...
average-of-levels-in-binary-tree
python solution
benon
1
38
average of levels in binary tree
637
0.717
Easy
10,636
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2000219/Python-Clean-and-Simple!-DFS-Recursive
class Solution: def averageOfLevels(self, root): self.sums, self.counts = [], [] self.dfs(root) return [s/c for s,c in zip(self.sums, self.counts)] def dfs(self, root, level=0): if len(self.counts) <= level: self.counts.append(1) self.sums.append(root...
average-of-levels-in-binary-tree
Python - Clean and Simple! DFS / Recursive
domthedeveloper
1
101
average of levels in binary tree
637
0.717
Easy
10,637
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/1986782/python-oror-BFS-with-q
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: res = [] q = deque([root]) curSum, size, count = 0, 1, 1 while q: node = q.popleft() curSum += node.val size -= 1 if node.left: q.append...
average-of-levels-in-binary-tree
python || BFS with q
gulugulugulugulu
1
50
average of levels in binary tree
637
0.717
Easy
10,638
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/1591604/python-98.12-faster-level-by-level
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: q: list = [root] res = [] while len(q) > 0: temp = [] node_count = 0 sum = 0 while len(q) > 0: current_node = q.pop(0) node_cou...
average-of-levels-in-binary-tree
python 98.12% faster, level by level
msugamsingh
1
102
average of levels in binary tree
637
0.717
Easy
10,639
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2789095/Python-BFS-solution-explained
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: ans = [] q = deque([root]) s = 0 while q: lq = len(q) for i in range(lq): cur = q.popleft() s += cur.val if i==lq-1: ...
average-of-levels-in-binary-tree
Python BFS solution explained
Pirmil
0
1
average of levels in binary tree
637
0.717
Easy
10,640
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2694401/Python-O(n)-BFS-solution-5-lines
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: answer, level = [], [root] while level: answer.append(sum(node.val for node in level) / len(level)) level = [leaf for node in level for leaf in (node.left, node.right) if leaf] return ...
average-of-levels-in-binary-tree
[Python] O(n) BFS solution 5 lines
smokfyz
0
3
average of levels in binary tree
637
0.717
Easy
10,641
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2673416/Python-Level-Order-Traversal-Variation-Easy-Understanding
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: ans = [] q = collections.deque() q.append(root) while q: level = [] size = len(q) for i in range(size): curNode = q.popleft() ...
average-of-levels-in-binary-tree
Python Level Order Traversal Variation - Easy Understanding
logeshsrinivasans
0
17
average of levels in binary tree
637
0.717
Easy
10,642
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2533722/Simple-python-solution-using-queue
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: q =[] ans =[] q.append(root) while(len(q)>0): lvl_size = len(q) avg = 0 total = 0 for i in range(lvl_size): curr = q.pop(0) ...
average-of-levels-in-binary-tree
Simple python solution [using queue]
miyachan
0
15
average of levels in binary tree
637
0.717
Easy
10,643
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2520217/Level-Order-Traversal-or-Queue-or-Python-or-UwU
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: if(root is None): return [] q = [root] ans = [] while(q): sumi = 0 n = len(q) for i in range(n): node = q.pop(0) if(node...
average-of-levels-in-binary-tree
Level Order Traversal | Queue | Python | UwU
mohithnc456
0
8
average of levels in binary tree
637
0.717
Easy
10,644
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2519460/Python-oror-BFS-with-one-loop
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: avg = [] cur_sum, count = 0, 0 running_level = 0 q = deque((root, 0)) while q: node, level = q.popleft() if node is None: continue q.append...
average-of-levels-in-binary-tree
Python || BFS with one loop
wilspi
0
6
average of levels in binary tree
637
0.717
Easy
10,645
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2518881/Python3-Solution-with-using-bfs
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: if not root: return None q = collections.deque([root]) res = [] while q: next_lvl = collections.deque() _sum = 0 _cnt = 0...
average-of-levels-in-binary-tree
[Python3] Solution with using bfs
maosipov11
0
3
average of levels in binary tree
637
0.717
Easy
10,646
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2518851/Python-Simple-Faster-than-90
class Solution: levelsList = [] def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: self.levelsList = [] currentLevel = 0 output = [] self.traverse(root, currentLevel) for level in self.levelsList: output.append(sum(level) / len(level)) ...
average-of-levels-in-binary-tree
Python Simple Faster than 90%
AxelDovskog
0
11
average of levels in binary tree
637
0.717
Easy
10,647
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2518114/Faster-than-99.61-of-submissions-or-Python-or-BFS-solution-or-Easy-to-understand
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: dict_lvl=defaultdict(list) def bfs(root,lvl): if root is None: return dict_lvl[lvl].append(root.val) bfs(root.left,lvl+1) bfs(root.right,lvl+1) ...
average-of-levels-in-binary-tree
Faster than 99.61% of submissions | Python | BFS solution | Easy to understand
ankush_A2U8C
0
10
average of levels in binary tree
637
0.717
Easy
10,648
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2517939/Python-Pre-order-Traversal-Recursive-Solution-O(n)-time-O(h)-space
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: # Create dictionaries with levels {level: sum} and {level: count} levels_with_sums, levels_with_counts = {}, {} root_level = 0 # Recursive pre-order traversal def preorder_traverse(root, levels_with...
average-of-levels-in-binary-tree
Python Pre-order Traversal - Recursive Solution O(n) time, O(h) space
AleksandrEfimenko
0
7
average of levels in binary tree
637
0.717
Easy
10,649
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2517369/Python-Simple-Python-Solution-Using-Level-Order-Traversal-or-Recursion
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: def Height(node): if node == None: return 0 return max(Height(node.left), Height(node.right)) + 1 def LevelOrder(node,current_level, level): if node == None: return None if level == 1: current_level.app...
average-of-levels-in-binary-tree
[ Python ] ✅✅ Simple Python Solution Using Level Order Traversal | Recursion 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
22
average of levels in binary tree
637
0.717
Easy
10,650
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2517299/Python-Accepted
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: q=deque() q.append(root) ans =[] while q: qlen=len(q) row =0 for i in range(qlen): node = q.popleft() row += node.val ...
average-of-levels-in-binary-tree
Python Accepted ✅
Khacker
0
12
average of levels in binary tree
637
0.717
Easy
10,651
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2517074/Python-or-Easy-Solution
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: level_dict={} def averageOfLevelsUtil(root, level): if root is None: return if level in level_dict: level_dict[level].append(root.val) else...
average-of-levels-in-binary-tree
Python | Easy Solution
Siddharth_singh
0
12
average of levels in binary tree
637
0.717
Easy
10,652
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2516924/An-iterative-BFS-approach-or-Python-or-Simple-and-Easy
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: lvl = [root] ret = [] while lvl : l = [] for i in range(len(lvl)): node = lvl.pop() if node: ...
average-of-levels-in-binary-tree
An iterative BFS approach | Python | Simple and Easy
haminearyan
0
4
average of levels in binary tree
637
0.717
Easy
10,653
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2516611/Python-or-DFS
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: nodeStack = [(root, 0)]; nodeCountSum = [] while nodeStack: currentNode, level = nodeStack.pop() if len(nodeCountSum) == level: nodeCountSum.append([1, curren...
average-of-levels-in-binary-tree
Python | DFS
sr_vrd
0
17
average of levels in binary tree
637
0.717
Easy
10,654
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2516581/Python3-or-Easy-to-Understand-or-BFS
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: # do level order traversing # perform average and save in array if not root: return [] q = deque([root]) average = [] while q: level_...
average-of-levels-in-binary-tree
✅Python3 | Easy to Understand | BFS
thesauravs
0
12
average of levels in binary tree
637
0.717
Easy
10,655
https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/2516567/Easy-python-solution
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: lst=[root] flst=[] avg=[] sm,ct=0,0 while lst: x=lst.pop(0) sm+=x.val ct+=1 if x.left: flst.append(x.left) if x.righ...
average-of-levels-in-binary-tree
Easy python solution
shubham_1307
0
7
average of levels in binary tree
637
0.717
Easy
10,656
https://leetcode.com/problems/shopping-offers/discuss/783072/Python-3-DFS-%2B-Memoization-(lru_cache)
class Solution: def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int: n = len(price) @lru_cache(maxsize=None) def dfs(needs): ans = sum([i*j for i, j in zip(price, needs)]) cur = sys.maxsize for s in special: ...
shopping-offers
Python 3 DFS + Memoization (lru_cache)
idontknoooo
2
292
shopping offers
638
0.541
Medium
10,657
https://leetcode.com/problems/shopping-offers/discuss/888324/Python3-top-down-dp
class Solution: def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int: @lru_cache(None) def fn(*args): """Return the lowest price one has to pay to get items in args.""" ans = sum(x*y for x, y in zip(args, price)) ...
shopping-offers
[Python3] top-down dp
ye15
1
123
shopping offers
638
0.541
Medium
10,658
https://leetcode.com/problems/shopping-offers/discuss/2830071/knap-sack-DP-or-top-down-memo-python-simple-solution
class Solution: def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int: memo = dict() def dfs(remain): if tuple(remain) in memo: return memo[tuple(remain)] ans = math.inf for i in range(len(special)): ...
shopping-offers
knap-sack / DP or top-down memo / python simple solution
Lara_Craft
0
7
shopping offers
638
0.541
Medium
10,659
https://leetcode.com/problems/shopping-offers/discuss/2787895/Faster-than-90.-Memoization-Python3
class Solution: def shoppingOffers(self, price: List[int], special: List[List[int]], initial_needs: List[int]) -> int: memo = {} def helper(needs): lookup = str(needs) if lookup in memo: return memo[lookup] min_price = sum([price[idx]*needs[idx] for idx in range(l...
shopping-offers
Faster than 90%. Memoization [Python3]
kunal5042
0
6
shopping offers
638
0.541
Medium
10,660
https://leetcode.com/problems/shopping-offers/discuss/2474969/Python3-or-Tried-to-solve-using-Backtracking-%2B-Recursive-Approach%3A-Seems-Multidmensional-DP-Required
class Solution: def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int: #Approach: At every decision making node, we have an option to choose one of #many available sale special offers! Once we run out of offers to choose from, #we will simply have to ...
shopping-offers
Python3 | Tried to solve using Backtracking + Recursive Approach: Seems Multidmensional DP Required
JOON1234
0
33
shopping offers
638
0.541
Medium
10,661
https://leetcode.com/problems/decode-ways-ii/discuss/2509952/Best-Python3-implementation-(Top-93.7)-oror-Clean-code
class Solution: def numDecodings(self, s: str) -> int: non_zero = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] first_incl, second_incl = 1, 0 first_excl, second_excl = 0, 0 if s[0] in non_zero: second_incl = 1 if s[0] == '*': second_incl = 9 ...
decode-ways-ii
✔️ Best Python3 implementation (Top 93.7%) || Clean code
UpperNoot
0
25
decode ways ii
639
0.304
Hard
10,662
https://leetcode.com/problems/decode-ways-ii/discuss/1340485/Python3-top-down-dp
class Solution: def numDecodings(self, s: str) -> int: @cache def fn(i): """Return decode ways.""" if i == len(s): return 1 if s[i] == "0": return 0 if i == len(s)-1: return 9 if s[i] == '*' else 1 if s[i] == "*": ...
decode-ways-ii
[Python3] top-down dp
ye15
0
94
decode ways ii
639
0.304
Hard
10,663
https://leetcode.com/problems/solve-the-equation/discuss/837106/Python-or-No-Regex-or-Simple-Logic-or-Probably-better-for-interviews-or-Commented
class Solution: def solveEquation(self, equation: str) -> str: def helper(l,r): # left inclusive and right exclusive constant = unknown = 0 sign,val = 1,'' while l < r: if equation[l].isnumeric(): val += equation[l] elif...
solve-the-equation
Python | No Regex | Simple Logic | Probably better for interviews | Commented
since2020
6
299
solve the equation
640
0.434
Medium
10,664
https://leetcode.com/problems/solve-the-equation/discuss/1318772/Python-3-or-Simulation-Math-or-Explanations
class Solution: def solveEquation(self, equation: str) -> str: left, right = equation.split('=') def simplify(s): x_cnt, c_cnt, cur, sign = 0, 0, '', 1 for c in s + '+': # adding `+` to process the last term of `s`, since sign is a trigger if c in...
solve-the-equation
Python 3 | Simulation, Math | Explanations
idontknoooo
2
192
solve the equation
640
0.434
Medium
10,665
https://leetcode.com/problems/solve-the-equation/discuss/885893/Python3-parse-lhs-and-rhs-respectively
class Solution: def solveEquation(self, equation: str) -> str: lhs, rhs = equation.split("=") def fn(s): """Parse s into coefficients.""" ii = x = y = 0 for i in range(len(s)+1): if i == len(s) or s[i] in "+-": if ii ...
solve-the-equation
[Python3] parse lhs & rhs respectively
ye15
1
156
solve the equation
640
0.434
Medium
10,666
https://leetcode.com/problems/solve-the-equation/discuss/395304/Two-Solutions-in-Python-3-(beats-~100)-(five-lines-and-two-lines)
class Solution: def solveEquation(self, E: str) -> str: [L,R] = E.replace('+x',' 1x').replace('-x',' -1x').replace('=x','=1x').replace('+',' ').replace('-',' -').split('=') L, R, LC, RC = ['1x'] + L.split()[1:] if L[0] == 'x' else L.split(), R.split(), [0, 0], [0, 0] for i in L: LC = [LC[0]+int(i[:-1...
solve-the-equation
Two Solutions in Python 3 (beats ~100%) (five lines and two lines)
junaidmansuri
1
381
solve the equation
640
0.434
Medium
10,667
https://leetcode.com/problems/solve-the-equation/discuss/395304/Two-Solutions-in-Python-3-(beats-~100)-(five-lines-and-two-lines)
class Solution: def solveEquation(self, E: str) -> str: [a,b] = (lambda x: [x.real, x.imag])(eval(E.replace('x','j').replace('=','-(')+')', {'j': 1j})) return 'x=' + str(int(-a//b)) if b else 'Infinite solutions' if not a else 'No solution' - Junaid Mansuri (LeetCode ID)@hotmail.com
solve-the-equation
Two Solutions in Python 3 (beats ~100%) (five lines and two lines)
junaidmansuri
1
381
solve the equation
640
0.434
Medium
10,668
https://leetcode.com/problems/solve-the-equation/discuss/2717613/Easy-Python-solution-similar-to-basic-calculator
class Solution: def solveEquation(self, equation: str) -> str: def solve(eqn): x, n, i, num = 0, 0, 0, 0 sign = 1 while i < len(eqn): if eqn[i].isnumeric(): num = num * 10 + int(eqn[i]) i += 1 con...
solve-the-equation
Easy Python solution similar to basic calculator
lmnvs
0
9
solve the equation
640
0.434
Medium
10,669
https://leetcode.com/problems/solve-the-equation/discuss/1568996/Python-faster-than-99-O(n)
class Solution: def solveEquation(self, equation: str) -> str: m = 1 cur = 0 is_cur = False left = True left_x = left_val = right_x = right_val = 0 equation += '+' for c in equation: if c.isdigit(): cur = cur * 10 + int(c) ...
solve-the-equation
Python faster than 99% O(n)
dereky4
0
228
solve the equation
640
0.434
Medium
10,670
https://leetcode.com/problems/solve-the-equation/discuss/1545684/C%2B%2B-0ms-Python-24ms-Explained-Solution-without-String-Splitting-or-Replacing
class Solution: def solveEquation(self, equation: str) -> str: s = '' x, i = 0, 0 rev = False for c in equation: if c in '+-': if s: i += int(s or 0) * (rev or -1) s = c elif c == 'x': x -= int(s+'1' if s in '+-' els...
solve-the-equation
[C++ 0ms, Python 24ms, Explained] Solution without String Splitting or Replacing
SakretteAmi
0
82
solve the equation
640
0.434
Medium
10,671
https://leetcode.com/problems/maximum-average-subarray-i/discuss/336428/Solution-in-Python-3-(beats-100)
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: M = d = 0 for i in range(len(nums)-k): d += nums[i+k] - nums[i] if d > M: M = d return (sum(nums[:k])+M)/k - Python 3 - Junaid Mansuri
maximum-average-subarray-i
Solution in Python 3 (beats 100%)
junaidmansuri
11
2,100
maximum average subarray i
643
0.438
Easy
10,672
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1356537/Easy-Python-Solution(91.86)
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: g=sum(nums[:k]) m=g for i in range(len(nums)-k): g=g-nums[i]+nums[i+k] m=max(m,g) return m/k
maximum-average-subarray-i
Easy Python Solution(91.86%)
Sneh17029
7
712
maximum average subarray i
643
0.438
Easy
10,673
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1251206/Python3-simple-solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: res = sum(nums[:k]) x = res for i in range(1,len(nums)-k+1): x = x - nums[i-1] + nums[i+k-1] res = max(res, x) return res/k
maximum-average-subarray-i
Python3 simple solution
EklavyaJoshi
2
106
maximum average subarray i
643
0.438
Easy
10,674
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2779144/Max-Average-Sum
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: window_sum=0 for i in range(0,k): window_sum=window_sum+nums[i] max_sum=window_sum start=0 for j in range(k,len(nums)): window_sum=window_sum-nums[start]+nums[j] ...
maximum-average-subarray-i
Max Average Sum
RaviShanker__Thadishetti
1
22
maximum average subarray i
643
0.438
Easy
10,675
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1337906/PYTHON-oror-SLIDING-WINDOW-oror-RUN-TIME-BEATS-90-or-MEMORY-USAGE-BEATS-88
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: n = len(nums) curr_sum = 0 max_sum = 0 if n == 1: return nums[0]/k if n == k: for i in range(0,n): curr_sum += nums[i] return curr_sum/k ...
maximum-average-subarray-i
PYTHON || SLIDING WINDOW || RUN TIME BEATS 90% | MEMORY USAGE BEATS 88%
pranshusharma712
1
173
maximum average subarray i
643
0.438
Easy
10,676
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2833720/Pen-n-Paper-Solution-oror-Easy-Solution-oror-Python
class Solution: def findMaxAverage(self, arr: List[int], k: int) -> float: n=len(arr) # n is the length of array window_sum=sum(arr[:k]) #initially , cal the sum of given window size MaxAverage=window_sum for element in range(1,n-k+1): #range in which window'll slide win...
maximum-average-subarray-i
Pen n Paper Solution || Easy Solution || Python
user9516zM
0
3
maximum average subarray i
643
0.438
Easy
10,677
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2803999/Python-easy-Sliding-window-approach
class Solution: def findMaxAverage(self, nums, k: int) -> float: maxi=sum(nums[:k])/k running_sum = sum(nums[:k]) for i in range(1,len(nums)-k+1): running_sum = running_sum-nums[i-1]+nums[i+k-1] avg_s=running_sum/k maxi=max(maxi,avg_s) return maxi
maximum-average-subarray-i
Python easy Sliding window approach
ankansharma1998
0
7
maximum average subarray i
643
0.438
Easy
10,678
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2796523/Maximum-Average-Subarray-I-Easy-Solution-Two-pointers-and-Sliding-windwo-python
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: curSum = sum(nums[:k]) ave = curSum / k left, right = 1, k while right < len(nums): curSum += (nums[right] - nums[left - 1]) ave = max(ave, curSum / k) left += 1 ...
maximum-average-subarray-i
Maximum Average Subarray I Easy Solution Two pointers and Sliding windwo python
poison_11
0
4
maximum average subarray i
643
0.438
Easy
10,679
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2788624/Maximum-Average-Subarray-I-solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: maxSum = windowSum = sum(nums[:k]) for i in range(k,len(nums)): windowSum += nums[i] - nums[i-k] maxSum = max(maxSum,windowSum) return maxSum / k
maximum-average-subarray-i
Maximum Average Subarray I solution
vazimax
0
2
maximum average subarray i
643
0.438
Easy
10,680
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2727214/Concise-Python-and-golang-Solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: len_nums = len(nums) # Set smallest size max_average = -1 * sys.maxsize # left index i = 0 # right index j = k # O(N) while j <= len_nums: average = sum(nums[i: j]) / k if max_average < average: max...
maximum-average-subarray-i
Concise Python and golang Solution
namashin
0
5
maximum average subarray i
643
0.438
Easy
10,681
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2727214/Concise-Python-and-golang-Solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: len_nums = len(nums) # Set minimum size max_size = sum(nums[: k]) # Current average size current_size = max_size for i in range(k, len_nums): current_size += nums[i] - nums[i - k] if max_size < current_s...
maximum-average-subarray-i
Concise Python and golang Solution
namashin
0
5
maximum average subarray i
643
0.438
Easy
10,682
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2701111/Pattern-sliding-window
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: win_sum, win_start, max_sum = 0, 0, 0 temp = None for win_end in range(len(nums)): win_sum += nums[win_end] if win_end >= k-1: if temp is None: temp = win_s...
maximum-average-subarray-i
Pattern sliding window
samratM
0
6
maximum average subarray i
643
0.438
Easy
10,683
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2677207/Simple-python-solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: m = sum(nums[:k]) avg = m/k for i in range(k,len(nums)): m = m - nums[i-k] + nums[i] if (m/k) > avg: avg = m/k return avg
maximum-average-subarray-i
Simple python solution
parthdixit
0
17
maximum average subarray i
643
0.438
Easy
10,684
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2645197/Python3-Solution-oror-O(N)-Time-and-O(1)-Space-Complexity
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: sum=0 n=len(nums) for i in range(k): sum+=nums[i] maxSum=sum for i in range(k,n): sum=sum+nums[i]-nums[i-k] if sum>maxSum: maxSum=sum return...
maximum-average-subarray-i
Python3 Solution || O(N) Time & O(1) Space Complexity
akshatkhanna37
0
5
maximum average subarray i
643
0.438
Easy
10,685
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2404512/Python%3A-Sliding-Window%3A-O(n)-Time-and-Space-Complexity
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: result = [] window_sum, window_start = 0,0 for window_end in range(len(nums)): window_sum += nums[window_end] # we do k -1 instead of k because you always have 1 var in t...
maximum-average-subarray-i
Python: Sliding Window: O(n) Time & Space Complexity
obaissa
0
111
maximum average subarray i
643
0.438
Easy
10,686
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2315252/Python3-or-Sliding-Window-O(n)-Solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: #sliding window technique! L, R = 0, 0 cur_sum = 0 length = 0 output = float(-inf) while R < len(nums): #process right element first! cur_sum += nums[R] ...
maximum-average-subarray-i
Python3 | Sliding Window O(n) Solution
JOON1234
0
36
maximum average subarray i
643
0.438
Easy
10,687
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2164028/Python-Sliding-Window-Solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: max_sum = current_sum = sum(nums[0:k]) for i in range(k, len(nums)): current_sum += nums[i] - nums[i-k] if(current_sum > max_sum): max_sum = current_sum ...
maximum-average-subarray-i
Python Sliding Window Solution
kaus_rai
0
75
maximum average subarray i
643
0.438
Easy
10,688
https://leetcode.com/problems/maximum-average-subarray-i/discuss/2051559/Python-Sliding-Window-Solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: current = sum(nums[0 : k]) mx, i = current / k, 1 while i < len(nums) - k + 1: current = current - nums[i - 1] + nums[k + i - 1] mx, i = max(mx, current / k), i + 1 ...
maximum-average-subarray-i
Python Sliding Window Solution
Hejita
0
88
maximum average subarray i
643
0.438
Easy
10,689
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1995520/Python-Clean-and-Simple!-From-TLE-to-Accepted
class Solution: def findMaxAverage(self, nums, k): n = len(nums) maxTotal = sum(nums[:k]) for i in range(k, n+1): total = sum(nums[i-k:i]) maxTotal = max(maxTotal, total) return maxTotal / k
maximum-average-subarray-i
Python - Clean and Simple! From TLE to Accepted
domthedeveloper
0
123
maximum average subarray i
643
0.438
Easy
10,690
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1995520/Python-Clean-and-Simple!-From-TLE-to-Accepted
class Solution: def findMaxAverage(self, nums, k): n = len(nums) maxTotal = total = sum(nums[:k]) for i in range(k, n): total -= nums[i-k] total += nums[i] maxTotal = max(total, maxTotal) return maxTotal / k
maximum-average-subarray-i
Python - Clean and Simple! From TLE to Accepted
domthedeveloper
0
123
maximum average subarray i
643
0.438
Easy
10,691
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1979308/Python-or-Sliding-Window-or-O(N)-Time-or-O(1)-Space-or-Fully-Explained-with-comments
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: # If the array contains only one element # then average would certainly be equal # to the element itself. if len(nums) == 1: return float(nums[0]) sumK = -math.inf # stores the maximum sum of k elements. calcSumK = 0 ...
maximum-average-subarray-i
Python | Sliding Window | O(N) Time | O(1) Space | Fully Explained with comments
ranitdey94
0
132
maximum average subarray i
643
0.438
Easy
10,692
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1901100/Python-Easiest-Solution-With-Explanation-or-93.30-Faster-or-Sliding-Window-or-Beg-to-Adv
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: average = [] # taking a empty list for capturing average of different sum, start = 0, 0 for i in range(len(nums)): sum += nums[i] # adding elements for calculating average ...
maximum-average-subarray-i
Python Easiest Solution With Explanation | 93.30% Faster | Sliding Window | Beg to Adv
rlakshay14
0
72
maximum average subarray i
643
0.438
Easy
10,693
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1614780/Easy-to-understand-prefixsum-python3-solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: n=len(nums) s=sum(nums[:k]) res=s/k prefix=[0]*(n) prefix[0]=nums[0] for i in range(1,n): prefix[i]=prefix[i-1]+nums[i] for i in range(k,n): ...
maximum-average-subarray-i
Easy to understand prefixsum python3 solution
Karna61814
0
38
maximum average subarray i
643
0.438
Easy
10,694
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1614755/Easy-to-understand-sliding-window-python3-solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: n=len(nums) s=sum(nums[:k]) res=s/k for i in range(1,n-k+1): s-=nums[i-1] s+=nums[i+k-1] res=max(res,s/k) return res
maximum-average-subarray-i
Easy to understand sliding window python3 solution
Karna61814
0
35
maximum average subarray i
643
0.438
Easy
10,695
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1561614/Python3-simple-sliding-window-solution
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: max_average: int = sum(nums[:k]) average: int = max_average for i in range(k, len(nums)): average = average + nums[i] - nums[i - k] max_average = max(max_average, average) ...
maximum-average-subarray-i
Python3 simple sliding window solution
sirenescx
0
127
maximum average subarray i
643
0.438
Easy
10,696
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1392086/Python-3-Faster-than-86
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: s = 0 for i in range(k): s += nums[i] m=s for i in range(k, len(nums) ,1): s = s-nums[i-k]+nums[i] m = max(m,s) return m/k
maximum-average-subarray-i
Python 3 Faster than 86%
saumyasuvarna
0
161
maximum average subarray i
643
0.438
Easy
10,697
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1342675/Python-Solution-or-Time-O(n)-or-Space-O(1)
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: # O(n) if len(nums) == k: return sum(nums) / k # O(n) max_sum = tmp_sum = sum(nums[0: k]) for right in range(k, len(nums)): left = right - k tmp_s...
maximum-average-subarray-i
Python Solution | Time - O(n) | Space - O(1)
peatear-anthony
0
74
maximum average subarray i
643
0.438
Easy
10,698
https://leetcode.com/problems/maximum-average-subarray-i/discuss/1304844/Python3-dollarolution-(95-Faster)
class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: v = sum(nums[0:k]) s = v for i in range(k,len(nums)): v = v - nums[i-k] + nums[i] if s < v: s = v return s/k
maximum-average-subarray-i
Python3 $olution (95% Faster)
AakRay
0
129
maximum average subarray i
643
0.438
Easy
10,699