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/form-array-by-concatenating-subarrays-of-another-array/discuss/1083204/Python3-Dynamic-Programming-solution
class Solution: def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool: grouplen = len(groups) numslen = len(nums) @lru_cache(None) def f(groupindex, innerindex, cont ,numsindex): if groupindex == grouplen: return True if numsindex == numslen: return False # we match ok = False if groups[groupindex][innerindex] == nums[numsindex]: if innerindex == len(groups[groupindex]) - 1: ok |= f(groupindex + 1, 0, 1 ,numsindex + 1) else: ok |= f(groupindex, innerindex + 1, 1 ,numsindex + 1) # we don't match ok |= f(groupindex, 0, 0 ,numsindex + 1) return ok return f(0,0,0,0)
form-array-by-concatenating-subarrays-of-another-array
[Python3] Dynamic Programming solution
Soumya_Saurav
1
86
form array by concatenating subarrays of another array
1,764
0.527
Medium
25,300
https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/discuss/2138654/Python-KMP-Solution
class Solution: def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool: pos = 0 for group in groups: pos = self.substring(nums, group, pos) if pos == -1: return False pos += len(group) return True # start: starting position of the next substring to check(they have to be in the same order) def substring(self, text, pattern, start): lps = self.get_lps(pattern) i, j = start, 0 while i < len(text): if text[i] == pattern[j]: i, j = i + 1, j + 1 else: if j == 0: i += 1 else: j = lps[j-1] if j == len(pattern): return i - len(pattern) return -1 def get_lps(self, s): lps = [0] * len(s) # first lps val will always be one prev_lps, i = 0, 1 while i < len(s): if s[i] == s[prev_lps]: lps[i] = prev_lps + 1 prev_lps, i = prev_lps + 1, i + 1 else: if prev_lps == 0: lps[i] = 0 i += 1 else: prev_lps = lps[prev_lps - 1] return lps
form-array-by-concatenating-subarrays-of-another-array
Python - KMP Solution
ErickMwazonga
0
45
form array by concatenating subarrays of another array
1,764
0.527
Medium
25,301
https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/discuss/1337913/One-pass-with-stack-95-speed
class Solution: def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool: len_groups = len(groups) idx_group = 0 len_group = len(groups[idx_group]) stack = [] for n in nums: stack.append(n) if (len(stack) >= len_group and stack[-len_group:] == groups[idx_group]): stack = [] idx_group += 1 if idx_group < len_groups: len_group = len(groups[idx_group]) else: return True return False
form-array-by-concatenating-subarrays-of-another-array
One pass with stack, 95% speed
EvgenySH
0
64
form array by concatenating subarrays of another array
1,764
0.527
Medium
25,302
https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/discuss/1074955/Python3-straightforward-solution
class Solution: def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool: groups_n = sum(len(group) for group in groups) nums_n = len(nums) if groups_n > nums_n: return False i = 0 for group in groups: n = len(group) while nums_n - i >= n: if nums[i:i+n] == group: break i += 1 if nums_n - i < n: return False else: i += n return True
form-array-by-concatenating-subarrays-of-another-array
[Python3] straightforward solution
hwsbjts
0
43
form array by concatenating subarrays of another array
1,764
0.527
Medium
25,303
https://leetcode.com/problems/map-of-highest-peak/discuss/1074561/Python3-bfs
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: m, n = len(isWater), len(isWater[0]) # dimensions queue = [(i, j) for i in range(m) for j in range(n) if isWater[i][j]] ht = 0 ans = [[0]*n for _ in range(m)] seen = set(queue) while queue: newq = [] for i, j in queue: ans[i][j] = ht for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in seen: newq.append((ii, jj)) seen.add((ii, jj)) queue = newq ht += 1 return ans
map-of-highest-peak
[Python3] bfs
ye15
7
349
map of highest peak
1,765
0.604
Medium
25,304
https://leetcode.com/problems/map-of-highest-peak/discuss/1074561/Python3-bfs
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: m, n = len(isWater), len(isWater[0]) # dimensions ans = [[-1]*n for _ in range(m)] queue = deque() for i in range(m): for j in range(n): if isWater[i][j]: queue.append((i, j)) ans[i][j] = 0 while queue: i, j = queue.popleft() for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and ans[ii][jj] == -1: ans[ii][jj] = 1 + ans[i][j] queue.append((ii, jj)) return ans
map-of-highest-peak
[Python3] bfs
ye15
7
349
map of highest peak
1,765
0.604
Medium
25,305
https://leetcode.com/problems/map-of-highest-peak/discuss/1442614/Python-3-or-Greedy-Multi-source-BFS-or-Explanation
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: arr = collections.deque() m, n = len(isWater), len(isWater[0]) for i in range(m): for j in range(n): if isWater[i][j] == 1: arr.append((0, i, j)) ans = [[-1] * n for _ in range(m)] while arr: val, x, y = arr.popleft() if ans[x][y] != -1: continue ans[x][y] = val for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: xx, yy = x+dx, y+dy if 0 <= xx < m and 0 <= yy < n and ans[xx][yy] == -1: arr.append((val+1, xx, yy)) return ans
map-of-highest-peak
Python 3 | Greedy, Multi-source BFS | Explanation
idontknoooo
6
264
map of highest peak
1,765
0.604
Medium
25,306
https://leetcode.com/problems/map-of-highest-peak/discuss/1503490/Greedy-oror-BFS-oror-Well-Explained
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: m,n = len(isWater),len(isWater[0]) q = collections.deque() dp = [[float('inf') for _ in range(n)] for _ in range(m)] for i in range(m): for j in range(n): if isWater[i][j]==1: dp[i][j] = 0 q.append([i,j,0]) while q: x,y,c = q.popleft() for i,j in [(-1,0),(1,0),(0,1),(0,-1)]: if 0<=x+i<m and 0<=y+j<n and dp[x+i][y+j]==float('inf'): dp[x+i][y+j] = c+1 q.append([x+i,y+j,c+1]) return dp
map-of-highest-peak
📌📌 Greedy || BFS || Well-Explained 🐍
abhi9Rai
4
151
map of highest peak
1,765
0.604
Medium
25,307
https://leetcode.com/problems/map-of-highest-peak/discuss/1338049/Find-surrounding-neighbors-layer-by-layer-88-speed
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: land = set() water = set() for r, row in enumerate(isWater): for c, v in enumerate(row): if v: water.add((r, c)) else: land.add((r, c)) height = 0 cells = water while cells: new_cells = set() for r, c in cells: isWater[r][c] = height for i, j in [(1, 0), (0, 1), (-1, 0), (0, -1)]: new_cell = (r + i, c + j) if new_cell in land: land.remove(new_cell) new_cells.add(new_cell) cells = new_cells height += 1 return isWater
map-of-highest-peak
Find surrounding neighbors layer by layer, 88% speed
EvgenySH
1
68
map of highest peak
1,765
0.604
Medium
25,308
https://leetcode.com/problems/map-of-highest-peak/discuss/2834433/python-super-easy-BFS-%2B-DP
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: dp = [[0 if isWater[i][j] else -1 for j in range(len(isWater[0]))] for i in range(len(isWater))] queue = [] for i in range(len(isWater)): for j in range(len(isWater[0])): if dp[i][j] == 0: queue.append((i, j)) while queue: i, j = queue.pop(0) for x in range(-1, 2): for y in range(-1, 2): if abs(x+y) == 1 and i + y >= 0 and i + y < len(isWater) and j + x >= 0 and j + x < len(isWater[0]) and dp[i+y][j+x] == -1: dp[i+y][j+x] = 1 + dp[i][j] queue.append((i+y, j+x)) return dp
map-of-highest-peak
python super easy BFS + DP
harrychen1995
0
1
map of highest peak
1,765
0.604
Medium
25,309
https://leetcode.com/problems/map-of-highest-peak/discuss/2009910/Python-easy-to-read-and-understand-or-bfs
class Solution: def highestPeak(self, isWater): m, n = len(isWater), len(isWater[0]) visited = set() q = [] for i in range(m): for j in range(n): if isWater[i][j] == 1: visited.add((i, j)) q.append((i, j)) isWater[i][j] = 0 while q: num = len(q) for i in range(num): x, y = q.pop(0) val = isWater[x][y] if x > 0 and (x - 1, y) not in visited: isWater[x - 1][y] = val + 1 visited.add((x - 1, y)) q.append((x - 1, y)) if y > 0 and (x, y - 1) not in visited: isWater[x][y - 1] = val + 1 visited.add((x, y - 1)) q.append((x, y - 1)) if x < m - 1 and (x + 1, y) not in visited: isWater[x + 1][y] = val + 1 visited.add((x + 1, y)) q.append((x + 1, y)) if y < n - 1 and (x, y + 1) not in visited: isWater[x][y + 1] = val + 1 visited.add((x, y + 1)) q.append((x, y + 1)) return isWater
map-of-highest-peak
Python easy to read and understand | bfs
sanial2001
0
52
map of highest peak
1,765
0.604
Medium
25,310
https://leetcode.com/problems/map-of-highest-peak/discuss/1955062/Python-BFS-oror-O(1)-Space-Complexity-oror-beats-97
class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: queue = deque() rows = len(isWater) cols = len(isWater[0]) for i in range(rows): for j in range(cols): if isWater[i][j] == 1: queue.append((i,j)) isWater[i][j] = 0 # set height of water as 0 else: isWater[i][j] = '$' # mark the land while queue: row, col = queue.popleft() for x, y in [(0,1),(1,0),(0,-1),(-1,0)]: nRow = row + x nCol = col + y if 0<=nRow<rows and 0<=nCol<cols and isWater[nRow][nCol] == '$': isWater[nRow][nCol] = isWater[row][col]+1 queue.append((nRow, nCol)) return isWater
map-of-highest-peak
Python BFS || O(1) Space Complexity || beats 97%
NamanGarg20
0
58
map of highest peak
1,765
0.604
Medium
25,311
https://leetcode.com/problems/tree-of-coprimes/discuss/1074565/Python3-dfs
class Solution: def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]: tree = {} # tree as adjacency list for u, v in edges: tree.setdefault(u, []).append(v) tree.setdefault(v, []).append(u) ans = [-1]*len(nums) path = {} # val -> list of position &amp; depth seen = {0} def fn(k, i): """Populate ans via dfs.""" ii = -1 for x in path: if gcd(nums[k], x) == 1: # coprime if path[x] and path[x][-1][1] > ii: ans[k] = path[x][-1][0] ii = path[x][-1][1] path.setdefault(nums[k], []).append((k, i)) for kk in tree.get(k, []): if kk not in seen: seen.add(kk) fn(kk, i+1) path[nums[k]].pop() fn(0, 0) return ans
tree-of-coprimes
[Python3] dfs
ye15
10
702
tree of coprimes
1,766
0.392
Hard
25,312
https://leetcode.com/problems/tree-of-coprimes/discuss/2373686/runtime%3A-100.00-faster-or-python3
class Solution: def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]: gcdset = [set() for i in range(51)] for i in range(1,51): for j in range(1,51): if math.gcd(i,j) == 1: gcdset[i].add(j) gcdset[j].add(i) graph = defaultdict(list) for v1, v2 in edges: graph[v1].append(v2) graph[v2].append(v1) ans = [-1]*len(nums) q = [[0, {}]] seen = set([0]) depth = 0 while q: temp = [] for node, ancestors in q: index_depth = (-1,-1) for anc in list(ancestors.keys()): if anc in gcdset[nums[node]]: index, d = ancestors[anc] if d > index_depth[1]: index_depth = (index,d) ans[node] = index_depth[0] copy = ancestors.copy() copy[nums[node]] = (node,depth) for child in graph[node]: if child not in seen: seen.add(child) temp.append([child, copy]) q = temp depth += 1 return ans
tree-of-coprimes
runtime: - 100.00% faster | python3
vimla_kushwaha
1
41
tree of coprimes
1,766
0.392
Hard
25,313
https://leetcode.com/problems/tree-of-coprimes/discuss/2373677/faster-than-100.00-or-easy-to-understand-or-python-solution
class Solution: def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]: gcdset = [set() for i in range(51)] for i in range(1,51): for j in range(1,51): if math.gcd(i,j) == 1: gcdset[i].add(j) gcdset[j].add(i) graph = defaultdict(list) for v1, v2 in edges: graph[v1].append(v2) graph[v2].append(v1) ans = [-1]*len(nums) q = [[0, {}]] seen = set([0]) depth = 0 while q: temp = [] for node, ancestors in q: index_depth = (-1,-1) for anc in list(ancestors.keys()): if anc in gcdset[nums[node]]: index, d = ancestors[anc] if d > index_depth[1]: index_depth = (index,d) ans[node] = index_depth[0] copy = ancestors.copy() copy[nums[node]] = (node,depth) for child in graph[node]: if child not in seen: seen.add(child) temp.append([child, copy]) q = temp depth += 1 return ans ''' **:)**
tree-of-coprimes
faster than 100.00% | easy to understand | python solution
vimla_kushwaha
1
43
tree of coprimes
1,766
0.392
Hard
25,314
https://leetcode.com/problems/merge-strings-alternately/discuss/1075531/Simple-Python-Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: res='' for i in range(min(len(word1),len(word2))): res += word1[i] + word2[i] return res + word1[i+1:] + word2[i+1:]
merge-strings-alternately
Simple Python Solution
lokeshsenthilkumar
36
2,500
merge strings alternately
1,768
0.761
Easy
25,315
https://leetcode.com/problems/merge-strings-alternately/discuss/1075470/Python3-zip_longest
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: ans = [] for x, y in zip_longest(word1, word2, fillvalue=""): ans.append(x) ans.append(y) return "".join(ans)
merge-strings-alternately
[Python3] zip_longest
ye15
7
300
merge strings alternately
1,768
0.761
Easy
25,316
https://leetcode.com/problems/merge-strings-alternately/discuss/1075470/Python3-zip_longest
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return "".join(x+y for x, y in zip_longest(word1, word2, fillvalue=""))
merge-strings-alternately
[Python3] zip_longest
ye15
7
300
merge strings alternately
1,768
0.761
Easy
25,317
https://leetcode.com/problems/merge-strings-alternately/discuss/1335393/Easy-Python-Solution-one-for-loop
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: s = "" n = max(len(word1), len(word2)) for i in range(n): if len(word1) > i: s += word1[i] if len(word2) > i: s += word2[i] return s
merge-strings-alternately
Easy Python Solution, one for loop
samirpaul1
6
309
merge strings alternately
1,768
0.761
Easy
25,318
https://leetcode.com/problems/merge-strings-alternately/discuss/1127421/Easy-Python-Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: minimum = min(len(word1),len(word2)) finalword="" count=0 #first combine words until they have same length for i in range(minimum): finalword = finalword +word1[i]+word2[i] count= count+1 #if word1 or word2 has unequal length if len(word1)>len(word2): finalword = finalword + word1[count:] elif len(word2) > len(word1): finalword = finalword + word2[count:] return(finalword)
merge-strings-alternately
Easy Python Solution
YashashriShiral
6
482
merge strings alternately
1,768
0.761
Easy
25,319
https://leetcode.com/problems/merge-strings-alternately/discuss/2080424/Easy-To-Understand-Solution-oror-Python
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: l1 = [char for char in word1] l2 = [char for char in word2] string = "" if len(l1) < len(l2): for i in range(len(l1)): string += l1[i] + l2[i] for i in range(len(l1) , len(l2)): string += l2[i] elif len(l1) > len(l2): string = "" for i in range(len(l2)): string += l1[i] + l2[i] for i in range(len(l2) , len(l1)): string += l1[i] else: string = "" for i in range(len(l2)): string += l1[i] + l2[i] return string
merge-strings-alternately
Easy To Understand Solution || Python
Shivam_Raj_Sharma
3
58
merge strings alternately
1,768
0.761
Easy
25,320
https://leetcode.com/problems/merge-strings-alternately/discuss/2408545/Python3-Merge-Strings-Alternately-w-comments
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: i = 0 output = "" # Loop through both strings until the end of one is reached while i < len(word1) and i < len(word2): output = output + word1[i] + word2[i] i+=1 # Add the remainder of the longer word (if there is one) if len(word1) < len(word2): output += word2[i:] if len(word1) > len(word2): output += word1[i:] return output
merge-strings-alternately
[Python3] Merge Strings Alternately w comments
connorthecrowe
2
73
merge strings alternately
1,768
0.761
Easy
25,321
https://leetcode.com/problems/merge-strings-alternately/discuss/1203241/Python-EASY-PEASY-Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: ans = "" i=0 while i<len(word1) and i<len(word2): ans+=word1[i]+word2[i] i+=1 if i<len(word1): ans+=word1[i:] if i<len(word2): ans+=word2[i:] return ans
merge-strings-alternately
Python EASY-PEASY Solution
iamkshitij77
2
197
merge strings alternately
1,768
0.761
Easy
25,322
https://leetcode.com/problems/merge-strings-alternately/discuss/2302772/Python3-One-line-solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return ''.join((a + b for a, b in zip_longest(word1, word2, fillvalue='')))
merge-strings-alternately
[Python3] One line solution
geka32
1
42
merge strings alternately
1,768
0.761
Easy
25,323
https://leetcode.com/problems/merge-strings-alternately/discuss/2266314/Python3-Runtime%3A-35ms-oror-Memory%3A-13.8mb-98.52
class Solution: # Runtime: 35ms || Memory: 13.8mb 98.52% # O(max(n, m)) || O(n), where n is the num of letters present in wordOne # where m is the num of letters present in wordTwo def mergeAlternately(self, wordOne: str, wordTwo: str) -> str: newString = [''] * (len(wordOne) + len(wordTwo)) left, right = 0, 0 indexOne, indexTwo = 0, 1 while left < len(wordOne) or right < len(wordTwo): if len(wordOne) > left: newString[indexOne] = wordOne[left] indexOne += 2 if right < len(wordTwo) else 1 left += 1 if len(wordTwo) > right: newString[indexTwo] = wordTwo[right] indexTwo += 2 if left < len(wordOne) else 1 right += 1 return ''.join(newString)
merge-strings-alternately
Python3 Runtime: 35ms || Memory: 13.8mb 98.52%
arshergon
1
36
merge strings alternately
1,768
0.761
Easy
25,324
https://leetcode.com/problems/merge-strings-alternately/discuss/2163666/Python-Simple-and-Easy-Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: l=min(len(word1),len(word2)) n=l i=0 word=[] while(l!=0): word.append(word1[i]+word2[i]) i=i+1 l=l-1 if len(word1)<len(word2): word+=word2[n:] else: word+=word1[n:] return "".join(word)
merge-strings-alternately
Python Simple and Easy Solution
pruthashouche
1
14
merge strings alternately
1,768
0.761
Easy
25,325
https://leetcode.com/problems/merge-strings-alternately/discuss/2137165/Three-approaches-to-solve-this-problem
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: s = '' for i in range(min(len(word1), len(word2))): s += word1[i] + word2[i] return s + word1[i+1:] + word2[i+1:]
merge-strings-alternately
Three approaches to solve this problem
writemeom
1
52
merge strings alternately
1,768
0.761
Easy
25,326
https://leetcode.com/problems/merge-strings-alternately/discuss/2137165/Three-approaches-to-solve-this-problem
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: s = '' ptr1, ptr2 = 0, 0 while ptr1 < len(word1) or ptr2 < len(word2): if ptr1 < len(word1): s += word1[ptr1] ptr1 += 1 if ptr2 < len(word2): s += word2[ptr2] ptr2 += 1 return s
merge-strings-alternately
Three approaches to solve this problem
writemeom
1
52
merge strings alternately
1,768
0.761
Easy
25,327
https://leetcode.com/problems/merge-strings-alternately/discuss/2137165/Three-approaches-to-solve-this-problem
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return ''.join(a+b for a, b in zip_longest(word1, word2, fillvalue=''))
merge-strings-alternately
Three approaches to solve this problem
writemeom
1
52
merge strings alternately
1,768
0.761
Easy
25,328
https://leetcode.com/problems/merge-strings-alternately/discuss/2089069/Python-Easy-solution-with-complexities
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: i=0 j=0 len1 = len (word1) len2 = len (word2) string = "" while (i < len1 or j < len2 ): if (i < len1) : string = string + word1[i] i=i+1 if (j < len2 ) : string = string + word2[j] j=j+1 return string # time O(n+m) # space O(n+m)
merge-strings-alternately
[Python] Easy solution with complexities
mananiac
1
40
merge strings alternately
1,768
0.761
Easy
25,329
https://leetcode.com/problems/merge-strings-alternately/discuss/1903353/Python-easy-to-understand-with-comments.
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: out = '' i = 0 while i < len(word1) and i < len(word2): # run loop till the small word length. out += word1[i] out += word2[i] i += 1 out += word1[i:] # add the remaining length if left out += word2[i:] #check for both words return out
merge-strings-alternately
Python easy to understand with comments.
harishthakur4455
1
55
merge strings alternately
1,768
0.761
Easy
25,330
https://leetcode.com/problems/merge-strings-alternately/discuss/1686715/Python3-Solution-With-Iterator
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: iter1, iter2 = iter(word1), iter(word2) res = '' a, b = next(iter1, ''), next(iter2, '') while a or b: res += a + b a, b = next(iter1, ''), next(iter2, '') return res
merge-strings-alternately
Python3 Solution With Iterator
atiq1589
1
67
merge strings alternately
1,768
0.761
Easy
25,331
https://leetcode.com/problems/merge-strings-alternately/discuss/1104958/Python3-faster-100-and-less-memory-100
class Solution(object): def mergeAlternately(self, word1, word2): ran = min(len(word1), len(word2)) string = "" for i in range(ran): string += word1[i] + word2[i] string += word1[ran:] + word2[ran:] return string
merge-strings-alternately
Python3, faster 100% and less memory 100%
CODPUD
1
98
merge strings alternately
1,768
0.761
Easy
25,332
https://leetcode.com/problems/merge-strings-alternately/discuss/2833727/Python-solution-94-faster-using-zip
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: min_len = min(len(word1), len(word2)) if len(word1) == min_len: max_len_word = word2 else: max_len_word = word1 li = [] for i, j in zip(word1, word2): li.append(i) li.append(j) return "".join(li) + max_len_word[min_len::]
merge-strings-alternately
Python solution 94% faster using zip
samanehghafouri
0
1
merge strings alternately
1,768
0.761
Easy
25,333
https://leetcode.com/problems/merge-strings-alternately/discuss/2821337/Simple-linear-solution-in-Python-with-10-lines.-Only-today-for-free-%3A-)
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: """ Solution #1: Linear. Iterate over each string while one of the string not finish. Check each string and add last part of the string to the result string. Runtime: O(N), where N is the size of the smalest string. """ i = 0 result = "" while i < len(word1) and i < len(word2): result = f"{result}{word1[i]}{word2[i]}" i += 1 if i < len(word1): result = f"{result}{word1[i:]}" if i < len(word2): result = f"{result}{word2[i:]}" return result
merge-strings-alternately
Simple linear solution in Python with 10 lines. Only today for free :-)
denisOgr
0
1
merge strings alternately
1,768
0.761
Easy
25,334
https://leetcode.com/problems/merge-strings-alternately/discuss/2818527/Python-or-Simple-Solution-or-Merge-Sort-way
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: len_a = len(word1)-1 len_b = len(word2)-1 i = 0 j = 0 aux = "" while i <= len_a and j <= len_b: if i <= j: aux += word1[i] i += 1 else: aux += word2[j] j += 1 while i <= len_a: aux += word1[i] i += 1 while j <= len_b: aux += word2[j] j += 1 return aux
merge-strings-alternately
Python | Simple Solution | Merge Sort way
ajay_gc
0
1
merge strings alternately
1,768
0.761
Easy
25,335
https://leetcode.com/problems/merge-strings-alternately/discuss/2807523/Merge-String-Alternately-or-Python-Easy-Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: mword = '' n = min(len(word1),len(word2)) for i in range(n): mword += word1[i] +word2[i] return mword + word1[n:] + word2[n:]
merge-strings-alternately
Merge String Alternately | Python Easy Solution
jashii96
0
2
merge strings alternately
1,768
0.761
Easy
25,336
https://leetcode.com/problems/merge-strings-alternately/discuss/2788202/Simple-Python3-Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: output = '' for i in range(max(len(word1), len(word2))): if i < len(word1): output += word1[i] if i < len(word2): output += word2[i] return output
merge-strings-alternately
Simple Python3 Solution
vivekrajyaguru
0
1
merge strings alternately
1,768
0.761
Easy
25,337
https://leetcode.com/problems/merge-strings-alternately/discuss/2784583/Python-one-liner-run-91-memory-96-zip_longest
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: temp = list() for a,b in zip_longest(word1,word2, fillvalue=''): temp.append(a) temp.append(b) return ''.join(temp)
merge-strings-alternately
[Python] one-liner, run 91%, memory 96%, zip_longest
srebrny
0
6
merge strings alternately
1,768
0.761
Easy
25,338
https://leetcode.com/problems/merge-strings-alternately/discuss/2784583/Python-one-liner-run-91-memory-96-zip_longest
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return ''.join(list(a + b for a,b in zip_longest(word1,word2,fillvalue='')))
merge-strings-alternately
[Python] one-liner, run 91%, memory 96%, zip_longest
srebrny
0
6
merge strings alternately
1,768
0.761
Easy
25,339
https://leetcode.com/problems/merge-strings-alternately/discuss/2693398/Python-Easy-solution.-It's-as-efficient-as-other-solutions.
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: l=0 res="" while(l<len(word1) and l<len(word2)): res+=word1[l]+word2[l] l+=1 return res+word1[l:]+word2[l:]
merge-strings-alternately
Python Easy solution. It's as efficient as other solutions.
Navaneeth7
0
5
merge strings alternately
1,768
0.761
Easy
25,340
https://leetcode.com/problems/merge-strings-alternately/discuss/2685648/Python-or-Simple-solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: i, j = 0, 0 ans = [] while i < len(word1) and j < len(word2): ans.append(word1[i]) ans.append(word2[j]) i += 1 j += 1 for k in range(i, len(word1)): ans.append(word1[k]) for k in range(j, len(word2)): ans.append(word2[k]) return "".join(k for k in ans)
merge-strings-alternately
Python | Simple solution
LordVader1
0
12
merge strings alternately
1,768
0.761
Easy
25,341
https://leetcode.com/problems/merge-strings-alternately/discuss/2631759/Python-basic-solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: ans="" for i in range(min(len(word1),len(word2))): ans+=word1[i]+word2[i] return ans+word1[min(len(word1),len(word2)):]+word2[min(len(word1),len(word2)):]
merge-strings-alternately
Python basic solution
beingab329
0
3
merge strings alternately
1,768
0.761
Easy
25,342
https://leetcode.com/problems/merge-strings-alternately/discuss/2629479/Merge-Strings-Alternately-oror-Python3-Solution-oror-Easy
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: ans=[] i=0 j=0 word2=list(word2) word1=list(word1) while i<len(word1) and j<len(word2): word1.insert(i+1,word2[j]) i+=2 word2.pop(j) if word2: word1.extend(word2) return ''.join(word1)
merge-strings-alternately
Merge Strings Alternately || Python3 Solution || Easy
shagun_pandey
0
4
merge strings alternately
1,768
0.761
Easy
25,343
https://leetcode.com/problems/merge-strings-alternately/discuss/2626851/Python-Two-Pointers-(Straight-Forward-Solution)-Time-Complexity-O(n)
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: l1=list(word1) l2=list(word2) i,j=0,0 while i<len(l1) and j<len(l2): l1.insert(i+1,l2[j]) l2.remove(l2[j]) i+=2 if len(l2)!=0: l1.extend(l2) return "".join(l1)
merge-strings-alternately
Python- Two Pointers (Straight Forward Solution) [Time Complexity- O(n)]
utsa_gupta
0
8
merge strings alternately
1,768
0.761
Easy
25,344
https://leetcode.com/problems/merge-strings-alternately/discuss/2593239/Python-Solution-or-Two-Ways-Naive-and-One-Liner-or-Both-itertools.zip_longest-Based
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: combined = list(itertools.zip_longest(word1,word2)) ans = '' for char1, char2 in combined: ans += (w1[:] if w1 else '') + (w2[:] if w2 else '') return ans def mergeAlternately(self, word1: str, word2: str) -> str: return ''.join(char1 + char2 for char1, char2 in itertools.zip_longest(word1,word2,fillvalue=''))
merge-strings-alternately
Python Solution | Two Ways - Naive and One Liner | Both itertools.zip_longest Based
Gautam_ProMax
0
30
merge strings alternately
1,768
0.761
Easy
25,345
https://leetcode.com/problems/merge-strings-alternately/discuss/2573613/Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: s = "" if len(word1) < len(word2): for i in range(len(word1)): s += word1[i] s += word2[i] s += word2[i+1:] else: for i in range(len(word2)): s += word1[i] s += word2[i] s += word1[i+1:] return s
merge-strings-alternately
Solution
fiqbal997
0
9
merge strings alternately
1,768
0.761
Easy
25,346
https://leetcode.com/problems/merge-strings-alternately/discuss/2524411/PYTHON-Simple-Clean-approach-beat-95-Easy-T%3A-O(max(NM))
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: p1=0 l1,l2 = len(word1), len(word2) res = "" while p1<l1 and p1<l2: res+= word1[p1] res+= word2[p1] p1+=1 while p1<l1: res+=word1[p1] p1+=1 while p1<l2: res+=word2[p1] p1+=1 return res
merge-strings-alternately
✅ [PYTHON] Simple, Clean approach beat 95% Easy T: O(max(N,M))
girraj_14581
0
26
merge strings alternately
1,768
0.761
Easy
25,347
https://leetcode.com/problems/merge-strings-alternately/discuss/2515134/Python-simple-two-pointer-sol
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: i = 0 j = 0 result = "" while i < len(word1) and j < len(word2): result += word1[i] + word2[j] i += 1 j += 1 if len(word1) > len(word2): while i < len(word1): result += word1[i] i += 1 else: while j < len(word2): result += word2[j] j += 1 return result
merge-strings-alternately
Python simple two pointer sol
aruj900
0
27
merge strings alternately
1,768
0.761
Easy
25,348
https://leetcode.com/problems/merge-strings-alternately/discuss/2427404/Python-simple-solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: w = list(word1) w2 = list(word2) res = "" i, j = 0, 0 n, m = len(w) - 1, len(w2) - 1 while i <= n and j <= m: res += w[i] + w2[j] i += 1 j += 1 while i <= n: res += w[i] i += 1 while j <= m: res += w2[j] j += 1 return res
merge-strings-alternately
Python simple solution
ankurbhambri
0
23
merge strings alternately
1,768
0.761
Easy
25,349
https://leetcode.com/problems/merge-strings-alternately/discuss/2405783/Simple-and-straighforward-Solution
class Solution: def mergeAlternately(self, w1: str, w2: str) -> str: def mer(s1,s2,j): re="" a1=len(s1) a2=len(s2) x=0 y=0 while y<a2: if j==1: re=re+s1[x] x+=1 j=0 else: re=re+s2[y] y+=1 j=1 re=re+s1[x:] return re n1=len(w1) n2=len(w2) if n1>n2: r= mer(w1,w2,1) else: r= mer(w2,w1,0) return r
merge-strings-alternately
Simple and straighforward Solution
godemode12
0
11
merge strings alternately
1,768
0.761
Easy
25,350
https://leetcode.com/problems/merge-strings-alternately/discuss/2250349/Python%3A-Simplest-Solution-(Faster-then-96)
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: res = "" for i in range(min(len(word1),len(word2))): res += word1[i]+word2[i] return res+word1[i+1:]+word2[i+1:]
merge-strings-alternately
Python: Simplest Solution (Faster then 96%)
ajaykr2811
0
34
merge strings alternately
1,768
0.761
Easy
25,351
https://leetcode.com/problems/merge-strings-alternately/discuss/2243621/Python3-two-pointers-solution-O(n)-time
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: length1, length2 = len(word1), len(word2) resultLength = min(length1, length2) *2 i, iterator1, iterator2, result = 0, 0, 0, "" while i < resultLength: if i%2 == 0: result+=word1[iterator1] iterator1+=1 else: result+=word2[iterator2] iterator2+=1 i+=1 while iterator1 < length1: result+=word1[iterator1] iterator1+=1 while iterator2 < length2: result+=word2[iterator2] iterator2+=1 return result
merge-strings-alternately
📌 Python3 two pointers solution O(n) time
Dark_wolf_jss
0
11
merge strings alternately
1,768
0.761
Easy
25,352
https://leetcode.com/problems/merge-strings-alternately/discuss/2194708/Python-Simple-Python-Solution-By-Adding-Alternate-Elements
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: result = '' i , j = 0 , 0 while i < len(word1) and j < len(word2): result = result + word1[i] + word2[j] i = i + 1 j = j + 1 while i < len(word1): result = result + word1[i] i = i + 1 while j < len(word2): result = result + word2[j] j = j + 1 return result
merge-strings-alternately
[ Python ] ✅✔ Simple Python Solution By Adding Alternate Elements 🔥✌
ASHOK_KUMAR_MEGHVANSHI
0
48
merge strings alternately
1,768
0.761
Easy
25,353
https://leetcode.com/problems/merge-strings-alternately/discuss/2190890/Python3-solution-oror-Better-than-90-in-runtime
'''class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: lst=[] l1=len(word1) l2=len(word2) if l1<l2: for i in range(0,l1): lst.append(word1[i]) lst.append(word2[i]) lst.append(word2[l1:]) elif l2<l1: for i in range(0,l2): lst.append(word1[i]) lst.append(word2[i]) lst.append(word1[l2:]) else: for i in range(0,l2): lst.append(word1[i]) lst.append(word2[i]) s="".join(j for j in lst) return s print(mergeAlternately(word1,word2))'''
merge-strings-alternately
Python3 solution || Better than 90% in runtime
keertika27
0
17
merge strings alternately
1,768
0.761
Easy
25,354
https://leetcode.com/problems/merge-strings-alternately/discuss/2169620/Python-simple-solution
class Solution: def mergeAlternately(self, w1: str, w2: str) -> str: ans = '' for i in range(max([len(w1), len(w2)])): if i < len(w1): ans += w1[i] if i < len(w2): ans += w2[i] return ans
merge-strings-alternately
Python simple solution
StikS32
0
44
merge strings alternately
1,768
0.761
Easy
25,355
https://leetcode.com/problems/merge-strings-alternately/discuss/2089342/Solution-in-Python
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: w = '' for c1, c2 in zip(word1, word2): w += c1+c2 n1, n2 = len(word1), len(word2) if n1 == n2: return w elif n1 > n2: return w + word1[n2: n2+(n1-n2)] else: return w + word2[n1: n1+(n2-n1)]
merge-strings-alternately
Solution in Python
pe-mn
0
19
merge strings alternately
1,768
0.761
Easy
25,356
https://leetcode.com/problems/merge-strings-alternately/discuss/2037085/Python-Queue-Clean-and-Simple!
class Solution: def mergeAlternately(self, word1, word2): q1, q2, ans = deque(word1), deque(word2), list() while q1 or q2: if q1: ans.append(q1.popleft()) if q2: ans.append(q2.popleft()) return "".join(ans)
merge-strings-alternately
Python - Queue - Clean and Simple!
domthedeveloper
0
35
merge strings alternately
1,768
0.761
Easy
25,357
https://leetcode.com/problems/merge-strings-alternately/discuss/1917074/Easy-Python-solution-with-zip()-and-max()-functions
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: ans = '' for char in zip(word1, word2): ans += char[0]+char[1] if len(word1) != len(word2): m = max(word1, word2, key=len) # m - the longest word from word1 and word2 ans += m[len(ans)//2:] return ans
merge-strings-alternately
Easy Python solution with zip() and max() functions
dashaternovskaya
0
44
merge strings alternately
1,768
0.761
Easy
25,358
https://leetcode.com/problems/merge-strings-alternately/discuss/1910506/Python-Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return reduce(lambda x, y: x + y[0] + y[1], itertools.zip_longest(word1, word2, fillvalue=''), '')
merge-strings-alternately
Python Solution
hgalytoby
0
55
merge strings alternately
1,768
0.761
Easy
25,359
https://leetcode.com/problems/merge-strings-alternately/discuss/1910506/Python-Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return ''.join(x + y for x, y in itertools.zip_longest(word1, word2, fillvalue=''))
merge-strings-alternately
Python Solution
hgalytoby
0
55
merge strings alternately
1,768
0.761
Easy
25,360
https://leetcode.com/problems/merge-strings-alternately/discuss/1854433/Python-easy-solution-faster-than-95
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: res = "" if len(word1) == len(word2): for i in range(len(word1)): res = res + word1[i] + word2[i] elif len(word1) < len(word2): for i in range(len(word1)): res = res + word1[i] + word2[i] res = res + word2[len(word1):] else: for i in range(len(word2)): res = res + word1[i] + word2[i] res = res + word1[len(word2):] return res
merge-strings-alternately
Python easy solution, faster than 95%
alishak1999
0
38
merge strings alternately
1,768
0.761
Easy
25,361
https://leetcode.com/problems/merge-strings-alternately/discuss/1655598/Easy-and-Readable-Python-Code
class Solution(object): def mergeAlternately(self, word1, word2): """ :type word1: str :type word2: str :rtype: str """ # edge cases - if word1 is None: return word2 if word2 is None: return word1 if word1 is None and word2 is None: return "" else: strr = "" l1 = len(word1) l2 = len(word2) for (i,j) in zip(range(l1), range(l2)): strr +=word1[i] strr +=word2[j] if i!=l1-1: strr += word1[i+1:] if j!=l2-1: strr += word2[j+1:] #print(strr) return strr
merge-strings-alternately
Easy and Readable Python Code
pandeylalit9
0
54
merge strings alternately
1,768
0.761
Easy
25,362
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1075895/Easy-Python-beats-100-time-and-space
class Solution: def minOperations(self, boxes: str) -> List[int]: ans = [0]*len(boxes) leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes) for i in range(1, n): if boxes[i-1] == '1': leftCount += 1 leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left ans[i] = leftCost for i in range(n-2, -1, -1): if boxes[i+1] == '1': rightCount += 1 rightCost += rightCount ans[i] += rightCost return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
Easy Python beats 100% time and space
trungnguyen276
126
6,000
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,363
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1614367/Python-O(n)-solution-easy-to-understand
class Solution: def minOperations(self, boxes: str) -> List[int]: l = len(boxes) ans = [0] * l before = 0 after = 0 num = 0 for i in range(l): if boxes[i] == "1": after += 1 num += i for i in range(l): ans[i] = num if boxes[i] == "1": before += 1 after -= 1 num += before - after return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
Python O(n) solution, easy to understand
PoHandsome
7
428
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,364
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1510448/96-faster-oror-Greedy-Approach-oror-Well-Explained-oror-For-Beginners
class Solution: def minOperations(self, boxes: str) -> List[int]: n = len(boxes) boxes = [int(i) for i in boxes] pre = [[0,0] for i in range(n)] post= [[0,0] for i in range(n)] for i in range(1,n): pre[i][0] = boxes[i-1] + pre[i-1][0] pre[i][1] = boxes[i-1] + pre[i-1][0] + pre[i-1][1] for i in range(n-2,-1,-1): post[i][0] = boxes[i+1] + post[i+1][0] post[i][1] = boxes[i+1] + post[i+1][0] + post[i+1][1] for i in range(n): boxes[i] = pre[i][1]+post[i][1] return boxes
minimum-number-of-operations-to-move-all-balls-to-each-box
📌📌 96% faster || Greedy Approach || Well-Explained || For-Beginners 🐍
abhi9Rai
7
401
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,365
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1172589/Python3-Brute-Force-Solution
class Solution: def minOperations(self, boxes: str) -> List[int]: arr = [] for i in range(len(boxes)): sumi = 0 for j in range(len(boxes)): if(boxes[j] == '1'): sumi += abs(j - i) arr.append(sumi) return arr
minimum-number-of-operations-to-move-all-balls-to-each-box
[Python3] Brute Force Solution
VoidCupboard
7
303
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,366
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1101094/Python-or-O(N)-or-DP-or-Time-beats-100-or-space-beats-100
class Solution: def minOperations(self, boxes: str) -> List[int]: n = len(boxes) dpleft, dpright = [0]*n, [0]*n countleft, countright = int(boxes[0]), int(boxes[-1]) ans = [0]*n for i in range(1, n): dpleft[i] = dpleft[i-1] + countleft if boxes[i] == '1': countleft += 1 for i in range(n-2, -1, -1): dpright[i] = dpright[i+1] + countright if boxes[i] == '1': countright += 1 for i in range(len(boxes)): ans[i] = dpleft[i]+dpright[i] return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
Python | O(N) | DP | Time beats 100% | space beats 100%
anuraggupta29
7
643
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,367
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1075585/Simple-Python-Solution
class Solution: def minOperations(self, boxes: str) -> List[int]: l=[] for i in range(len(boxes)): k=0 for j in range(len(boxes)): if boxes[j]=='1': k+=abs(i-j) l.append(k) return l
minimum-number-of-operations-to-move-all-balls-to-each-box
Simple Python Solution
lokeshsenthilkumar
6
468
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,368
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1075681/Python3-line-sweep
class Solution: def minOperations(self, boxes: str) -> List[int]: ans = [] ops = cnt = 0 # count of remaining "1"s for i, x in enumerate(boxes): if x == "1": ops += i cnt += 1 for i, x in enumerate(boxes): ans.append(ops) if x == "1": cnt -= 2 ops -= cnt return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
[Python3] line sweep
ye15
4
356
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,369
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1226993/python-easiest-oror-two-solution-brute-force-%2B-efficient-one(beats-99.24-solution)oror
class Solution: def minOperations(self, boxes: str) -> List[int]: n=len(boxes) ans=[] for i in range(n): p=0 for j in range(n): if boxes[j]=='1': p+= abs(i-j) ans.append(p) return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
python easiest || two solution brute force + efficient one(beats 99.24% solution)||
chikushen99
3
233
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,370
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1226993/python-easiest-oror-two-solution-brute-force-%2B-efficient-one(beats-99.24-solution)oror
class Solution: def minOperations(self, boxes: str) -> List[int]: n=len(boxes) ans=[] right=0 left = 0 p=0 for i in range(n): if boxes[i]=='1': left+=1 p+=i ans.append(p) if boxes[0]=='1': left-=1 right+=1 for j in range(1,n): if boxes[j]=='0': ans.append(ans[-1]-left+right) else: ans.append(ans[-1]-left+right) left-=1 right+=1 return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
python easiest || two solution brute force + efficient one(beats 99.24% solution)||
chikushen99
3
233
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,371
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2697071/Simple-Python3-Solution
class Solution: def minOperations(self, boxes: str) -> List[int]: arr = [] for i, balls in enumerate(boxes): if balls == '1': arr.append(i) res = [] for i in range(len(boxes)): tmp = 0 for index in arr: tmp += abs(i - index) res.append(tmp) return res
minimum-number-of-operations-to-move-all-balls-to-each-box
Simple Python3 Solution
mediocre-coder
2
144
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,372
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1367760/Python-solution-O(n)
class Solution: def minOperations(self, boxes: str) -> List[int]: n = len(boxes) left_side = [0]*n right_side = [0]*n left_count, right_count = int(boxes[0]), int(boxes[n-1]) for i in range(1, n): left_side[i] = left_count + left_side[i-1] if boxes[i] == '1': left_count += 1 for i in range(n-2, -1, -1): right_side[i] = right_side[i+1] + right_count if boxes[i] == '1': right_count += 1 return [left + right for left, right in zip(left_side, right_side)]
minimum-number-of-operations-to-move-all-balls-to-each-box
Python solution O(n)
peatear-anthony
1
311
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,373
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1250009/Intuitive-Python-Brute-Force-O(n2)
class Solution: def minOperations(self, boxes: str) -> List[int]: minMoves = [] for i in range(len(boxes)): moves = 0 for j in range(0, i): if boxes[j] == "1": moves += abs(i-j) for j in range(len(boxes) - 1, i, -1): if boxes[j] == "1": moves += abs(i-j) minMoves.append(moves) return minMoves
minimum-number-of-operations-to-move-all-balls-to-each-box
Intuitive Python Brute Force O(n^2)
iPwnNOwn
1
150
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,374
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2812100/python-O(n)-one-pass-solution
class Solution: # think the code explains itself pretty much. basically I used # the idea of sweeping line. for each iteration, we need to add # additional steps for balls before the line, because we are # further away from those balls. and delete extra steps after # the sweeping line, because we are moving closer to the balls. def minOperations(self, b: str) -> List[int]: boxes = [0 if c == '0' else 1 for c in b] onesBeforeLine, onesAfterLine = 0, sum(boxes[1:]) stepsBeforeLine, stepsAfterLine = 0, sum([i if b else 0 for i, b in enumerate(boxes)]) res = [stepsBeforeLine + stepsAfterLine] for line in range(1, len(boxes)): onesBeforeLine += boxes[line - 1] stepsBeforeLine += onesBeforeLine stepsAfterLine -= onesAfterLine onesAfterLine -= boxes[line] res.append(stepsBeforeLine + stepsAfterLine) return res
minimum-number-of-operations-to-move-all-balls-to-each-box
python O(n) one pass solution
tinmanSimon
0
2
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,375
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2663568/Python-3
class Solution: def minOperations(self, boxes: str) -> List[int]: valid = {1:[]} for i in range(len(boxes)): if boxes[i] == '1': valid[1].append(i) print(valid) result = [] for i in range(len(boxes)): ans = 0 for j in valid[1]: ans += abs(j-i) result.append(ans) return result
minimum-number-of-operations-to-move-all-balls-to-each-box
Python 3
Noisy47
0
12
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,376
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2661464/Python3-O(n)-From-Left-and-From-Right
class Solution: def minOperations(self, boxes: str) -> List[int]: b = [int(s) for s in boxes] fl = [(0 ,0) for i in range(len(b))] fr = [(0, 0) for i in range(len(b))] fl[0] = (0, b[0]) fr[-1] = (0, b[-1]) for i in range(1,len(b)): fl[i] = fl[i-1][0] + fl[i-1][1], fl[i-1][1] + b[i] for i in reversed(range(0,len(b)-1)): fr[i] = fr[i+1][0] + fr[i+1][1], fr[i+1][1] + b[i] ret = [fl[i][0] + fr[i][0] for i in range(len(b))] return ret
minimum-number-of-operations-to-move-all-balls-to-each-box
Python3 O(n) From Left and From Right
godshiva
0
4
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,377
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2635923/Getting-Time-limit-exceded-can-anyone-help-with-this-code
class Solution: def minOperations(self, boxes: str) -> List[int]: output=[None]*len(boxes) l=len(str(boxes)) for i in range(l): val=0 for a,j in enumerate(boxes): k=a-i if k<0: k=-k else: k=k val+=int(j)*k output[i]=val return output
minimum-number-of-operations-to-move-all-balls-to-each-box
Getting Time limit exceded can anyone help with this code
dnrkcharan
0
10
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,378
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2531417/Easy-Python-Solution-or-Prefix-and-Postfix
class Solution: def minOperations(self, boxes: str) -> List[int]: n = len(boxes) pre = [0]*n post = [0]*n numberOfOnes = (1 if boxes[0]=="1" else 0) for i in range(1,n): pre[i] += pre[i-1] + numberOfOnes if boxes[i]=="1": numberOfOnes+=1 numberOfOnes = (1 if boxes[n-1]=="1" else 0) for i in range(n-2,-1,-1): post[i] += post[i+1] + numberOfOnes if boxes[i]=="1": numberOfOnes+=1 ans = [] for i in range(n): ans.append(pre[i]+post[i]) return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
Easy Python Solution | Prefix and Postfix
coolakash10
0
29
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,379
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2524074/python-98
class Solution: def minOperations(self, boxes: str) -> List[int]: def calc_number_of_operations(boxes): answer = [0] * len(boxes) acc = step = 0 for idx, box in enumerate(boxes): acc += step answer[idx] = acc if box == "1": step += 1 return answer return [ sum(pair) for pair in zip(calc_number_of_operations(boxes), reversed(calc_number_of_operations(boxes[::-1]))) ]
minimum-number-of-operations-to-move-all-balls-to-each-box
python 98%
Potentis
0
22
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,380
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2488971/Python-Solution-easy-to-understand-solution-if-you-understood-the-question
class Solution: def minOperations(self, boxes: str) -> List[int]: s=0 c=0 j=0 for i in range(len(boxes)): if boxes[i]=='1': s+=(i-j) c+=1 ans=[] ans.append(s) a=0 if boxes[0]=='1': a+=1 c-=1 for i in range(1,len(boxes)): ans.append(ans[i-1]-c+a) if boxes[i]=='1': a+=1 c-=1 return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
Python Solution - easy to understand solution if you understood the question
T1n1_B0x1
0
50
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,381
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2405051/Easy-to-understand-Python-Solution-O(n)
class Solution(object): def minOperations(self, boxes): """ :type boxes: str :rtype: List[int] """ boxes = list(map(int,list(boxes))) left = [0]*len(boxes) right = [0]*len(boxes) counter = boxes[0] for l in range(1,len(boxes)): left[l] = left[l-1]+counter counter += boxes[l] counter = boxes[-1] for r in range(len(boxes)-2,-1,-1): right[r] = right[r+1]+counter counter += boxes[r] for r in range(len(right)): right[r] = right[r]+left[r] return right
minimum-number-of-operations-to-move-all-balls-to-each-box
Easy to understand Python Solution O(n)
freeform270
0
81
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,382
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2376404/Python3-or-simple-9-line-solution
class Solution: def minOperations(self, boxes: str) -> List[int]: n = len(boxes) result = [0] * n for idx, b in enumerate(boxes): if b == "1": for j in range(n): if j == idx: continue result[j] += abs(idx-j) return result
minimum-number-of-operations-to-move-all-balls-to-each-box
Python3 | simple 9-line solution
Ploypaphat
0
49
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,383
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2209052/Simple-Python-Solution
class Solution: def minOperations(self, boxes: str) -> List[int]: res = list() i = 0 while(i < len(boxes)): count = 0 for j in range(0, len(boxes)): if(boxes[j] == '1'): count = count+(abs(i-j)) res.append(count) i = i+1 return res
minimum-number-of-operations-to-move-all-balls-to-each-box
Simple Python Solution
kaus_rai
0
52
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,384
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2114272/python-two-solutions
class Solution: def minOperations(self, boxes: str) -> List[int]: # ans1 ans = [0]*len(boxes) leftCount,rightCount,leftCost,rightCost,n = 0,0,0,0,len(boxes) for i in range(1,n): if boxes[i-1] == "1": leftCount+=1 leftCost+=leftCount ans[i] = leftCost for i in range(n-2,-1,-1): if boxes[i+1] == "1": rightCount+=1 rightCost+=rightCount ans[i]+=rightCost return ans # ans2 arr = [] for i in range(len(boxes)): if boxes[i] == "1": arr.append(i) ans = [] for i in range(len(boxes)): sum = 0 for j in range(len(arr)): sum+=abs(i-arr[j]) ans.append(sum) return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
python two solutions
somendrashekhar2199
0
109
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,385
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/2028025/Python-easy-brute-force-solution
class Solution: def minOperations(self, boxes: str) -> List[int]: res = [0] * len(boxes) for i in range(len(boxes)): for j in range(len(boxes)): if boxes[j] == '1': res[i] += abs(j - i) return res
minimum-number-of-operations-to-move-all-balls-to-each-box
Python easy brute force solution
alishak1999
0
64
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,386
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1989738/Python-3-Easy-to-Understand-solution-But-not-much-optimized
class Solution: def minOperations(self, boxes: str) -> List[int]: balls = [ int(ball) for ball in boxes] boxes_having_balls = [ i for i in range(len(balls)) if balls[i] == 1] results = [] for i in range(len(balls)): result = 0 for box in boxes_having_balls: result = result + abs(i - box) results.append(result) return results
minimum-number-of-operations-to-move-all-balls-to-each-box
Python 3 Easy to Understand solution But not much optimized
hardik097
0
73
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,387
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1782373/Python-oror-Brute-Force-Solution
class Solution: def minOperations(self, boxes: str) -> List[int]: ans = [] for i in range(len(boxes)): count = 0 for j in range(len(boxes)): if boxes[j] == '1': count += abs(j-i) ans.append(count) return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
Python || Brute Force Solution
dos_77
0
69
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,388
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1772557/Minimum-Number-of-Operations-to-Move-All-Balls-to-Each-Box-Python-solution-brute-force
class Solution: def minOperations(self, boxes: str) -> List[int]: answer = [] boxe = list(boxes) for i in range(len(boxe)): count = 0 for j in range(len(boxe)): if i != j and boxe[j] == '1': count += abs(j - i) answer.append(count) return answer
minimum-number-of-operations-to-move-all-balls-to-each-box
Minimum Number of Operations to Move All Balls to Each Box Python solution brute force
seabreeze
0
99
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,389
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1752656/Not-so-optimal-but-One-liner-solution
class Solution: def minOperations(self, boxes: str) -> List[int]: return [sum([abs(j-i) for j in range(len(boxes)) if boxes[j]=="1" and i!=j]) for i in range(len(boxes))]
minimum-number-of-operations-to-move-all-balls-to-each-box
Not so optimal but One liner solution
blackmishra
0
74
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,390
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1739533/simple-python-solution
class Solution: def minOperations(self, boxes: str) -> List[int]: arr = [] #array to store indexes for i in range(len(boxes)): if boxes[i] == "1": arr.append(i) arr2 = [] for j in range(len(boxes)): var = 0 for k in arr: var += abs(k-j) arr2.append(var) return arr2
minimum-number-of-operations-to-move-all-balls-to-each-box
simple python solution
vijayvardhan6
0
106
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,391
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1646018/python-O(n)-sliding-window-with-explanation-87.75-in-time-91.26-in-space
class Solution: def minOperations(self, boxes: str) -> List[int]: #sliding window? ones = [] for i,j in enumerate(boxes): if j == '1': ones.append(i) left, right = 0, len(ones) ini, ini_val = 0, sum(ones) ans = [] while ini < len(boxes): if ini == 0: ans.append(ini_val) else: ini_val += left ini_val -= right ans.append(ini_val) if boxes[ini] == '1': left += 1 right -= 1 ini += 1 return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
python O(n) sliding window with explanation, 87.75% in time, 91.26% in space
752937603
0
156
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,392
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1365983/Python3-solution-with-comments
class Solution: def minOperations(self, boxes: str) -> List[int]: my_list = [] count = 0 pos_list = [] # making a list with every position of every 1 from boxes for i, number in enumerate(boxes): if int(number) == 1: pos_list.append(i) # calculating the first number of moves and adding it to the list for j, element in enumerate(boxes): if int(boxes[j]) == 1 and 0 != j: count += abs(0-j) my_list.append(count) count = 0 for i, elements in enumerate(boxes): # counting the other moves using the list of positions if i != 0: # without the first element of the list for j, pos in enumerate(pos_list): count += abs(pos_list[j] - 1) pos_list[j] -= 1 my_list.append(count) count = 0 return my_list
minimum-number-of-operations-to-move-all-balls-to-each-box
Python3 solution with comments
FlorinnC1
0
84
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,393
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1339575/Two-lines
class Solution: def minOperations(self, boxes: str) -> List[int]: balls = [i for i, b in enumerate(boxes) if b == "1"] return [sum(abs(i - b) for b in balls) for i in range(len(boxes))]
minimum-number-of-operations-to-move-all-balls-to-each-box
Two lines
EvgenySH
0
112
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,394
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1178275/python-sol
class Solution: def minOperations(self, boxes: str) -> List[int]: n=len(boxes) right=[0]*n left=[0]*n if boxes[-1]=="1": count=1 else: count=0 for i in range(n-2,-1,-1): right[i]=right[i+1]+count if boxes[i]=="1": count+=1 if boxes[0]=="1": count=1 else: count=0 ans=[] ans.append(left[0]+right[0]) for i in range(1,n): left[i]=left[i-1]+count if boxes[i]=="1": count+=1 ans.append(left[i]+right[i]) return ans
minimum-number-of-operations-to-move-all-balls-to-each-box
python sol
heisenbarg
0
108
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,395
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1169924/Simple-Python3-solution-with-O(n)-DP
class Solution: def minOperations(self, boxes: str) -> List[int]: # count num of elements in the left/now/right left_val, left_count = 0, 0 right_val = sum([idx+1 for idx, c in enumerate(boxes) if c == '1']) right_count = sum([1 for c in boxes if c == '1']) res = [] prev_c = '0' for c in boxes: # update left if needed if prev_c == '1': left_count += 1 left_val += left_count right_val -= right_count res.append(left_val+right_val) # update right if needed if c == '1': right_count -= 1 # update prev_c prev_c = c return res
minimum-number-of-operations-to-move-all-balls-to-each-box
Simple Python3 solution with O(n) DP
tkuo-tkuo
0
203
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,396
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1124906/short-python-solution
class Solution: def minOperations(self, b: str) -> List[int]: one_loc = [i for i,j in enumerate(b) if j=='1'] return [int(sum([ abs(i-j) for j in one_loc])) for i in range(len(b))]
minimum-number-of-operations-to-move-all-balls-to-each-box
short python solution
viridis45
0
89
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,397
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1076591/Python-3-or-Hash-Set-O(M*N)
class Solution: def minOperations(self, boxes: str) -> List[int]: m = set() for i,j in enumerate(boxes): if j == '1': m.add(i) res = [] for i in range(len(boxes)): res.append(sum(abs(i-index) for index in m)) return res
minimum-number-of-operations-to-move-all-balls-to-each-box
Python 3 | Hash Set O(M*N)
juesong931103
0
55
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,398
https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1075494/Python-easy-solution
class Solution: def minOperations(self, b: str) -> List[int]: l=[] for i in range(len(b)): a=0 for j in range(len(b)): if(i!=j and b[j]=="1"): a+=abs(j-i) l.append(a) return l
minimum-number-of-operations-to-move-all-balls-to-each-box
Python easy solution
ameygodse7
0
104
minimum number of operations to move all balls to each box
1,769
0.852
Medium
25,399