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/interval-list-intersections/discuss/2551919/Python-Solution
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: first_list_pointer = 0 second_list_pointer = 0 ans = [] while first_list_pointer < len(firstList) and second_list_pointer < len(secondList): # find if the two intervals are overlaping, two intervals are said to overlap # if max(start1, start) <= min(end1, end2) max_start = max(firstList[first_list_pointer][0], secondList[second_list_pointer][0]) min_end = min(firstList[first_list_pointer][1], secondList[second_list_pointer][1]) # Intersecting condition if max_start <= min_end: ans.append([max_start, min_end]) # search for next higher end time for interval in either firstList or secondlist if firstList[first_list_pointer][1] > secondList[second_list_pointer][1]: second_list_pointer += 1 else: first_list_pointer += 1 return ans Second Aproach class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: ans = [] p1 = p2 = 0 while p1 < len(firstList) and p2 < len(secondList): aux = [firstList[p1], secondList[p2]] aux.sort() if aux[0][0] <= aux[1][0] <= aux[0][1]: ans.append([max(firstList[p1][0], secondList[p2][0]),min(firstList[p1][1], secondList[p2][1])]) if firstList[p1][1] <= secondList[p2][1]: p1 += 1 else: p2 += 1 return ans
interval-list-intersections
Python Solution
DietCoke777
1
34
interval list intersections
986
0.714
Medium
16,000
https://leetcode.com/problems/interval-list-intersections/discuss/2429574/As-easy-as-it-comes(plain-English)-python3-solution-with-complexity-analysis
class Solution: # O(n + m) time, # O(n + m) space, # Approach: two pointers def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: ans = [] n = len(firstList) m = len(secondList) def findIntersection(interval1: List[int], interval2: List[int]) -> List[int]: lower_bound = max(interval1[0], interval2[0]) upper_bound = min(interval1[1], interval2[1]) if lower_bound > upper_bound: return [lower_bound] return [lower_bound, upper_bound] i, j = 0, 0 while i < n and j < m: interval1 = firstList[i] interval2 = secondList[j] intersection = findIntersection(interval1, interval2) higher_bound = intersection[-1] if len(intersection) > 1: ans.append(intersection) if interval1[-1] > higher_bound: j+=1 else: i +=1 return ans
interval-list-intersections
As easy as it comes(plain English), python3 solution with complexity analysis
destifo
1
8
interval list intersections
986
0.714
Medium
16,001
https://leetcode.com/problems/interval-list-intersections/discuss/2400696/Python3-easy-to-understand.-Not-too-pythonic
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: # a: [x, y], b: [u, v]. ret = [] # while there is still both, since will ignore everything that is not in. i = j = 0 while i < len(firstList) and j < len(secondList): interval = firstList[i] interval2 = secondList[j] # case where x > u if interval[0] > interval2[0]: start = interval[0] # case where u >= x else: start = interval2[0] # could be optimized but I am lazy end = min(interval[1], interval2[1]) if start <= end: ret.append([start, end]) # too lazy to manually calculate min if end == interval[1]: i += 1 # using if for a reason. # reason is because both could be at end lol. if end == interval2[1]: j += 1 return ret
interval-list-intersections
Python3, easy to understand. Not too pythonic
randomlylelo
1
28
interval list intersections
986
0.714
Medium
16,002
https://leetcode.com/problems/interval-list-intersections/discuss/1986161/oror-PYTHON-SOL-oror-EASY-oror-LINEAR-SOL-oror-EXPLAINED-oror
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: n1 = len(firstList) n2 = len(secondList) i1,i2 = 0,0 ans = [] while i1<n1 and i2<n2: l = firstList[i1][0] if firstList[i1][0] > secondList[i2][0] else secondList[i2][0] r = firstList[i1][1] if firstList[i1][1] < secondList[i2][1] else secondList[i2][1] if firstList[i1][1] < secondList[i2][1]: i1 += 1 else: i2 += 1 if l <= r: ans.append([l,r]) return ans
interval-list-intersections
|| PYTHON SOL || EASY || LINEAR SOL || EXPLAINED ||
reaper_27
1
54
interval list intersections
986
0.714
Medium
16,003
https://leetcode.com/problems/interval-list-intersections/discuss/1895158/simple-python3-solution-with-queue-and-greedy-algorithm
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: result = [] def getIntersection(fl, sl): maxStartTime = max(fl[0], sl[0]) minEndTime = min(fl[1], sl[1]) if maxStartTime <= minEndTime: result.append([maxStartTime, minEndTime]) return while len(firstList)!=0 and len(secondList)!=0: getIntersection(firstList[0], secondList[0]) # greedily pop the item that ends first if firstList[0][1] < secondList[0][1]: firstList.pop(0) else: secondList.pop(0) return result
interval-list-intersections
simple python3 solution with queue and greedy algorithm
karanbhandari
1
48
interval list intersections
986
0.714
Medium
16,004
https://leetcode.com/problems/interval-list-intersections/discuss/2847464/interval-list-intersections
class Solution: def check_overlap(self,int_val1,int_val2): overlap=[max(int_val1[0],int_val2[0]),min(int_val1[1],int_val2[1])] if overlap[0]>overlap[1]: return None return overlap def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: i=0 j=0 overlap_li=[] while i<len(firstList) and j < len(secondList): overlap=self.check_overlap(firstList[i],secondList[j]) if overlap: overlap_li.append(overlap) if firstList[i][1]<secondList[j][1]: i+=1 else: j+=1 return overlap_li
interval-list-intersections
interval-list-intersections
shaikkamran
0
1
interval list intersections
986
0.714
Medium
16,005
https://leetcode.com/problems/interval-list-intersections/discuss/2816949/Python-O(n)-(maybe-O(n-%2B-m))-solution-Accepted
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: fint = 0 sint = 0 ans = [] while fint < len(firstList) and sint < len(secondList): lowbound = max(firstList[fint][0], secondList[sint][0]) highbound = min(firstList[fint][1], secondList[sint][1]) if lowbound <= highbound: ans.append([lowbound, highbound]) if firstList[fint][1] < secondList[sint][1]: fint += 1 else: sint += 1 return ans
interval-list-intersections
Python O(n) (maybe O(n + m)) solution [Accepted]
lllchak
0
1
interval list intersections
986
0.714
Medium
16,006
https://leetcode.com/problems/interval-list-intersections/discuss/2808507/hash-table-is-all-you-need
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: hash1={} hash2={} for i in range(len(firstList)): hash1[i]=firstList[i] for j in range(len(secondList)): hash2[j]=secondList[j] out=[] for i in range(len(firstList)): for j in range(len(secondList)): inter_1=hash1[i] inter_2=hash2[j] l=max(inter_1[0],inter_2[0]) r=min(inter_1[1],inter_2[1]) if r-l>=0: out.append([l,r]) return out
interval-list-intersections
hash table is all you need
althrun
0
1
interval list intersections
986
0.714
Medium
16,007
https://leetcode.com/problems/interval-list-intersections/discuss/2770942/python-oror-easy-solu-oror-using-Two-Pointer
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: l=[] m=len(firstList) n=len(secondList) i=0 j=0 while i<m and j<n: if firstList[i][0]<=secondList[j][1] and secondList[j][0]<=firstList[i][1]: l.append([max(firstList[i][0],secondList[j][0]),min(secondList[j][1],firstList[i][1])]) if firstList[i][1]>secondList[j][1]: j+=1 else: i+=1 return (l)
interval-list-intersections
python || easy solu || using Two Pointer
tush18
0
1
interval list intersections
986
0.714
Medium
16,008
https://leetcode.com/problems/interval-list-intersections/discuss/2767965/Two-Pointers
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: l=[] i,j=0,0 while i<len(firstList) and j<len(secondList): s=max(firstList[i][0],secondList[j][0]) e=min(firstList[i][1],secondList[j][1]) if (s<=e): l.append([s,e]) if(firstList[i][1]<=secondList[j][1]): i+=1 else: j+=1 return l
interval-list-intersections
Two Pointers
liontech_123
0
3
interval list intersections
986
0.714
Medium
16,009
https://leetcode.com/problems/interval-list-intersections/discuss/2697115/Python-solution-or-O(m%2Bn)-time
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: ans = [] FirstIndex = 0 SecondIndex = 0 while FirstIndex < len(firstList) and SecondIndex < len(secondList): left = max(firstList[FirstIndex][0], secondList[SecondIndex][0]) right = min(firstList[FirstIndex][1], secondList[SecondIndex][1]) if left > right: if firstList[FirstIndex][0] < secondList[SecondIndex][0]: FirstIndex += 1 else: SecondIndex += 1 else: ans.append([left,right]) if firstList[FirstIndex][1] < secondList[SecondIndex][1]: FirstIndex += 1 else: SecondIndex += 1 return ans
interval-list-intersections
Python solution | O(m+n) time
maomao1010
0
7
interval list intersections
986
0.714
Medium
16,010
https://leetcode.com/problems/interval-list-intersections/discuss/2683308/Easy-Solution
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: p = 0 q = 0 res = [] while p < len(firstList) and q < len(secondList): start = max(firstList[p][0], secondList[q][0]) stop = min(firstList[p][1], secondList[q][1]) if start <= stop: res.append([start, stop]) if firstList[p][1] > secondList[q][1]: q += 1 else: p += 1 return res
interval-list-intersections
Easy Solution
user6770yv
0
3
interval list intersections
986
0.714
Medium
16,011
https://leetcode.com/problems/interval-list-intersections/discuss/2657592/Two-pointers-python-simple-solution
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: i, j = 0, 0 res = [] while i < len(firstList) and j < len(secondList): start1, end1 = firstList[i][0], firstList[i][1] start2, end2 = secondList[j][0], secondList[j][1] if end1 >= start2 and start1 <= end2: res.append([max(start1, start2), min(end1, end2)]) if end1 >= end2: j += 1 else: i += 1 return res
interval-list-intersections
Two pointers python simple solution
wguo
0
4
interval list intersections
986
0.714
Medium
16,012
https://leetcode.com/problems/interval-list-intersections/discuss/2527055/Python3%3A-Two-Indices-to-track-the-two-arrays
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: i = j = 0 result = [] while i < len(firstList) and j < len(secondList): a_left, a_right = firstList[i] b_left, b_right = secondList[j] if a_left <= b_right and b_left <= a_right: result.append([max(a_left,b_left), min(a_right,b_right)]) if a_right <= b_right: i += 1 else: j += 1 return result
interval-list-intersections
Python3: Two Indices to track the two arrays
NinjaBlack
0
10
interval list intersections
986
0.714
Medium
16,013
https://leetcode.com/problems/interval-list-intersections/discuss/1704526/Python3-Solution
class Solution: def intervalIntersection(self, A, B): ans, i, j = [], 0, 0 while i < len(A) and j < len(B): if A[i][1] >= B[j][0] and A[i][0] <= B[j][1]: ans.append([max(A[i][0], B[j][0]), min(A[i][1], B[j][1])]) if A[i][1] < B[j][1]: i += 1 else: j += 1 return ans
interval-list-intersections
Python3 Solution
nomanaasif9
0
24
interval list intersections
986
0.714
Medium
16,014
https://leetcode.com/problems/interval-list-intersections/discuss/1698939/python-simple-two-pointers-O(m%2Bn)-time-O(1)-extra-space-solution
class Solution: def intervalIntersection(self, first: List[List[int]], second: List[List[int]]) -> List[List[int]]: m, n = len(first), len(second) i, j = 0, 0 def intersect(x1, x2): # intersection of [a1, b1], [a2, b2] a1, b1 = x1[0], x1[1] a2, b2 = x2[0], x2[1] if a2 < a1: a1, b1, a2, b2 = a2, b2, a1, b1 # now a1 <= a2 if a2 <= b1: return [a2, min(b1, b2)] else: return [] res = [] while i < m and j < n: arr = intersect(first[i], second[j]) if arr: res.append(arr) if first[i][1] < second[j][1]: i += 1 elif first[i][1] > second[j][1]: j += 1 else: i += 1 j += 1 else: if first[i][0] > second[j][1]: j += 1 else: # first[i][1] < second[j][0]: i += 1 return res
interval-list-intersections
python simple two-pointers O(m+n) time, O(1) extra space solution
byuns9334
0
33
interval list intersections
986
0.714
Medium
16,015
https://leetcode.com/problems/interval-list-intersections/discuss/1594238/Python-Simple-Solution.-Beats-95.30-and-39.75
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: i,j=0,0 start=0 end=1 ans=[] while i<len(firstList) and j<len(secondList): if firstList[i][start]<secondList[j][start]: #S1 FirstList starts before SecondList if firstList[i][end]<secondList[j][start]: #C1 nothing common i+=1 continue else: first=secondList[j][start] if firstList[i][end]>secondList[j][end]: second=secondList[j][end] #C3 Firstlist overlaps SecondList.Secondlist to increment j+=1 else: #C2 Secondlist ends after firstList, Firstlist to increment second=firstList[i][end] i+=1 ans.append([first,second]) else: #S2 Second Starts before first if firstList[i][start]>secondList[j][end]: #C4 Nothing common j+=1 continue else: first=firstList[i][start] if secondList[j][end]>firstList[i][end]: #C6 Second OverLaps First. First to increment second=firstList[i][end] i+=1 else: #C5 First Ends after Second, second to increment second=secondList[j][end] j+=1 ans.append([first,second]) return ans
interval-list-intersections
Python Simple Solution. Beats 95.30% and 39.75%
JMV5000
0
12
interval list intersections
986
0.714
Medium
16,016
https://leetcode.com/problems/interval-list-intersections/discuss/1575292/One-while-loop-for-two-indices-99-speed
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: len1, len2 = len(firstList), len(secondList) if not len1 or not len2: return [] len1_1, len2_1 = len1 - 1, len2 - 1 i = j = 0 ans = [] both_reached = False while i < len1 or j < len2: left = max(firstList[i][0], secondList[j][0]) right = min(firstList[i][1], secondList[j][1]) if left <= right: if ans: if [left, right] != ans[-1]: ans.append([left, right]) else: ans.append([left, right]) if firstList[i][1] <= secondList[j][1]: if i < len1_1: i += 1 elif j < len2_1: j += 1 else: if j < len2_1: j += 1 elif i < len1_1: i += 1 if both_reached: break if i == len1_1 and j == len2_1: both_reached = True return ans
interval-list-intersections
One while loop for two indices, 99% speed
EvgenySH
0
100
interval list intersections
986
0.714
Medium
16,017
https://leetcode.com/problems/interval-list-intersections/discuss/1460927/Python3-Two-pointers-solution-with-results
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: first, second = 0, 0 res = [] while first < len(firstList) and second < len(secondList): first_begin, first_end = firstList[first] second_begin, second_end = secondList[second] new_begin = max(first_begin, second_begin) new_end = min(first_end, second_end) if new_begin <= new_end: res.append([new_begin, new_end]) if first_end < second_end: first += 1 else: second += 1 return res
interval-list-intersections
[Python3] Two pointers solution with results
maosipov11
0
20
interval list intersections
986
0.714
Medium
16,018
https://leetcode.com/problems/interval-list-intersections/discuss/1453202/PyPy3-Simple-solution-with-comments
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: # A function which defines all criteria # possible between two intervals. This function # also help in deciding which index to increment # which to not increment. # x : First Interval at ith index of firstList # y : Second Interval at jth index of secondList def commonInterval(x,i,y,j): x1, x2 = x y1, y2 = y if x1 <= y1 <= y2 <= x2: return y,i,j+1 elif y1 <= x1 <= x2 <= y2: return x,i+1,j elif x1 <= y1 <= x2 <= y2: return [y1,x2],i+1,j elif y1 <= x1 <= y2 <= x2: return [x1,y2],i,j+1 elif x2 == y1: return [x2,y1],i+1,j elif x2 < y1: return None,i+1,j elif y2 == x1: return [y2,x1],i,j+1 elif y2 < x1: return None,i,j+1 else: return None,i,j # Init n = len(firstList) m = len(secondList) output = [] # Minimum conidition if n and m: # Indexes i = 0 # for firstList j = 0 # for secondList # Loop for each possiblilities till # both the indexes are valid while i < n and j < m: # get interval at index i of firstList x = firstList[i] # get interval at index j of secondList y = secondList[j] # find common interval and increment indexes c,i,j = commonInterval(x,i,y,j) # If interval is not none, append to output if c: output.append(c) return output
interval-list-intersections
[Py/Py3] Simple solution with comments
ssshukla26
0
40
interval list intersections
986
0.714
Medium
16,019
https://leetcode.com/problems/interval-list-intersections/discuss/1296757/Python3-solution-using-single-while-loop
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: res = [] i = 0 j = 0 while i < len(firstList) and j < len(secondList): if firstList[i][1] < secondList[j][0]: i += 1 elif firstList[i][0] > secondList[j][1]: j += 1 else: res.append([max(firstList[i][0], secondList[j][0]),min(firstList[i][1], secondList[j][1])]) if firstList[i][1] < secondList[j][1]: i += 1 else: j += 1 return res
interval-list-intersections
Python3 solution using single while loop
EklavyaJoshi
0
18
interval list intersections
986
0.714
Medium
16,020
https://leetcode.com/problems/interval-list-intersections/discuss/1277761/Python-O(min(m-n))-solution-using-DeMorgan's-Law-(Runtime%3A-136ms-beats-98.77)
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: i = j = 0 m, n = len(firstList), len(secondList) res = [] while i < m and j < n: if not (firstList[i][1] < secondList[j][0] or secondList[j][1] < firstList[i][0]): res.append([max(firstList[i][0], secondList[j][0]), min(firstList[i][1], secondList[j][1])]) if firstList[i][1] < secondList[j][1]: i += 1 else: j += 1 return res
interval-list-intersections
Python O(min(m, n)) solution using DeMorgan's Law (Runtime: 136ms - beats 98.77%)
genefever
0
40
interval list intersections
986
0.714
Medium
16,021
https://leetcode.com/problems/interval-list-intersections/discuss/1261917/Python-Two-Pointers-O(n-%2B-m)
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: intersection = [] i, j = 0, 0 # Traverse while i < len(firstList) and j < len(secondList): # Overlap if secondList[j][1] >= firstList[i][0]: start = max(firstList[i][0], secondList[j][0]) end = min(firstList[i][1], secondList[j][1]) # Otherwise implies no overlap if start <= end: intersection.append([start, end]) # Update pointers if firstList[i][1] < secondList[j][1]: i += 1 else: j += 1 return intersection
interval-list-intersections
[Python] Two Pointers O(n + m)
jsanchez78
0
94
interval list intersections
986
0.714
Medium
16,022
https://leetcode.com/problems/interval-list-intersections/discuss/1093227/Python-or-O(N%2BM)-Time-or-O(N)-Space
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: index1 = index2 = 0 start, end = 0, 1 merged_list = [] while index1 < len(firstList) and index2 < len(secondList): overlap1 = firstList[index1][start] <= secondList[index2][end] \ and firstList[index1][start] >= secondList[index2][start] overlap2 = secondList[index2][start] <= firstList[index1][end] \ and secondList[index2][start] >= firstList[index1][start] if overlap1 or overlap2: merged_list.append([max(firstList[index1][start], secondList[index2][start]), min(firstList[index1][end], secondList[index2][end])]) if firstList[index1][end] < secondList[index2][end]: index1 += 1 else: index2 += 1 return merged_list
interval-list-intersections
Python | O(N+M) Time | O(N) Space
Rakesh301
0
35
interval list intersections
986
0.714
Medium
16,023
https://leetcode.com/problems/interval-list-intersections/discuss/461381/Python-3-(six-lines)-(beats-~100)
class Solution: def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]: LA, LB, I, i, j = len(A), len(B), [], 0, 0 while i < LA and j < LB: a, b, i = A[i], B[j], i + 1 if a[1] > b[1]: a, b, i, j = b, a, i - 1, j + 1 if b[0] <= a[1]: I.append([max(a[0],b[0]),a[1]]) return I - Junaid Mansuri - Chicago, IL
interval-list-intersections
Python 3 (six lines) (beats ~100%)
junaidmansuri
0
159
interval list intersections
986
0.714
Medium
16,024
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2526928/Python-BFS-%2B-Hashmap
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: results = defaultdict(list) queue = [ (root, 0, 0) ] while queue: node, pos, depth = queue.pop(0) if not node: continue results[(pos,depth)].append(node.val) results[(pos,depth)].sort() queue.extend( [ (node.left, pos-1, depth+1), (node.right, pos+1, depth+1) ] ) res = defaultdict(list) keys = sorted(list(results.keys()), key=lambda x: (x[0], x[1])) for k in keys: pos, depth = k res[pos].extend(results[k]) return res.values()
vertical-order-traversal-of-a-binary-tree
Python BFS + Hashmap
complete_noob
13
1,700
vertical order traversal of a binary tree
987
0.447
Hard
16,025
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2527209/Easy-Python-code-with-DFS-and-Default-Dictionary
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: ans = [] def dfs(root,r,c): if root: ans.append([r,c,root.val]) dfs(root.left,r+1,c-1) dfs(root.right,r+1,c+1) return dfs(root,0,0) ans=sorted(ans,key=lambda x:(x[1],x[0],x[2])) d=defaultdict(list) for i,j,k in ans: d[j].append(k) l=[] for i in d.values(): l.append(i) return l
vertical-order-traversal-of-a-binary-tree
Easy Python code with DFS and Default Dictionary
a_dityamishra
2
124
vertical order traversal of a binary tree
987
0.447
Hard
16,026
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/1040240/Elegant-and-Intuitive-Python3-solution-(using-dict-of-dict)
class Solution: def __init__(self): self.order = collections.defaultdict(dict) def dfs(self, node, x, y): if not node: return self.order[x][y] = self.order[x].get(y, []) + [node.val] self.dfs(node.left, x-1, y-1) self.dfs(node.right, x+1, y-1) def verticalTraversal(self, root: TreeNode) -> List[List[int]]: # placeholder to store the list of reports verticalOrder = [] # step 1 : traverse the tree, to create list of values at each (x, y) self.dfs(root, 0, 0) # step 2 : at each x, sort the values first by y, then by value for x in sorted(self.order): report = [] for y in sorted(self.order[x], reverse=True): report += sorted(self.order[x][y]) verticalOrder.append(report) # step 3 : return the list of reports return verticalOrder
vertical-order-traversal-of-a-binary-tree
Elegant and Intuitive Python3 solution (using dict of dict)
adkakne
2
94
vertical order traversal of a binary tree
987
0.447
Hard
16,027
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2150384/Python-queue-%2B-hashmap-simple-and-efficient-solution
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: d = defaultdict(list) q = [(root, 0)] start = end = 0 while q : n = len(q) curr = defaultdict(list) for i in range(n) : temp = q.pop(0) start = min(start, temp[1]) end = max(end, temp[1]) curr[temp[1]].append(temp[0].val) if temp[0].left : q.append((temp[0].left, temp[1]-1)) if temp[0].right : q.append((temp[0].right, temp[1]+1)) for i in curr : d[i] += sorted(curr[i]) return [d[i] for i in range(start, end+1)]
vertical-order-traversal-of-a-binary-tree
Python queue + hashmap simple and efficient solution
runtime-terror
1
131
vertical order traversal of a binary tree
987
0.447
Hard
16,028
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/1566881/Simple-python-iterative-DFS-O(N-log-Nk)-time-and-O(N)-space-with-explanation
class Solution(object): def verticalTraversal(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ myC=defaultdict(list) #key=col value=[(row,node.val),...] stack=[(root,0,0)] #node, col, row maxCol,minCol=0,0 #the goal of this to avoid sorting the whole myC dictionary at the end while stack: #DFS O(N) node,col,row=stack.pop() maxCol,minCol=max(maxCol,col),min(minCol,col) myC[col].append((row,node.val)) #append tuple to hashmap if node.left: stack.append((node.left,col-1,row+1)) #DFS: so row+1 and if left so col-1 if node.right: stack.append((node.right,col+1,row+1)) #DFS: so row+1 and if right so col+1 res=[] for col in range(minCol,maxCol+1): #loop on range otherwise I would loop on sorted(myC) that will result in added complexity res.append([v for row,v in sorted(myC[col])]) #for loop is O(N), sorted is O(XlogX), what is X here, #if we assume nodes are distributed on cols so each # of cols=K , so each col has N/k nodes, #so sorting 1 col is O(N/K log N/K), sorting K cols = O(NK/K log N/K) --> simplify = O(N log N/k) return res #so total time = O(N) DFS + O(N) for loop + O(NlogN/K) = O(NlogN/K) , while space=stack andhashmap = O(N)
vertical-order-traversal-of-a-binary-tree
Simple python 🐍 iterative DFS O(N log N/k) time and O(N) space with explanation
InjySarhan
1
112
vertical order traversal of a binary tree
987
0.447
Hard
16,029
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/978946/Python-Simplest-Solution
class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: res, positions = [], collections.defaultdict(list) def assignPositions(root: TreeNode, x: int, y: int): if not root: return assignPositions(root.left, x-1, y+1) positions[x].append((y, root.val)) assignPositions(root.right, x+1, y+1) assignPositions(root, 0, 0) for x in sorted(positions.keys()): res.append([i[1] for i in sorted(positions[x])]) return res
vertical-order-traversal-of-a-binary-tree
Python Simplest Solution
cj1989
1
167
vertical order traversal of a binary tree
987
0.447
Hard
16,030
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/659293/Super-simple-easy-to-understand-fast-basic-recursive-traversal-solution
class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: result = {} def traverse(node, width, depth): if node is None: return # (depth, val) order so that later we can sort by depth and if same depth then sort # by val in default sorted(), else we'll have to pass key=lambda x: (x[1], x[0]) # if it was val first i.e (val, depth) try: result[width].append((depth, node.val)) except KeyError: # Apparently using normal dict with try catch is faster than default dict # as well as dict.get(dist, []) way result[width] = [(depth, node.val)] traverse(node.left, width-1, depth+1) traverse(node.right, width+1, depth+1) traverse(root, 0, 0) # This is pretty fast even with sorting as these are really small lists to sort return [list(map(lambda x: x[1], sorted(v))) for _,v in sorted(result.items())]
vertical-order-traversal-of-a-binary-tree
Super simple, easy to understand fast basic recursive traversal solution
reachsaurabhpandey
1
84
vertical order traversal of a binary tree
987
0.447
Hard
16,031
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2602231/I-did-something-DFS-Sorting
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: ans = [] def dfs(node, level, width): if not node : return nonlocal ans ans.append((width, node.val, level)) dfs(node.left, level + 1, width - 1) dfs(node.right, level + 1, width + 1) dfs(root, 0, 0) # sort by width -> level (tie-break) -> value (tie-break) ans.sort(key = lambda x :(x[0], x[2], x[1])) res = [[ans[0][1]]] last = ans[0][0] for x in ans[1:]: if x[0] == last : res[-1].append(x[1]) else: res.append([x[1]]) last = x[0] return res
vertical-order-traversal-of-a-binary-tree
I did something - DFS, Sorting
kunal768
0
19
vertical order traversal of a binary tree
987
0.447
Hard
16,032
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2562477/Vertical-Order-Traversal-of-a-Binary-Tree-Python-3-Simple-Solution
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: lst = []; def traversal(node: Optional[TreeNode],row: int,col: int): #traversing the left child if it exists if node.left: traversal(node.left,row+1,col-1); #appending the present node after finishing the left most traversal lst.append([[row,col],node.val]); #traversing the right child if it exists if node.right: traversal(node.right,row+1,col+1); traversal(root,0,0); #collecting the distinct column values and sorting distinct = []; for i in lst: if i[0][1] not in distinct: distinct.append(i[0][1]); distinct.sort(); #nodes are sorted according to distinct(column values in ascending) lst1 = [[[k[0][0],k[1]] for k in lst if k[0][1] == j] for j in distinct]; #nodes are sorted according to row values lst2 = [[x[1] for x in y] for y in [sorted(m) for m in lst1]]; return lst2;
vertical-order-traversal-of-a-binary-tree
Vertical Order Traversal of a Binary Tree - Python 3 Simple Solution
shay1831
0
40
vertical order traversal of a binary tree
987
0.447
Hard
16,033
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2545664/Veritical-Tree-Traversal
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: traversal = defaultdict(list) output = [] queue = deque() queue.append((root, 0)) while queue: count = len(queue) level = defaultdict(list) for _ in range(count): node, column = queue.popleft() bisect.insort(level[column], node.val) if node.left is not None: queue.append((node.left, column - 1)) if node.right is not None: queue.append((node.right, column + 1)) for column in level.keys(): traversal[column] += level[column] for i in range(min(traversal), max(traversal) + 1): output.append(traversal[i]) return output
vertical-order-traversal-of-a-binary-tree
Veritical Tree Traversal
mansoorafzal
0
28
vertical order traversal of a binary tree
987
0.447
Hard
16,034
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2541235/Python-solution-using-bfs
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: ans = [] dic = {} q=[] q.append([root,0]) while(len(q)!=0): mydic={} lvl_size = len(q) for i in range(lvl_size): curr,col=q.pop(0) if col not in mydic: mydic[col]=[] mydic[col].append(curr.val) if curr.left: q.append([curr.left,col-1]) if curr.right: q.append([curr.right,col+1]) #print(mydic) for key in mydic.keys(): if key not in dic: dic[key]=[] for num in sorted(mydic[key]): dic[key].append(num) #print(dic) for key in sorted(dic.keys()): ans.append(dic[key]) return ans
vertical-order-traversal-of-a-binary-tree
Python solution [using bfs]
miyachan
0
23
vertical order traversal of a binary tree
987
0.447
Hard
16,035
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2532458/Python-dfs-and-Hashmap
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: res = collections.defaultdict(lambda: collections.defaultdict(list)) mini = [0] self.dfs(root, 0, 0, res, mini) ans = [None]*len(res) for i in range(mini[0], mini[0]+len(res)): temp = [] for j in sorted(res[i].keys()): res[i][j].sort() temp+=res[i][j] ans[i-mini[0]] = temp return ans def dfs(self, root, row, col, res, mini): if not root: return if col<mini[0]: mini[0] = col res[col][row].append(root.val) self.dfs(root.left, row+1, col-1, res, mini) self.dfs(root.right, row+1, col+1, res, mini) ```
vertical-order-traversal-of-a-binary-tree
Python dfs and Hashmap
li87o
0
8
vertical order traversal of a binary tree
987
0.447
Hard
16,036
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2531963/Python-or-BFS-or-HashMap
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: def bfs(curNode, curCol): q = collections.deque() q.append((curNode, curCol, 0)) colHash = defaultdict(list) while q: node, col, row = q.popleft() colHash[col].append([row, node.val]) if node.left: q.append((node.left, col-1, row+1)) if node.right: q.append((node.right, col+1, row+1)) return colHash # create hash map that has column of nodes in a certain row traversal = bfs(root, 0) # turn into list traversalArr = list(traversal.items()) # sort list by lowest column traversalArr.sort() # go through the list and sort each coumn by lowest row, if tie, will go by lowest node val for x in traversalArr: x[1].sort() # now go through each column and get the nodes in the column rowArr = [x[1] for x in traversalArr] res = [] # go through each array for arr in rowArr: # append every node value for each column res.append([x[1] for x in arr]) return res
vertical-order-traversal-of-a-binary-tree
Python | BFS | HashMap
Mark5013
0
8
vertical order traversal of a binary tree
987
0.447
Hard
16,037
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2530927/Python-simple-DFS-using-stack-with-heavy-comments
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: d = collections.defaultdict(list) # in stack, also store row and column stack = [(root, 0, 0)] # While we have stuff in the stack while stack: # pop the node node, row, col = stack.pop() # if node is not None if node: # columns are keys for the dictionary # put the node's value into dictionary as a tuple, (row, value) d[col].append((row, node.val)) # push right and left children with row and column to stack stack.append((node.right, row + 1, col + 1)) stack.append((node.left, row + 1, col - 1)) # sort items with same rows d = {k: sorted(v) for k, v in d.items()} # sort by dictionary keys, which are columns # then convert tuples into values return [list(map(lambda x: x[1], tup)) for tup in dict(sorted(d.items())).values()]
vertical-order-traversal-of-a-binary-tree
Python simple DFS using stack with heavy comments
shipalnomoo
0
3
vertical order traversal of a binary tree
987
0.447
Hard
16,038
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2529793/Python3-Simple-DFS-solution
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: def dfs(node: Optional[TreeNode], row: int, col: int): if not node: return cols[col].append((row, node.val)) dfs(node.left, row+1, col-1) dfs(node.right, row+1, col+1) cols = defaultdict(list) dfs(root, 0, 0) res = [] for col in sorted(cols.keys()): res.append([val for _, val in sorted(cols[col])]) return res
vertical-order-traversal-of-a-binary-tree
[Python3] Simple DFS solution
geka32
0
18
vertical order traversal of a binary tree
987
0.447
Hard
16,039
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2529687/Python3-99.86-Faster-solution-using-BFS-and-Hashmap
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: if not root: return [[]] # if root is null, return empty list queue = deque() dict = defaultdict(list) # just an ordinary dictionary/hashmap queue.append([root, 0, 0]) # Appending [node, coloumn, row] in queue leftMost, rightMost = 0, 0 # to determine the leftmost and rightmost coloumn number while queue: node, col, row = queue.popleft() dict[col].append([row, node.val]) # on the key of coloumn, we are appending values like [row, node value] if node.left: queue.append([node.left, col-1, row+1]) leftMost = min(leftMost, col - 1) # Getting the left most coloumn number if node.right: queue.append([node.right, col+1, row+1]) rightMost = max(rightMost, col + 1) # Getting the right most coloumn number ans = [] # Initializing the answer list for i in range(leftMost, rightMost+1): if dict[i]: # Checking if this coloumn has any value dict[i] = sorted(dict[i], key= lambda x: (x[0], x[1])) # sorting the values firstly with respect to level and after that with respect to node value tempArr = [] for j in dict[i]: tempArr.append(j[1]) # appending node values in temporary array ans.append(tempArr) # appending temporary array values in answer array return ans
vertical-order-traversal-of-a-binary-tree
[Python3] 99.86% Faster solution using BFS and Hashmap
mahedee_
0
12
vertical order traversal of a binary tree
987
0.447
Hard
16,040
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2529623/Python-Easy-to-understand-DFS-iterative
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: levels = defaultdict(list) stack = [(root, 0, 0)] result = [] while stack: node, row, col = stack.pop() levels[col].append([row, node.val]) if node.left: stack.append([node.left, row+1, col-1]) if node.right: stack.append([node.right, row+1, col+1]) for val in sorted(levels.keys()): result.append([v[1] for v in sorted(levels[val])]) return result
vertical-order-traversal-of-a-binary-tree
[Python] Easy to understand DFS iterative
dlog
0
11
vertical order traversal of a binary tree
987
0.447
Hard
16,041
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2529080/Easy-to-understand-2-short-python-solutions-or-with-Explanations
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: dic = defaultdict(list) def solve(root, vDist, hDist): if root: dic[vDist].append((hDist, root.val)) solve(root.left, vDist - 1, hDist + 1) solve(root.right, vDist + 1, hDist + 1) solve(root, 0, 0) k = list(dic.keys()) k.sort() ans = [] for key in k: values = sorted(dic[key]) ans.append([val[1] for val in values]) return ans # solution 2 # store = [] # def solve(root, vDist, hDist): # if root: # store.append((vDist, hDist, root.val)) # solve(root.left, vDist - 1, hDist + 1) # solve(root.right, vDist + 1, hDist + 1) # solve(root, 0, 0) # store.sort(reverse = True) # ans = [[]] # prevVDist = None # i = 0 # while store: # item = store.pop() # if prevVDist is not None and prevVDist != item[0]: # i += 1 # ans.append([]) # prevVDist = item[0] # ans[i].append(item[2]) # return ans
vertical-order-traversal-of-a-binary-tree
Easy to understand 2 short python solutions | with Explanations
ramsudharsan
0
15
vertical order traversal of a binary tree
987
0.447
Hard
16,042
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2529008/Python3-90-sort-tuples-easy
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: nodes = [] ret = [] def traverse(root,row,col): if not root: return nodes.append((col,row,root.val)) traverse(root.left,row+1,col-1) traverse(root.right,row+1,col+1) traverse(root,0,0) nodes.sort() last = None for t in nodes: if last is None or last != t[0]: ret.append([t[2]]) last = t[0] else: ret[-1].append(t[2]) return ret
vertical-order-traversal-of-a-binary-tree
Python3 90% sort tuples easy
1ncu804u
0
5
vertical order traversal of a binary tree
987
0.447
Hard
16,043
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2528968/Python-Easy-BFS-Solution
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: dic={} dequeue = [(root,0,0)] while dequeue: curr,level,val = dequeue.pop() if val in dic: if level in dic[val]: dic[val][level].append(curr.val) else: dic[val][level] = [curr.val] else: dic[val] = {level:[curr.val]} if curr.left: dequeue.append((curr.left,level+1,val-1)) if curr.right: dequeue.append((curr.right,level+1,val+1)) res = [] for i in sorted(dic.keys()): curr = [] for j in sorted(dic[i]): curr.extend(sorted(dic[i][j])) res.append(curr) return res
vertical-order-traversal-of-a-binary-tree
Python Easy BFS Solution
sameer-555
0
10
vertical order traversal of a binary tree
987
0.447
Hard
16,044
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2528899/Vertical-Order-Traversal-of-a-Binary-Tree-Python-Solution
class Solution(object): def verticalTraversal(self, root): g = collections.defaultdict(list) queue = [(root,0)] while queue: new = [] d = collections.defaultdict(list) for node, s in queue: d[s].append(node.val) if node.left: new += (node.left, s-1), if node.right: new += (node.right,s+1), for i in d: g[i].extend(sorted(d[i])) queue = new return [g[i] for i in sorted(g)]
vertical-order-traversal-of-a-binary-tree
Vertical Order Traversal of a Binary Tree [ Python Solution ]
klu_2100031497
0
15
vertical order traversal of a binary tree
987
0.447
Hard
16,045
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2528803/Python-Solution
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: def id_adder(node, m, n): """Recursive function to add index id of node to tree_id""" if not node: return if tree_id.get((m, n)): tree_id[(m, n)].append(node.val) else: tree_id[(m, n)] = [node.val] id_adder(node.left, m+1, n-1) id_adder(node.right, m+1, n+1) tree_id = {} id_adder(root, 0, 0) # find the min and max of row and column max_row, min_col, max_col = 0, 0, 0 for row, col in tree_id: max_row = max(max_row, row) min_col = min(min_col, col) max_col = max(max_col, col) # vetical order traversal VOT_BT = [] for col in range(min_col, max_col + 1): current_col = [] for row in range(0, max_row + 1): current_element = tree_id.get((row, col)) if not current_element: continue current_element.sort() current_col += current_element VOT_BT.append(current_col) return VOT_BT
vertical-order-traversal-of-a-binary-tree
Python Solution
remenraj
0
7
vertical order traversal of a binary tree
987
0.447
Hard
16,046
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2528506/python-bfs-simple
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: ans = collections.defaultdict(list) queue = [(root,0)] while queue: ql = len(queue) newans = collections.defaultdict(list) for _ in range(ql): node, column = queue.pop(0) if not node: continue newans[column].append(node.val) queue.append((node.left,column-1)) queue.append((node.right,column+1)) for column in newans: ans[column] = ans[column] + sorted(newans[column]) return [ans[column] for column in sorted(ans.keys())]
vertical-order-traversal-of-a-binary-tree
python, bfs, simple
pjy953
0
4
vertical order traversal of a binary tree
987
0.447
Hard
16,047
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2528449/Easy-understandable-oror-Python-oror-DFS-and-sort
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: nodesInY = {} # inorder traversal to generate a map of list, key is column number def addToList(root, x, y): if root: addToList(root.left, x + 1, y - 1) if y in nodesInY: nodesInY[y].append((x, root.val)) else: nodesInY[y] = [(x, root.val)] addToList(root.right, x + 1, y + 1) addToList(root, 0, 0) ans = [] # nodesInY.keys() is unordered dict # inorder traversal won't guarantee this (eg: root.left is null but root.right.left.left exists) for y in range(min(nodesInY.keys()), max(nodesInY.keys()) + 1): nodesInY[y].sort() # key will be value at first index and then second index ans.append([n[1] for n in nodesInY[y]]) # append column list of values return ans
vertical-order-traversal-of-a-binary-tree
Easy understandable || Python || DFS and sort
wilspi
0
10
vertical order traversal of a binary tree
987
0.447
Hard
16,048
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2528362/Python-3-using-BFS-Min-Heap-Hashmap-O(nlogn)
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: #BFS with minheap and hashmap from collections import deque, defaultdict import heapq queue = deque() queue.append([0,0,root])#[col, row, val(tree structure)] minheap = [] res = [] while len(queue)>0: col,row,node = queue.popleft() heapq.heappush(minheap, [col,row,node.val]) if node.left is not None: queue.append([col-1, row+1, node.left]) if node.right is not None: queue.append([col+1, row+1, node.right]) hashmap = defaultdict(int)#{col: [val]} while len(minheap)>0: col, row, val = heapq.heappop(minheap) if col in hashmap: hashmap[col] += [val] else: hashmap[col] = [val] for key in list(hashmap.keys()): res.append(hashmap[key]) return res
vertical-order-traversal-of-a-binary-tree
Python 3 using BFS, Min-Heap, Hashmap, O(nlogn)
Arana
0
4
vertical order traversal of a binary tree
987
0.447
Hard
16,049
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2527575/Simple-Python-Solutions-with-defaultdict
class Solution: def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: cols_hash_map = collections.defaultdict(lambda : collections.defaultdict(list)) min_col = math.inf max_col = -math.inf max_row = -math.inf def traverse(root, row, col): nonlocal min_col, max_col, max_row if not root: return min_col = min(min_col, col) max_col = max(max_col, col) max_row = max(max_row, row) bisect.insort(cols_hash_map[col][row], root.val) traverse(root.left, row + 1, col - 1) traverse(root.right, row + 1, col + 1) traverse(root, 0, 0) res = [] for i in range(min_col, max_col + 1): tmp = [] for j in range(max_row + 1): tmp.extend(cols_hash_map[i][j]) res.append(tmp) return res
vertical-order-traversal-of-a-binary-tree
Simple Python Solutions with defaultdict
atiq1589
0
9
vertical order traversal of a binary tree
987
0.447
Hard
16,050
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/422855/Python-readable.-44ms-99.7-14MB-100
class Solution: res = 'z' * 13 # init max result, tree depth, 12< log2(8000) < 13 def smallestFromLeaf(self, root: TreeNode) -> str: def helper(node: TreeNode, prev): prev = chr(97 + node.val) + prev if not node.left and not node.right: self.res = min(self.res, prev) return if node.left: helper(node.left, prev) if node.right: helper(node.right, prev) helper(root, "") return self.res
smallest-string-starting-from-leaf
Python readable. 44ms 99.7% 14MB 100%
lsy7905
3
331
smallest string starting from leaf
988
0.497
Medium
16,051
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/1383626/Python-DFS-9-lines-with-comments
class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: paths = [] def dfs(node, string): # Translate node value to letter via ASCII string += chr(node.val + 97) if node.left: dfs(node.left, string) if node.right: dfs(node.right, string) # At leaf node, add reversed tree path to "paths" if not node.right and not node.left: paths.append(string[::-1]) dfs(root, '') # Sort in lexicographical order and return first path paths.sort() return paths[0]
smallest-string-starting-from-leaf
Python DFS 9 lines with comments
SmittyWerbenjagermanjensen
2
121
smallest string starting from leaf
988
0.497
Medium
16,052
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/2440095/Python3-or-DFS-%2BSorting
class Solution: def smallestFromLeaf(self, root: Optional[TreeNode]) -> str: ans=[] def dfs(root,ds): ds.append(chr(97+root.val)) if not root.left and not root.right: ans.append("".join(ds[:])) return if root.left: dfs(root.left,ds) ds.pop() if root.right: dfs(root.right,ds) ds.pop() dfs(root,[]) ans=sorted([i[::-1] for i in ans]) return ans[0]
smallest-string-starting-from-leaf
[Python3] | DFS +Sorting
swapnilsingh421
1
28
smallest string starting from leaf
988
0.497
Medium
16,053
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/1792112/Long-but-intuitive-solution-which-we-all-may-have-gone-through
class Solution: def __init__(self): pass def smallestFromLeaf(self, root) -> str: self.rlex = "" self.dfs(root) return self.rlex def dfs(self, root, lex=""): if root.left: self.dfs(root.left, chr(root.val + 97) + lex) if root.right: self.dfs(root.right, chr(root.val + 97) + lex) if root.left is None and root.right is None and self.rlex != "": self.compareLex(chr(root.val + 97) + lex, self.rlex) return elif root.left is None and root.right is None: self.rlex = chr(root.val + 97) + lex def compareLex(self, s1, s2): n1 = len(s1) n2 = len(s2) i = 0 if n1 < n2: while i < n1: if s1[i] < s2[i]: self.rlex = s1 return elif s2[i] < s1[i]: self.rlex = s2 return i += 1 self.rlex = s1 else: while i < n2: if s1[i] < s2[i]: self.rlex = s1 return elif s2[i] < s1[i]: self.rlex = s2 return i += 1 self.rlex = s2
smallest-string-starting-from-leaf
Long but intuitive solution which we all may have gone through
May-i-Code
1
36
smallest string starting from leaf
988
0.497
Medium
16,054
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/984859/Python3-dfs-O(N)
class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: ans = "" stack = [(root, "")] while stack: node, ss = stack.pop() ss += chr(node.val + 97) if node.left is node.right: ans = min(ans, ss[::-1]) if ans else ss[::-1] else: if node.left: stack.append((node.left, ss)) if node.right: stack.append((node.right, ss)) return ans
smallest-string-starting-from-leaf
[Python3] dfs O(N)
ye15
1
66
smallest string starting from leaf
988
0.497
Medium
16,055
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/1916085/Python-BFS
class Solution: def smallestFromLeaf(self, root: Optional[TreeNode]) -> str: q,result = collections.deque(),None q.append((root,chr(root.val+97))) while q: node,path = q.popleft() if not node.left and not node.right: if not result: result = path else: result = min(result,path) if node.left: q.append((node.left,chr(node.left.val+97)+path)) if node.right: q.append((node.right,chr(node.right.val+97)+path)) return result
smallest-string-starting-from-leaf
Python BFS
parthberk
0
14
smallest string starting from leaf
988
0.497
Medium
16,056
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/1781453/python-easy-to-read-and-understand-or-DFS
class Solution: def __init__(self): self.ans = 'z'*13 self.m = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] def dfs(self, node, path): if not node: return if not node.left and not node.right: path = self.m[node.val] + path self.ans = min(self.ans, path) return self.dfs(node.left, self.m[node.val]+path) self.dfs(node.right, self.m[node.val]+path) def smallestFromLeaf(self, root: Optional[TreeNode]) -> str: self.dfs(root, '') return self.ans
smallest-string-starting-from-leaf
python easy to read and understand | DFS
sanial2001
0
53
smallest string starting from leaf
988
0.497
Medium
16,057
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/1775751/Python3-DFS-solution
class Solution: def smallestFromLeaf(self, root: Optional[TreeNode]) -> str: self.ans="~" def dfs(root,path): if root==None: return if root.left==None and root.right==None: self.ans=min(self.ans,"".join(reversed(path+chr(97+root.val)))) dfs(root.left,path+chr(97+root.val)) dfs(root.right,path+chr(97+root.val)) dfs(root,"") return self.ans
smallest-string-starting-from-leaf
Python3 DFS solution
Karna61814
0
33
smallest string starting from leaf
988
0.497
Medium
16,058
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/1744187/python-simple-dfs-solution
class Solution: def smallestFromLeaf(self, root: Optional[TreeNode]) -> str: res = 0 stack = [(root, chr(root.val + ord('a')))] while stack: node, char = stack.pop() if not node.right and not node.left: if res == 0: res = char else: res = min(res, char) if node.right: stack.append((node.right, chr(node.right.val + ord('a')) + char )) if node.left: stack.append((node.left, chr(node.left.val + ord('a')) + char )) return res
smallest-string-starting-from-leaf
python simple dfs solution
byuns9334
0
35
smallest string starting from leaf
988
0.497
Medium
16,059
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/1556207/Easiest-Approach-oror-WELL-Explained-oror-O(n)
class Solution: def smallestFromLeaf(self, root: Optional[TreeNode]) -> str: res = "z"*27 def post(root,local): nonlocal res if root is None: return if root.left is None and root.right is None: res = min(res,(chr(97+root.val)+local)) return post(root.left,chr(97+root.val)+local) post(root.right,chr(97+root.val)+local) post(root,"") return res
smallest-string-starting-from-leaf
📌📌 Easiest Approach || WELL-Explained || O(n) 🐍
abhi9Rai
0
69
smallest string starting from leaf
988
0.497
Medium
16,060
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/1169983/Simplified-Recursive-DFS-using-Global-Var
class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: self.ans = "~" def dfs(root, s): if not root: return None if not root.right and not root.left: s = chr(97+root.val) + s #New if s < self.ans: self.ans = s s = chr(97+root.val) + s #New dfs(root.left, s) dfs(root.right,s) dfs(root, "") return self.ans
smallest-string-starting-from-leaf
Simplified Recursive DFS using Global Var
X00X
0
30
smallest string starting from leaf
988
0.497
Medium
16,061
https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/324003/Python-DFS
class Solution: stack = [] best = None def lexorder(s1,s2): if s1 == None: return s2 for i in range(min(len(s1),len(s2))): if s1[i] < s2[i]: return s1 elif s1[i] > s2[i]: return s2 if len(s1) < len(s2): return s1 return s2 def dfs(self, root): Solution.stack.append(root.val) if root.left: self.dfs(root.left) if root.right: self.dfs(root.right) if root.left == None and root.right == None: Solution.best = Solution.lexorder(Solution.best, Solution.stack[::-1]) Solution.stack.pop() def smallestFromLeaf(self, root: TreeNode) -> str: self.dfs(root) return "".join([chr(x+97) for x in Solution.best])
smallest-string-starting-from-leaf
Python DFS
alyshan
0
112
smallest string starting from leaf
988
0.497
Medium
16,062
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2037608/Python3-or-One-line-solution
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return list(str(int("".join([str(x) for x in num])) + k))
add-to-array-form-of-integer
Python3 | One line solution
manfrommoon
2
186
add to array form of integer
989
0.455
Easy
16,063
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1794862/Python3-or-hold-my-beer
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return [int(i) for i in str(int(''.join([str(i) for i in num]))+k)]
add-to-array-form-of-integer
Python3 | hold my beer
Anilchouhan181
2
158
add to array form of integer
989
0.455
Easy
16,064
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/501794/Python-one-liner-easy-to-understand.
class Solution: def addToArrayForm(self, A: List[int], K: int) -> List[int]: return list(str(int("".join([str(i) for i in A])) + K))
add-to-array-form-of-integer
Python one liner, easy to understand.
sudhirkumarshahu80
2
477
add to array form of integer
989
0.455
Easy
16,065
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2754867/Python3-Solution-oror-String-Integer-Conversion
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: s='' new = [] for i in num: s+=str(i) s = int(s) + k for i in str(s): new.append(int(i)) return(new)
add-to-array-form-of-integer
Python3 Solution || String-Integer Conversion
shashank_shashi
1
112
add to array form of integer
989
0.455
Easy
16,066
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2562650/Easy-Python-solution-or-time-and-space-O(n)
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: temp=0 for x in num: temp = (temp*10)+x temp+=k ans=[] while temp>0: rem=temp%10 ans.append(rem) temp=temp//10 #reverse the array without using reverse() method l=0 r=len(ans)-1 while l<r: ans[l],ans[r]=ans[r],ans[l] l+=1 r-=1 return ans
add-to-array-form-of-integer
Easy Python solution | time & space - O(n)
I_am_SOURAV
1
96
add to array form of integer
989
0.455
Easy
16,067
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1930260/O(N)-Solution-oror-Python-oror-Beats-94.66
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: a = "" for i in num: a += str(i) a = int(a) + k a = list(str(a)) return a
add-to-array-form-of-integer
✅O(N) Solution || Python || Beats 94.66%
Dev_Kesarwani
1
112
add to array form of integer
989
0.455
Easy
16,068
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1858653/Python-one-line-oror-Type-Casting
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return list(str(int("".join(str(n) for n in num)) + int(str(k))))
add-to-array-form-of-integer
Python one line || Type-Casting
airksh
1
36
add to array form of integer
989
0.455
Easy
16,069
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1234331/python3-Easy-to-understand-and-natural-solution-with-comments
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: ans=[] # to store final result # to make the given num a string string_num='' for i in num: string_num=string_num+str(i) # perform sum and append the result in the list for j in str(int(string_num)+k): ans.append(int(j)) return ans # returns list containing the final answer
add-to-array-form-of-integer
[python3] Easy to understand and natural solution with comments
nandanabhishek
1
67
add to array form of integer
989
0.455
Easy
16,070
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/947707/Python-one-liner
class Solution: def addToArrayForm(self, A: List[int], K: int) -> List[int]: return list(str(int(''.join(map(str,A)))+K))
add-to-array-form-of-integer
Python one-liner
lokeshsenthilkumar
1
197
add to array form of integer
989
0.455
Easy
16,071
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2842322/python-very-easy-solution-Beats-91.55-Memory-14.6-MB-Beats-89.20
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: x = ''; for i in num: x+=str(i); return list(str(int(x)+k))
add-to-array-form-of-integer
python very easy solution Beats 91.55% Memory 14.6 MB Beats 89.20%
seifsoliman
0
3
add to array form of integer
989
0.455
Easy
16,072
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2824340/Python-Solution
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: s="" for i in num: s=s+str(i) return list(str(int(s)+k))
add-to-array-form-of-integer
Python Solution
CEOSRICHARAN
0
1
add to array form of integer
989
0.455
Easy
16,073
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2821967/Simple-One-Line-Python
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return [int(x) for x in list(str(int(''.join(map(str,num)))+k))]
add-to-array-form-of-integer
Simple One Line Python
Jlonerawesome
0
2
add to array form of integer
989
0.455
Easy
16,074
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2816506/Python-Concise-Solution
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: # List[str] str_num = [str(number) for number in num] # + k result = str(int(''.join(str_num)) + k) # List[int] return [int(number) for number in result]
add-to-array-form-of-integer
Python Concise Solution
namashin
0
2
add to array form of integer
989
0.455
Easy
16,075
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2815521/Best-Python3-Solution-Faster-than-95-and-80-less-memory
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: num = ''.join(map(str, num)) # make string from list res = int(num) + k return [int(i) for i in str(res)]
add-to-array-form-of-integer
Best Python3 Solution Faster than 95% and 80% less memory
n555s77
0
2
add to array form of integer
989
0.455
Easy
16,076
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2813503/Add-to-Array-Form-of-Integer-%3A-100-working
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: num = int("".join(map(str,num))) + k num = [int(x) for x in str(num)] return num
add-to-array-form-of-integer
Add to Array-Form of Integer : 100% working
NIKHILTEJA
0
3
add to array form of integer
989
0.455
Easy
16,077
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2786656/Python3-Easy-to-Understand-Solution-greater-Conversion-String-Integer
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: arr_num = '' res = [] for i in num: # Iterate through array # Add digits in form of string (1 + 2 + 3 --> 123) arr_num += str(i) arr_num = int(arr_num) + k # Convert to integer and add k for j in str(arr_num): # Iterate through number in form of str # Convert digits to integers and add them to result array res.append(int(j)) return res
add-to-array-form-of-integer
✅Python3 Easy to Understand Solution --> Conversion String-Integer
radojicic23
0
2
add to array form of integer
989
0.455
Easy
16,078
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2732372/Python-easy-solution
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: b=[] string=''.join(str(i) for i in num) a=int(string)+k for i in str(a): b.append(i) return b
add-to-array-form-of-integer
Python easy solution
Navaneeth7
0
3
add to array form of integer
989
0.455
Easy
16,079
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2718918/Python-or-Easy-solution
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: k = [int(char) for char in str(k)] to_add = max(len(num), len(k)) num = [0]*abs(len(num) - to_add) + num k = [0]*abs(len(k) - to_add) + k carry = 0 for i in range(len(num) - 1, -1, -1): pl = num[i] + k[i] + carry if pl > 9: num[i] = pl % 10 carry = 1 else: num[i] = pl carry = 0 if carry: num = [1] + num return num
add-to-array-form-of-integer
Python | Easy solution
LordVader1
0
6
add to array form of integer
989
0.455
Easy
16,080
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2691217/python-1-liner
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return [int(i) for i in str(int(''.join([str(_) for _ in num]))+k)]
add-to-array-form-of-integer
python 1 liner
ece2019065
0
1
add to array form of integer
989
0.455
Easy
16,081
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2691216/python-1-liner
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return [int(i) for i in str(int(''.join([str(_) for _ in num]))+k)]
add-to-array-form-of-integer
python 1 liner
ece2019065
0
1
add to array form of integer
989
0.455
Easy
16,082
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2667543/Python-One-Liner
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return [int(e) for e in str(int(''.join([str(e) for e in num])) + k)]
add-to-array-form-of-integer
Python One Liner
nazimks
0
2
add to array form of integer
989
0.455
Easy
16,083
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2492344/Python-or-Easy-Solution-or-One-liner
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return list(str(int("".join(map(str, num)))+k))
add-to-array-form-of-integer
Python | Easy Solution | One-liner
k0te1ch
0
31
add to array form of integer
989
0.455
Easy
16,084
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2395400/one-liner-python
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return list(str(int("".join(map(str,num)))+k))
add-to-array-form-of-integer
one-liner python
sunakshi132
0
66
add to array form of integer
989
0.455
Easy
16,085
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2393809/python
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: output = list() position = len(num) - 1 number = k while position >= 0 or number > 0: if(position >= 0): number += num[position] output.append(number % 10) number = number // 10 position -= 1 output.reverse() return output
add-to-array-form-of-integer
python
sojwal_
0
26
add to array form of integer
989
0.455
Easy
16,086
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2213552/Python-Solution
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: s=0 li=[] n=len(num)-1 for i in num: s+=i*(10**n) n=n-1 return([int(x) for x in str(s+k)])
add-to-array-form-of-integer
Python Solution
SakshiMore22
0
36
add to array form of integer
989
0.455
Easy
16,087
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2213552/Python-Solution
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: for i in range(len(num) - 1, -1, -1): k, num[i] = divmod(num[i] + k, 10) return ([int(i) for i in str(k)] + num if k else num)
add-to-array-form-of-integer
Python Solution
SakshiMore22
0
36
add to array form of integer
989
0.455
Easy
16,088
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2033732/One-Liner-Python-3
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return [int(x) for x in (str(int(''.join([str(x) for x in num])) + k))]
add-to-array-form-of-integer
One Liner Python 3
Yodawgz0
0
47
add to array form of integer
989
0.455
Easy
16,089
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1822936/Ez-sol-oror-Simple-approach-oror-2-sols
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: for i in range(len(num)-1, -1, -1): v=(num[i]+k)//10 num[i]=(num[i]+k)%10 k=v left_K=[] if k: for i in str(k): left_K.append(int(i)) return left_K+num else: return num ```. B. using str() and join() 1. Generate the number by looping through the list. 2. Add k to the generated number 3. Convert the sum obtained to string 4. Use join method to form a list of digits and return this list 5. The TC is O(n) and SC is O(n) It is little slower as compared to the above solution
add-to-array-form-of-integer
Ez sol || Simple approach || 2 sols
ashu_py22
0
35
add to array form of integer
989
0.455
Easy
16,090
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1803887/1-Line-Python-Solution-oror-60-Faster-oror-Memory-less-than-70
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return [int(x) for x in str(int(''.join([str(x) for x in num]))+k)]
add-to-array-form-of-integer
1-Line Python Solution || 60% Faster || Memory less than 70%
Taha-C
0
63
add to array form of integer
989
0.455
Easy
16,091
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1648614/Python-3-Solution-O(N)
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return list(map(int, str(int("".join(map(str, num))) + k)))
add-to-array-form-of-integer
Python 3 Solution [O(N)]
1nnOcent
0
82
add to array form of integer
989
0.455
Easy
16,092
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1648614/Python-3-Solution-O(N)
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: val, res = 0, [] for n in num: # Get the integer val = val * 10 + n val += k if not val: return [0] while val: # Append the final value to a list res.append(val % 10) val //= 10 return res[::-1]
add-to-array-form-of-integer
Python 3 Solution [O(N)]
1nnOcent
0
82
add to array form of integer
989
0.455
Easy
16,093
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1441381/Python3-3-Lines-No-Memory-Clever-Idea-Take-a-Look-at-it.
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: num = "".join([str(i) for i in num]) k += int(num) return [] + [int(i) for i in str(k)]
add-to-array-form-of-integer
Python3 3 Lines, No Memory, Clever Idea Take a Look at it.
Hejita
0
108
add to array form of integer
989
0.455
Easy
16,094
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1351793/Python-1-Line-Solution!
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return list(map(int, str(int(''.join(list(map(str, num)))) + k)))
add-to-array-form-of-integer
Python 1 Line Solution!
Kenzjk
0
108
add to array form of integer
989
0.455
Easy
16,095
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1252368/Easy-Python3-solution
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return list(str((int("".join(str(i) for i in num))+k))) or class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return list(str(int("".join(map(str, num)))+k))
add-to-array-form-of-integer
Easy Python3 solution
Sanyamx1x
0
112
add to array form of integer
989
0.455
Easy
16,096
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1244810/Python-or-Without-any-conversion
class Solution: def arrayToNum(self, num): number=0 for item in num: number = number*10 + item return number def numToArray(self, number): arr = [] i=10 rem = number%10 number = number//10 while(number>0): arr.insert(0, rem) rem = number%10 number = number//10 arr.insert(0, rem) return arr def addToArrayForm(self, num: List[int], k: int) -> List[int]: if num: number = self.arrayToNum(num) return self.numToArray(number+k)
add-to-array-form-of-integer
Python | Without any conversion
rksharma19896
0
59
add to array form of integer
989
0.455
Easy
16,097
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1242196/Python3-simple-solution-by-two-approaches
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return map(int, str(int(''.join(map(str, num))) + k))
add-to-array-form-of-integer
Python3 simple solution by two approaches
EklavyaJoshi
0
49
add to array form of integer
989
0.455
Easy
16,098
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1242196/Python3-simple-solution-by-two-approaches
class Solution: def addToArrayForm(self, num1: List[int], num2: int) -> List[int]: num2 = str(num2) x = 1 n1 = len(num1) n2 = len(num2) carry = 0 while x <= max(n1,n2): z = 0 if x <= n1: z += num1[n1-x] if x <= n2: z += int(num2[n2-x]) z += carry carry = z//10 if x <= n1: num1[n1-x] = z%10 else: num1.insert(0,z%10) x += 1 if carry: num1.insert(0,1) return num1
add-to-array-form-of-integer
Python3 simple solution by two approaches
EklavyaJoshi
0
49
add to array form of integer
989
0.455
Easy
16,099