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/minimum-flips-to-make-a-or-b-equal-to-c/discuss/2211868/python-3-or-simple-solution-or-O(log(max(a-b-c)))O(1)
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: res = 0 while a or b or c: aBit, bBit, cBit = a % 2, b % 2, c % 2 if cBit: res += not (aBit or bBit) else: res += aBit + bBit a >>= 1 b >>= 1 c >>= 1 return res
minimum-flips-to-make-a-or-b-equal-to-c
python 3 | simple solution | O(log(max(a, b, c)))/O(1)
dereky4
0
28
minimum flips to make a or b equal to c
1,318
0.66
Medium
19,700
https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/discuss/1741099/1-Line-Python-with-Explanation
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: return (bin(~(c|(~a))) + bin(~(c|(~b))) + bin(c&(~(a|b)))).count('1')
minimum-flips-to-make-a-or-b-equal-to-c
1 Line Python with Explanation
bbiuyy
0
51
minimum flips to make a or b equal to c
1,318
0.66
Medium
19,701
https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/discuss/1200717/Python-fast-and-pythonic
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: result = 0 a, b, c = bin(a)[2:], bin(b)[2:], bin(c)[2:] max_len = max(len(a), len(b), len(c)) a, b, c = a.zfill(max_len), b.zfill(max_len), c.zfill(max_len) for i in range(len(c)): if c[i] == '1': result += a[i] == b[i] == '0' else: result += 2 if a[i] == b[i] == '1' else (a[i] == '1' or b[i] == '1') return result
minimum-flips-to-make-a-or-b-equal-to-c
[Python] fast and pythonic
cruim
0
71
minimum flips to make a or b equal to c
1,318
0.66
Medium
19,702
https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/discuss/979018/Beats-98
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: ans = 0 while a or b or c: if c % 2: if a%2 or b%2: pass else: ans += 1 else: if a%2 and b%2: ans += 2 elif (a%2 == 0 and b%2 == 1) or (a%2 == 1 and b%2 == 0): ans += 1 else: pass a = a >> 1 b = b >> 1 c = c >> 1 return ans
minimum-flips-to-make-a-or-b-equal-to-c
Beats 98%
Aditya380
0
49
minimum flips to make a or b equal to c
1,318
0.66
Medium
19,703
https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/discuss/776962/Python3-Simple-with-comments
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: # convert numbers to binary representation bin_a = bin(a)[2:] bin_b = bin(b)[2:] bin_c = bin(c)[2:] # pad numbers with zeros on the left side (aka rjust /right align) to make sure all 3 numbers are the same length max_len = max(len(bin_a), len(bin_b), len(bin_c)) bin_a = bin_a.rjust(max_len, '0') bin_b = bin_b.rjust(max_len, '0') bin_c = bin_c.rjust(max_len, '0') flips = 0 for i in range(max_len): if bin_c[i] == '1': # if c bit is 1, then at least one of a or b has to be 1 if bin_a[i] == '0' and bin_b[i] == '0': flips += 1 else: # if c bit is 0, then a and/or b need to flipped if they are not 0 if bin_a[i] == '1': flips += 1 if bin_b[i] == '1': flips += 1 return flips
minimum-flips-to-make-a-or-b-equal-to-c
Python3 - Simple with comments
beyondcloudtech
0
66
minimum flips to make a or b equal to c
1,318
0.66
Medium
19,704
https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/discuss/477724/Python3-Loop-through-bits
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: ans = 0 while a or b or c: a, aa = divmod(a, 2) b, bb = divmod(b, 2) c, cc = divmod(c, 2) if cc == 1: ans += (aa == bb == 0) else: ans += (aa == 1) + (bb == 1) return ans
minimum-flips-to-make-a-or-b-equal-to-c
[Python3] Loop through bits
ye15
0
44
minimum flips to make a or b equal to c
1,318
0.66
Medium
19,705
https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/discuss/1326153/Python3-solution-single-pass
class Solution: def minFlips(self, a: int, b: int, c: int) -> int: a = bin(a)[2:] b = bin(b)[2:] c = bin(c)[2:] x = max([len(a),len(b),len(c)]) a = a.zfill(x) b = b.zfill(x) c = c.zfill(x) count = 0 for i in range(x-1,-1,-1): if int(c[i]) != (int(a[i]) or int(b[i])): if c[i] == '0': if a[i] == '1': count += 1 if b[i] == '1': count += 1 else: count += 1 return count
minimum-flips-to-make-a-or-b-equal-to-c
Python3 solution single-pass
EklavyaJoshi
-1
47
minimum flips to make a or b equal to c
1,318
0.66
Medium
19,706
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2420269/Operations-to-make-network-connected-oror-Python3-oror-Union-Find
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: self.components = n # We need atleast n-1 connections to connect n networks if(len(connections) < n-1): return -1 # If we have n-1 connections, we only need to count to number of components # Union-Find parent = [i for i in range(0, n)] rank = [0] * n for x, y in connections: self.union(x, y, parent, rank) # we require no. of components - 1 edge to connect n components return self.components - 1 def find(self, x, parent): if(parent[x] != x): parent[x] = self.find(parent[x], parent) return parent[x] def union(self, x, y, parent, rank): parent_x = self.find(x, parent) parent_y = self.find(y, parent) if(parent_x == parent_y): return rank_x = rank[parent_x] rank_y = rank[parent_y] if(rank_x > rank_y): parent[parent_y] = parent_x elif(rank_x < rank_y): parent[parent_x] = parent_y else: parent[parent_y] = parent_x rank[parent_x] += 1 self.components -= 1
number-of-operations-to-make-network-connected
Operations to make network connected || Python3 || Union-Find
vanshika_2507
1
30
number of operations to make network connected
1,319
0.585
Medium
19,707
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2299765/Python3-DFS-solution
class Solution: def makeConnected(self, n: int, a: List[List[int]]) -> int: length = len(a) if length < n - 1: return -1 nodes = set() connections = defaultdict(list) for src,dest in a: connections[src].append(dest) connections[dest].append(src) def dfs(src): if src in nodes: return nodes.add(src) for node in connections[src]: dfs(node) result = 0 for i in range(n): if i not in nodes: dfs(i) result+=1 return result - 1
number-of-operations-to-make-network-connected
📌 Python3 DFS solution
Dark_wolf_jss
1
38
number of operations to make network connected
1,319
0.585
Medium
19,708
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2159089/Connected-Compnents-oror-DFS-oror-Fastest-Optimal-Solution-oror-TC-%3A-O(V2)
class Solution: def dfs(self, comp, idx, visited, graph): visited[idx] = True comp.append(idx) for neighbour in graph[idx]: if visited[neighbour] is False: comp = self.dfs(comp, neighbour, visited, graph) return comp def makeConnected(self, n: int, connections: List[List[int]]) -> int: graph = {} for i in range(n): graph[i] = [] for connection in connections: graph[connection[0]].append(connection[1]) graph[connection[1]].append(connection[0]) totalEdges = 0 for key, value in graph.items(): totalEdges += len(value) totalEdges = totalEdges//2 visited = [False]*n connectedComponents = [] for i in range(n): if len(graph[i]) > 0 and visited[i] is False: component = [] connectedComponents.append(self.dfs(component, i, visited, graph)) elif len(graph[i]) == 0: connectedComponents.append([i]) totalComponents = len(connectedComponents) redundantEdges = totalEdges - ((n - 1) - (totalComponents - 1)) requiredEdges = totalComponents - 1 if redundantEdges >= requiredEdges: return requiredEdges else: return -1
number-of-operations-to-make-network-connected
Connected Compnents || DFS || Fastest Optimal Solution || TC :- O(V^2)
Vaibhav7860
1
93
number of operations to make network connected
1,319
0.585
Medium
19,709
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2817975/Number-of-Operations-to-Make-Network-Connected
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: def solve(node, parent, vis, adj,check): vis[node] = True for i in adj[node]: #print(parent, node, i) if i == parent: continue if vis[i] and i != parent: #print(i,node) if check[str(sorted([i,node]))] == 0: solve.ans += 1 check[str(sorted([i,node]))] += 1 elif not vis[i]: solve(i, node, vis, adj, check) adj = [[] for i in range(n)] check = {} for i in connections: u = i[0] v = i[1] adj[u].append(v) adj[v].append(u) check[str(sorted([u,v]))] = 0 #print(check) empty = -1 parent = -1 vis = [False for i in range(n)] solve.ans = 0 for i in range(n): if not vis[i]: solve(i, parent, vis, adj, check) empty += 1 if (solve.ans) >= empty: return empty return -1
number-of-operations-to-make-network-connected
Number of Operations to Make Network Connected
sarthakchawande14
0
2
number of operations to make network connected
1,319
0.585
Medium
19,710
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2782904/Python-Union-Find-Method
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: #Check the numbers of cables if n>len(connections)+1: return -1 uf=UnionFind(n) for [x,y] in connections: uf.union(x,y) return uf.groups-1 # UnionFind class class UnionFind: def __init__(self, size): self.root = [i for i in range(size)] self.groups=size def find(self, x): if x == self.root[x]: return x self.root[x] = self.find(self.root[x]) return self.root[x] def union(self, x, y): rootX = self.find(x) rootY = self.find(y) if rootX != rootY: self.root[rootY] = rootX self.groups-=1
number-of-operations-to-make-network-connected
[Python] Union Find Method
Hikari-Tsai
0
3
number of operations to make network connected
1,319
0.585
Medium
19,711
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2748216/python3-oror-easy-oror-intuitive-disjoint-set-approach
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: parentArray=[i for i in range(n)] sizeArray=[1 for i in range(n)] extraEdges=0 components=0 def findUltimateParent(node): if parentArray[node]==node: return node parentArray[node]=findUltimateParent(parentArray[node]) return parentArray[node] def union(u,v): parentU=findUltimateParent(u) parentV=findUltimateParent(v) if parentU==parentV: return if sizeArray[parentU]<sizeArray[parentV]: parentArray[parentU]=parentV sizeArray[parentV]+=sizeArray[parentU] else: parentArray[parentV]=parentU sizeArray[parentU]+=sizeArray[parentV] for i,j in connections: if findUltimateParent(i)==findUltimateParent(j): extraEdges+=1 else: union(i,j) #counting connected components for i in range(len(parentArray)): if parentArray[i]==i: components+=1 if extraEdges>=(components-1): return components-1 return -1
number-of-operations-to-make-network-connected
python3 || easy || intuitive disjoint set approach
_soninirav
0
4
number of operations to make network connected
1,319
0.585
Medium
19,712
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2745075/DFS-BFS-UnionFind-to-find-number-of-components
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: if len(connections) < n-1: return -1 graph = [[] for _ in range(n)] for connection in connections: graph[connection[0]].append(connection[1]) graph[connection[1]].append(connection[0]) visited = set() def dfs(node): visited.add(node) for nei in graph[node]: if nei not in visited: dfs(nei) return components = 0 for node in range(n): if node not in visited: dfs(node) components += 1 return components - 1
number-of-operations-to-make-network-connected
DFS, BFS, UnionFind to find number of components
shriyansnaik
0
4
number of operations to make network connected
1,319
0.585
Medium
19,713
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2745075/DFS-BFS-UnionFind-to-find-number-of-components
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: if len(connections) < n-1: return -1 graph = [[] for _ in range(n)] for connection in connections: graph[connection[0]].append(connection[1]) graph[connection[1]].append(connection[0]) visited = set() def bfs(v): queue = deque() queue.append(v) visited.add(v) while queue: node = queue.popleft() for nei in graph[node]: if nei not in visited: queue.append(nei) visited.add(nei) return components = 0 for node in range(n): if node not in visited: bfs(node) components += 1 return components - 1
number-of-operations-to-make-network-connected
DFS, BFS, UnionFind to find number of components
shriyansnaik
0
4
number of operations to make network connected
1,319
0.585
Medium
19,714
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2363013/or-Python-3-or-DFS-Solution-or
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: if len(connections) < n - 1: return -1 visited = [False for vis in range(n)] graph = [[] for grp in range(n)] for connection in connections: graph[connection[0]].append(connection[1]) graph[connection[1]].append(connection[0]) def dfs(idx) -> None: if visited[idx]: return visited[idx] = True for destination in graph[idx]: dfs(destination) answer = -1 i = 0 while i < n: if not visited[i]: answer += 1 dfs(i) i += 1 return answer
number-of-operations-to-make-network-connected
| Python 3 | DFS Solution |
YudoTLE
0
22
number of operations to make network connected
1,319
0.585
Medium
19,715
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2318137/Python3-Find-number-of-redundant-connection-and-connected-component
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: # if number of connected component - 1 == number of redundant wire # use union find par = [i for i in range(n)] rank = [1 for i in range(n)] connected = n redundant_wire = 0 def find(n1): p = par[n1] while p != par[p]: p = par[p] return p def union(n1, n2): p1 = find(n1) p2 = find(n2) if p1 == p2: # redundant connetion return False if rank[p1] >= rank[p2]: par[p2] = p1 rank[p1] += rank[p2] else: par[p1] = p2 rank[p2] += rank[p1] return True for connection in connections: if union(connection[0], connection[1]): connected -= 1 else: redundant_wire += 1 # if we have more redundant wire, we just need connected - 1 wires if connected - 1 <= redundant_wire: return connected-1 return -1
number-of-operations-to-make-network-connected
[Python3] Find number of redundant connection and connected component
Gp05
0
50
number of operations to make network connected
1,319
0.585
Medium
19,716
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/1899475/Python-99-Using-DFS
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: def dfs_(u): #internal dfs for going into depth of node # q = [u] if vis[u]: return #print(u,vis) vis[u] = True for j in graph[u]: if vis[j]: continue; #vis[j] = True dfs_(j) def dfs(): #dfs for each node c = 0 for i in range(n): if vis[i]: continue; #vis[i] = Trueu #print(i) dfs_(i) c+=1 return c-1 vis = [False]*n graph = defaultdict(list) graph = {i:[] for i in range(n)} for u,v in connections: graph[u].append(v) graph[v].append(u) #print(graph) return dfs() if n-1<=len(connections) else -1
number-of-operations-to-make-network-connected
[Python] 99% Using DFS
rstudy211
0
88
number of operations to make network connected
1,319
0.585
Medium
19,717
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/1818518/Python-Union-Find
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: parent = [i for i in range(n)] rank = [1] * n groups = [n] def find(x: int) -> int: p = parent[x] while p != parent[p]: p = parent[p] parent[x] = p return p def union(x: int, y: int) -> None: x, y = find(x), find(y) if x != y: if rank[y] > rank[x]: x, y = y, x parent[y] = x rank[x] += rank[y] groups[0] -= 1 for node, neigh in connections: union(node, neigh) # when we have n-1 or more connections it's always possible to connect all the components by moving the connections around if len(connections) >= n-1: return groups[0]-1 # for n amount of components, we only need n-1 connections to connect them all return -1
number-of-operations-to-make-network-connected
Python Union-Find
Rush_P
0
67
number of operations to make network connected
1,319
0.585
Medium
19,718
https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/478485/Python3-simple-solution-using-a-graph
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: if len(connections)<n-1: return -1 self.graph,self.visited = {node:set() for node in range(n)},[0]*n for n1,n2 in connections: self.graph[n1].add(n2) self.graph[n2].add(n1) count = -1 for node in range(n): count += self.dfs(node) return count def dfs(self,node): if self.visited[node]: return 0 self.visited[node]=1 for n in self.graph[node]: self.dfs(n) return 1
number-of-operations-to-make-network-connected
Python3 simple solution using a graph
jb07
0
55
number of operations to make network connected
1,319
0.585
Medium
19,719
https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/1509241/Well-Coded-oror-Clean-and-Concise-oror-93-faster
class Solution: def minimumDistance(self, word: str) -> int: def dist(pre,cur): if pre==None: return 0 x1,y1 = divmod(ord(pre)-ord('A'),6) x2,y2 = divmod(ord(cur)-ord('A'),6) return abs(x1-x2) + abs(y1-y2) @lru_cache(None) def fingers(i,l,r): if i == len(word): return 0 n1 = dist(l,word[i]) + fingers(i+1,word[i],r) n2 = dist(r,word[i]) + fingers(i+1,l,word[i]) return min(n1,n2) return fingers(0,None,None)
minimum-distance-to-type-a-word-using-two-fingers
📌📌 Well-Coded || Clean & Concise || 93% faster 🐍
abhi9Rai
2
228
minimum distance to type a word using two fingers
1,320
0.597
Hard
19,720
https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/1485756/Python-or-81-speed-or-Intuitive-or-O(676-*-orwordor)-or-Recursion-%2B-Memo
class Solution: def minimumDistance(self, word: str) -> int: locations = {} x, y = 0, 0 for i in range(65, 91): locations[chr(i)] = (x, y) y += 1 if y > 5: x += 1 y = 0 #print(locations) @lru_cache(None) def func(idx, f1, f2): if idx == len(word): return 0 # use f1 if f1 == '': x1, y1 = locations[word[idx]] else: x1, y1 = locations[f1] x, y = locations[word[idx]] dist1 = abs(x1 - x) + abs(y1 - y) useF1 = dist1 + func(idx + 1, word[idx], f2) if f2 == '': x2, y2 = locations[word[idx]] else: x2, y2 = locations[f2] dist2 = abs(x2 - x) + abs(y2 - y) useF2 = dist2 + func(idx + 1, f1, word[idx]) return min(useF1, useF2) return func(0, '', '')
minimum-distance-to-type-a-word-using-two-fingers
Python | 81% speed | Intuitive | O(676 * |word|) | Recursion + Memo
detective_dp
1
179
minimum distance to type a word using two fingers
1,320
0.597
Hard
19,721
https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/478022/Python-3-(eight-lines)-(beats-100)-(376-ms)-(BFS-w-Memo)
class Solution: def minimumDistance(self, W: str) -> int: A, B, I, W = {(ord(W[0])-65,-1):0}, {}, math.inf, [ord(w)-65 for w in W] def dist(u,v): return abs(u//6 - v//6) + abs(u % 6 - v % 6) for w in W[1:]: for a in A: B[(w,a[1])] = min(B.get((w,a[1]),I), A[a] + dist(a[0],w)) B[(a[0],w)] = min(B.get((a[0],w),I), A[a] + (a[1] != -1)*dist(a[1],w)) A, B = B, {} return min(A.values()) - Junaid Mansuri - Chicago, IL
minimum-distance-to-type-a-word-using-two-fingers
Python 3 (eight lines) (beats 100%) (376 ms) (BFS w/ Memo)
junaidmansuri
1
236
minimum distance to type a word using two fingers
1,320
0.597
Hard
19,722
https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/1106569/Python3-top-down-dp
class Solution: def minimumDistance(self, word: str) -> int: word = [ord(x)-65 for x in word] dist = lambda x, y: 0 if -1 in (x, y) else abs(x//6 - y//6) + abs(x%6 - y%6) # l1 distance @cache def fn(i, f1=-1, f2=-1): """Return minimum distance of typing word[i:] with 2 fingers.""" if i == len(word): return 0 return min(dist(word[i], f1) + fn(i+1, word[i], f2), dist(word[i], f2) + fn(i+1, f1, word[i])) return fn(0)
minimum-distance-to-type-a-word-using-two-fingers
[Python3] top-down dp
ye15
0
131
minimum distance to type a word using two fingers
1,320
0.597
Hard
19,723
https://leetcode.com/problems/maximum-69-number/discuss/2787125/PYTHON-oror-EASY-TO-UNDERSTAND-oror-WELL-EXPLAINED
class Solution: def maximum69Number (self, nums: int) -> int: nums = str(nums) #changing integer to string j = 1 #maximum number you can change atmost for i in range(len(nums)): if nums[i] == "6" and (j == 1): #checking if the element is "6" and we are change only once bef = nums[:i] #stored element before the element 6 using slicing aft = nums[i+1:] #stored element after the element 6 using slicing nums = bef + "9"+aft #adding element in place of 6 j-=1 # we will reduct 1. so that above condition cant satisfy again. nums = int(nums) return nums
maximum-69-number
PYTHON || EASY TO UNDERSTAND || WELL EXPLAINED
thesunnysinha
5
372
maximum 69 number
1,323
0.821
Easy
19,724
https://leetcode.com/problems/maximum-69-number/discuss/2787127/Detailed-Explanation-of-the-Python-Solution-or-99-Faster
class Solution: def maximum69Number (self, num: int) -> int: num = list(str(num)) for i, n in enumerate(num): if n == '6': num[i] = '9' break return int(''.join(num))
maximum-69-number
✔️ Detailed Explanation of the Python Solution | 99% Faster 🔥
pniraj657
4
144
maximum 69 number
1,323
0.821
Easy
19,725
https://leetcode.com/problems/maximum-69-number/discuss/486561/Python-beats-100-no-string-conversion-explained!
class Solution: def maximum69Number(self, num): i = j = 0 original_num = num while num: i += 1 d = num % 10 if d == 6: j = i num //= 10 return original_num + 3*10**(j-1) if j > 0 else original_num
maximum-69-number
Python - beats 100%, no string conversion - explained!
domthedeveloper
4
680
maximum 69 number
1,323
0.821
Easy
19,726
https://leetcode.com/problems/maximum-69-number/discuss/484317/Python-3-(one-line)-(beats-100)
class Solution: def maximum69Number (self, n: int) -> int: return int(str(n).replace('6','9',1)) - Junaid Mansuri - Chicago, IL
maximum-69-number
Python 3 (one line) (beats 100%)
junaidmansuri
4
399
maximum 69 number
1,323
0.821
Easy
19,727
https://leetcode.com/problems/maximum-69-number/discuss/1222931/python-95-fasteror-easy-solution
class Solution: def maximum69Number (self, num: int) -> int: string = str(num) string = string.replace('6','9',1) return int(string)
maximum-69-number
[python] 95% faster| easy solution
arkumari2000
3
353
maximum 69 number
1,323
0.821
Easy
19,728
https://leetcode.com/problems/maximum-69-number/discuss/2786667/Easy-Python-Solution
class Solution: def maximum69Number (self, num: int) -> int: m=num s=(str(num)) for i in range(len(s)): if s[i]=="6": temp=(int(s[:i]+"9"+s[i+1:])) else: temp=(int(s[:i]+"6"+s[i+1:])) m=max(m,temp) return m
maximum-69-number
Easy Python Solution
Vistrit
2
156
maximum 69 number
1,323
0.821
Easy
19,729
https://leetcode.com/problems/maximum-69-number/discuss/683315/Python-Very-Easy-One-Liner.
class Solution: def maximum69Number (self, num: int) -> int: return int(str(num).replace('6', '9', 1))
maximum-69-number
Python, Very Easy One-Liner.
Cavalier_Poet
2
301
maximum 69 number
1,323
0.821
Easy
19,730
https://leetcode.com/problems/maximum-69-number/discuss/1324678/Python-solution-using-replace
class Solution: def maximum69Number (self, num: int) -> int: num = str(num) if '6' in num: num = num.replace('6','9',1) return int(num)
maximum-69-number
Python solution using replace
_Mansiii_
1
76
maximum 69 number
1,323
0.821
Easy
19,731
https://leetcode.com/problems/maximum-69-number/discuss/522661/Python-Solution-using-Stack-O(log10(n))
class Solution: def maximum69Number (self, num: int) -> int: numStack = [] while num!=0: rem = num%10 num = num // 10 numStack.append(rem) newNum = 0 found = False while len(numStack)!=0: dig = numStack.pop() if dig == 6 and not found: dig = 9 found = True newNum *= 10 newNum += dig return newNum
maximum-69-number
[Python] Solution using Stack O(log10(n))
shreyashag
1
216
maximum 69 number
1,323
0.821
Easy
19,732
https://leetcode.com/problems/maximum-69-number/discuss/492058/Python3-String-replace
class Solution: def maximum69Number (self, num: int) -> int: return int(str(num).replace("6", "9", 1))
maximum-69-number
[Python3] String replace
ye15
1
107
maximum 69 number
1,323
0.821
Easy
19,733
https://leetcode.com/problems/maximum-69-number/discuss/2843599/Easy-to-understand-solution
class Solution: def maximum69Number (self, num: int) -> int: count = [] change = [] res=0 value=1 six=0 for i in str(num): change.append(i) for j in change: if j =='9': res += 9*10**int(len(change)-value) value +=1 if j == '6': if six ==0: res += 9*10**int(len(change)-value) value+=1 six+=1 else: res += 6*10**int(len(change)-value) value+=1 return res
maximum-69-number
Easy to understand solution
Warrior-Quant
0
3
maximum 69 number
1,323
0.821
Easy
19,734
https://leetcode.com/problems/maximum-69-number/discuss/2843599/Easy-to-understand-solution
class Solution: def maximum69Number (self, num: int) -> int: strNum = str(num) found = False for i in range(len(strNum)): if strNum[i] == '6' and not found: strNum = strNum[:i] + '9' + strNum[i+1:] found = True print(strNum) return int(strNum)
maximum-69-number
Easy to understand solution
Warrior-Quant
0
3
maximum 69 number
1,323
0.821
Easy
19,735
https://leetcode.com/problems/maximum-69-number/discuss/2816414/Fast-and-Simply-Solution-Python
class Solution: def maximum69Number (self, num: int) -> int: num = str(num) if "6" in num: index = num.index("6") number = "" for i in range(0, len(num)): if i == index: number += "9" else: number += num[i] return int(number) else: return int(num)
maximum-69-number
Fast and Simply Solution - Python
PranavBhatt
0
2
maximum 69 number
1,323
0.821
Easy
19,736
https://leetcode.com/problems/maximum-69-number/discuss/2805375/simple
class Solution: def maximum69Number (self, n: int) -> int: return int(str(n).replace('6','9',1))
maximum-69-number
simple
siva00100
0
1
maximum 69 number
1,323
0.821
Easy
19,737
https://leetcode.com/problems/maximum-69-number/discuss/2798768/Beats-98
class Solution: def maximum69Number (self, num: int) -> int: num_list = list(str(num)) for i in range(len(num_list)): if num_list[i] == str(6): num_list[i]=str(9) break print(num_list) num=int("".join(num_list)) return num
maximum-69-number
Beats 98%
user5333xb
0
2
maximum 69 number
1,323
0.821
Easy
19,738
https://leetcode.com/problems/maximum-69-number/discuss/2795483/Python-easy-to-read-and-understand
class Solution: def maximum69Number (self, num: int) -> int: nums = list(str(num)) for i, num in enumerate(nums): if num == '6': nums[i] = '9' break return int(''.join(nums))
maximum-69-number
Python easy to read and understand
sanial2001
0
4
maximum 69 number
1,323
0.821
Easy
19,739
https://leetcode.com/problems/maximum-69-number/discuss/2794393/Maximum-69-number-Python3-Easy
class Solution: def maximum69Number (self, num: int) -> int: num_arr=list(str(num)) for i in range(len(num_arr)): if num_arr[i]=='6': num_arr[i]='9' break return int(''.join(num_arr))
maximum-69-number
Maximum 69 number-Python3-Easy
phanee16
0
1
maximum 69 number
1,323
0.821
Easy
19,740
https://leetcode.com/problems/maximum-69-number/discuss/2794241/Maximum69-Solution-or-Python-or-Enumerate
class Solution: def maximum69Number (self, num: int) -> int: numbers_list = [int(d) for d in str(num)] for i,n in enumerate(numbers_list): if n == 6: numbers_list[i] = 9 break new_num = int("".join(map(str, numbers_list))) return new_num
maximum-69-number
Maximum69 Solution | Python | Enumerate
mitterbabu
0
1
maximum 69 number
1,323
0.821
Easy
19,741
https://leetcode.com/problems/maximum-69-number/discuss/2793401/Python-oror-String-oror-Easy-to-Understand
class Solution: def maximum69Number (self, num: int) -> int: newNum="" num=str(num) i=0 while (i<len(num)): if (num[i]=='6'): newNum+='9' break newNum+=num[i] i+=1 newNum+=num[i+1:] return int(newNum)
maximum-69-number
Python || String || Easy to Understand
vishal_niet
0
3
maximum 69 number
1,323
0.821
Easy
19,742
https://leetcode.com/problems/maximum-69-number/discuss/2792251/98.46-FASTERPYTHONand-ONE-LINER-EXPLAINED
class Solution: def maximum69Number (self, num: int) -> int: s = str(num) l = list(s) if '6' in s: six = s.index('6') l[six] = '9' return int("".join(l))
maximum-69-number
✅98.46% FASTER🐍PYTHON💥& ONE-LINER EXPLAINED
shubhamdraj
0
2
maximum 69 number
1,323
0.821
Easy
19,743
https://leetcode.com/problems/maximum-69-number/discuss/2792251/98.46-FASTERPYTHONand-ONE-LINER-EXPLAINED
class Solution: def maximum69Number (self, num: int) -> int: return int(str(num).replace("6", "9", 1))
maximum-69-number
✅98.46% FASTER🐍PYTHON💥& ONE-LINER EXPLAINED
shubhamdraj
0
2
maximum 69 number
1,323
0.821
Easy
19,744
https://leetcode.com/problems/maximum-69-number/discuss/2790640/Using-String-Python3
class Solution: def maximum69Number (self, num: int) -> int: num= list(str(num)) for i in range(len(num)): if num[i]=='6': num[i]='9' break return ''.join(num)
maximum-69-number
Using String Python3
SAI_KRISHNA_PRATHAPANENI
0
3
maximum 69 number
1,323
0.821
Easy
19,745
https://leetcode.com/problems/maximum-69-number/discuss/2790572/divmod-solution
class Solution: def maximum69Number (self, num: int) -> int: #k = int(log(num, 10)) k = 4 pos = 10**k cur_num = num while pos >= 1: cur_digit, cur_num = divmod(cur_num, pos) if cur_digit == 6: return num + 3*pos pos = pos // 10 return num
maximum-69-number
divmod solution
nonchalant-enthusiast
0
2
maximum 69 number
1,323
0.821
Easy
19,746
https://leetcode.com/problems/maximum-69-number/discuss/2790461/Python-3-solution
class Solution: def maximum69Number (self, num: int) -> int: num = list(str(num)) for i in range(0,len(num)): if num[i]=='6': num[i]='9' break return ''.join(num)
maximum-69-number
Python 3 solution
mj1602
0
3
maximum 69 number
1,323
0.821
Easy
19,747
https://leetcode.com/problems/maximum-69-number/discuss/2790423/Faster-than-82.37
class Solution: def maximum69Number (self, num: int) -> int: num_str = list(str(num)) change = False for i in range(len(num_str)): if num_str[i] == "6": change = True break if not change: return int("".join(num_str)) else: for i in range(len(num_str)): if num_str[i] == "6": num_str[i] = "9" break return int("".join(num_str))
maximum-69-number
Faster than 82.37% 🔥
starlingvibes
0
1
maximum 69 number
1,323
0.821
Easy
19,748
https://leetcode.com/problems/maximum-69-number/discuss/2790221/Use-math.log10-without-string-conversion
class Solution: def maximum69Number (self, num: int) -> int: ans = 0 while num: k = 10 ** int(math.log10(num)) first, num = divmod(num, k) ans += 9 * k if first == 6: return ans + num return ans
maximum-69-number
Use math.log10 without string conversion
kcostya
0
2
maximum 69 number
1,323
0.821
Easy
19,749
https://leetcode.com/problems/maximum-69-number/discuss/2790120/Python3-Solution-one-liner
class Solution: def maximum69Number (self, num: int) -> int: return num if str(num).find('6') == -1 else int(str(num).replace('6', '9', 1))
maximum-69-number
Python3 Solution one-liner
sipi09
0
4
maximum 69 number
1,323
0.821
Easy
19,750
https://leetcode.com/problems/maximum-69-number/discuss/2789974/Maximum-69-number-oror-PYTHON
class Solution: def maximum69Number (self, num: int) -> int: arr = [i for i in str(num)] ans = [ ] op="" for i in range(len(arr)): if arr[i]!="9": temp = op op = op + "9"+ "".join(arr[i+1:]) ans.append(int(op)) op = temp + arr[i] else: op+=arr[i] m=0 for i in ans: m=max(i,m) return max(m,num)
maximum-69-number
Maximum 69 number || PYTHON
cheems_ds_side
0
6
maximum 69 number
1,323
0.821
Easy
19,751
https://leetcode.com/problems/maximum-69-number/discuss/2789950/Intuition-Explained
class Solution: def maximum69Number (self, num: int) -> int: # convert integer to string num = str(num) # convert this string into array of chars, cuz python string is immutable num = list(num) # since 9 bigger than 6, best way to maximize value would be to find the 6 with highest position... # then swap it for a 9... # if number has no 6, no scope of increasing value.. for i in range(len(num)): if num[i] == '6': # found the first 6...make it 9 and break out of the loop num[i] = '9' break # if we got no 6, we will go through full loop without changing anything # convert our list back into an integer # list to string num = ''.join(num) # string to num num = int(num) return num
maximum-69-number
Intuition Explained
g_aswin
0
4
maximum 69 number
1,323
0.821
Easy
19,752
https://leetcode.com/problems/maximum-69-number/discuss/2789808/Maximum-69-Number-or-Python-Solution
class Solution: def maximum69Number (self, num: int) -> int: return int(str(num).replace('6', '9', 1))
maximum-69-number
Maximum 69 Number | Python Solution
nishanrahman1994
0
6
maximum 69 number
1,323
0.821
Easy
19,753
https://leetcode.com/problems/maximum-69-number/discuss/2789799/Easy-Solution
class Solution: def maximum69Number (self, num: int) -> int: m=num t=list(str(num)) for i in range(len(t)): t=list(str(num)) t[i]='6' if(t[i]=='9')else '9' m=max(m,int("".join(t))) return m
maximum-69-number
Easy Solution
soumya262003
0
3
maximum 69 number
1,323
0.821
Easy
19,754
https://leetcode.com/problems/maximum-69-number/discuss/2789709/Python3-Solution-with-using-remainder
class Solution: def maximum69Number (self, num: int) -> int: shift = 1 num_copy = num add_num = 0 while num_copy: digit = num_copy % 10 if digit == 6: add_num = shift * 3 shift *= 10 num_copy //= 10 return num + add_num
maximum-69-number
[Python3] Solution with using remainder
maosipov11
0
2
maximum 69 number
1,323
0.821
Easy
19,755
https://leetcode.com/problems/maximum-69-number/discuss/2789643/Simple-Python-Solution-or-Using-Strings
class Solution: def maximum69Number (self, num: int) -> int: temp = str(num) for i in range(len(temp)): if temp[i] == '6': return int(temp[:i] + '9' + temp[i+1:]) return num
maximum-69-number
Simple Python Solution | Using Strings
Depender
0
5
maximum 69 number
1,323
0.821
Easy
19,756
https://leetcode.com/problems/maximum-69-number/discuss/2789642/Python-easy-to-understand-solution-(Faster-than-94)
class Solution: def maximum69Number (self, num: int) -> int: numCopy = num i = 0 sixIdx = -1 while numCopy: r = numCopy % 10 numCopy //= 10 i += 1 if r == 6: sixIdx = i if sixIdx != -1: return num + 3 * (10 ** (sixIdx - 1)) return num
maximum-69-number
Python easy to understand solution (Faster than 94%)
KevinJM17
0
2
maximum 69 number
1,323
0.821
Easy
19,757
https://leetcode.com/problems/maximum-69-number/discuss/2789642/Python-easy-to-understand-solution-(Faster-than-94)
class Solution: def maximum69Number (self, num: int) -> int: numdigit = list(str(num)) for i in range(len(numdigit)): if numdigit[i] == '6': numdigit[i] = '9' return int(''.join(numdigit)) return num
maximum-69-number
Python easy to understand solution (Faster than 94%)
KevinJM17
0
2
maximum 69 number
1,323
0.821
Easy
19,758
https://leetcode.com/problems/maximum-69-number/discuss/2789639/1323-%3A-Python-Easy-Solution-with-comment
class Solution(object): def maximum69Number(self,num): num_arr = list(str(num) #first we will create a variable and convert string to list : eg 9995 will be ['9','9','9','5'] for i in range(len(num_arr): #we are going to iterate through the list if num_arr[i] == '6': #if index of num_arr is equal to 6 then num_arr[i] ='9' # for getting the maximum number break # to come out of the if statement print(''.join('num_sum')) # combine the list
maximum-69-number
✅✔1323 : Python Easy Solution with comment
nitin_207013
0
4
maximum 69 number
1,323
0.821
Easy
19,759
https://leetcode.com/problems/maximum-69-number/discuss/2789575/Without-converting-to-string-One-Liner-or-Python
class Solution: def maximum69Number (self, num: int) -> int: ind = 0 power = -1 var = num while var > 0: if var % 10 == 6: power = ind var = var //10 ind += 1 return (num + 3*(10**power)) if power != -1 else num
maximum-69-number
Without converting to string , One Liner | Python
Abhi_-_-
0
3
maximum 69 number
1,323
0.821
Easy
19,760
https://leetcode.com/problems/maximum-69-number/discuss/2789575/Without-converting-to-string-One-Liner-or-Python
class Solution: def maximum69Number (self, num: int) -> int: return int(str(num).replace('6', '9', 1))
maximum-69-number
Without converting to string , One Liner | Python
Abhi_-_-
0
3
maximum 69 number
1,323
0.821
Easy
19,761
https://leetcode.com/problems/maximum-69-number/discuss/2789575/Without-converting-to-string-One-Liner-or-Python
class Solution: def maximum69Number (self, num: int) -> int: dig = list(str(num)) if '6' in dig: dig[dig.index('6')] = '9' return int(''.join(dig)) return num
maximum-69-number
Without converting to string , One Liner | Python
Abhi_-_-
0
3
maximum 69 number
1,323
0.821
Easy
19,762
https://leetcode.com/problems/maximum-69-number/discuss/2789459/Python-or-LeetCode-or-1323.-Maximum-69-Number
class Solution: def maximum69Number (self, num: int) -> int: list_num = list(str(num)) for i, e in enumerate(list_num): if e == '6': list_num[i] = '9' break return int(''.join(list_num))
maximum-69-number
Python | LeetCode | 1323. Maximum 69 Number
UzbekDasturchisiman
0
7
maximum 69 number
1,323
0.821
Easy
19,763
https://leetcode.com/problems/maximum-69-number/discuss/2789459/Python-or-LeetCode-or-1323.-Maximum-69-Number
class Solution: def maximum69Number (self, num): exp = len(str(num)) - 1 n = num while exp >= 0: x = num // (10 ** exp) y = num % (10 ** exp) if x == 6: return n + 3 * (10 ** exp) else: exp -= 1 num = y return n
maximum-69-number
Python | LeetCode | 1323. Maximum 69 Number
UzbekDasturchisiman
0
7
maximum 69 number
1,323
0.821
Easy
19,764
https://leetcode.com/problems/maximum-69-number/discuss/2789459/Python-or-LeetCode-or-1323.-Maximum-69-Number
class Solution: def maximum69Number (self, num: int) -> int: return int(str(num).replace('6', '9', 1))
maximum-69-number
Python | LeetCode | 1323. Maximum 69 Number
UzbekDasturchisiman
0
7
maximum 69 number
1,323
0.821
Easy
19,765
https://leetcode.com/problems/maximum-69-number/discuss/2789459/Python-or-LeetCode-or-1323.-Maximum-69-Number
class Solution: def maximum69Number (self, num: int) -> int: list_num = list(str(num)) for i, e in enumerate(list_num): if e == "6": list_num[i] = "9" break ret_str = "" for j in list_num: ret_str += j return int(ret_str)
maximum-69-number
Python | LeetCode | 1323. Maximum 69 Number
UzbekDasturchisiman
0
7
maximum 69 number
1,323
0.821
Easy
19,766
https://leetcode.com/problems/maximum-69-number/discuss/2789416/Simple-Python-Solution-using-String
class Solution: def maximum69Number (self, num: int) -> int: x = str(num) if '6' in x: return int(x.replace('6','9',1)) return num
maximum-69-number
Simple Python Solution using String
jps194
0
4
maximum 69 number
1,323
0.821
Easy
19,767
https://leetcode.com/problems/maximum-69-number/discuss/2789369/Python-simple-to-understand
class Solution: def maximum69Number (self, num: int) -> int: num_str:str = str(num) for i,v in enumerate(num_str): if v != "9": num_str=num_str[:i] + "9" + num_str[i+1:] return int(num_str) return num
maximum-69-number
Python simple to understand
MuftawoOmar
0
5
maximum 69 number
1,323
0.821
Easy
19,768
https://leetcode.com/problems/maximum-69-number/discuss/2789214/Simple-Python-Solution
class Solution: def maximum69Number (self, num: int) -> int: s=str(num) r='' flag=1 for i in s: if i=='6' and flag: r+='9' flag=0 else: r+=i return int(r)
maximum-69-number
Simple Python Solution
Siddharth_singh
0
5
maximum 69 number
1,323
0.821
Easy
19,769
https://leetcode.com/problems/maximum-69-number/discuss/2789188/optimised-one-in-python3
class Solution: def maximum69Number (self, num: int) -> int: x=str(num) z="" n=1 for i in x: if(int(i)==6)and(n==1):z=z+"9";n=2;continue; if(n==2)or(int(i)==9):z=z+i; return int(z)
maximum-69-number
optimised one in python3
pavankumar19992208
0
2
maximum 69 number
1,323
0.821
Easy
19,770
https://leetcode.com/problems/maximum-69-number/discuss/2789185/Python-Solution
class Solution: def maximum69Number (self, num: int) -> int: # create result array res = [] num_list = str(num) n = len(num_list) # if num has no 6 int, then return num if '6' not in num_list: return num # Linearly iterate and subst 6 to 9 and 9 to 6 for i in range(len(num_list) -1): if num_list[i] == '6': res.append(int(num_list[:i] +'9' + num_list[i+1:])) else: res.append(int(num_list[:i] +'6' + num_list[i+1:])) # Check and update last element of string if num_list.endswith('6'): res.append(int(num_list[:n-1]+'9')) # return max number return max(res)
maximum-69-number
Python Solution
ratva0717
0
2
maximum 69 number
1,323
0.821
Easy
19,771
https://leetcode.com/problems/maximum-69-number/discuss/2789127/Python-3-or-Simple-Math
class Solution: def maximum69Number (self, num: int) -> int: temp = str(num) if '6' not in temp: return num left = 0 n = len(temp) while temp[left] != '6': if temp[left] != '6': left += 1 num += 3 * (10 ** (n-left -1)) return num
maximum-69-number
Python 3 | Simple Math
sweetkimchi
0
1
maximum 69 number
1,323
0.821
Easy
19,772
https://leetcode.com/problems/maximum-69-number/discuss/2789082/Python3-Solution
class Solution: def maximum69Number (self, num: int) -> int: num=str(num) num=list(num) for i in range(0,len(num)): if(num[i]=='6'): num[i]='9' break num = ''.join(num) return int(num)
maximum-69-number
Python3 Solution
jayesh_s_patil
0
3
maximum 69 number
1,323
0.821
Easy
19,773
https://leetcode.com/problems/maximum-69-number/discuss/2789081/Python3-Solution
class Solution: def maximum69Number (self, num: int) -> int: num=str(num) num=list(num) for i in range(0,len(num)): if(num[i]=='6'): num[i]='9' break num = ''.join(num) return int(num)
maximum-69-number
Python3 Solution
jayesh_s_patil
0
2
maximum 69 number
1,323
0.821
Easy
19,774
https://leetcode.com/problems/maximum-69-number/discuss/2789027/Python3-oror-Easy-way
class Solution: def maximum69Number (self, num: int) -> int: n = list(str(num)) for i in range(len(n)): if n[i] == '6': n[i] = '9' break return int(''.join(n))
maximum-69-number
✅ Python3 || Easy way
PabloVE2001
0
5
maximum 69 number
1,323
0.821
Easy
19,775
https://leetcode.com/problems/maximum-69-number/discuss/2789026/Simple-Python-Solution
class Solution: def maximum69Number (self, num: int) -> int: s = list(str(num)) n = len(s) for i in range(n): if s[i] == '6': s[i] = '9' break; return int(''.join(s))
maximum-69-number
Simple Python Solution
mansoorafzal
0
3
maximum 69 number
1,323
0.821
Easy
19,776
https://leetcode.com/problems/maximum-69-number/discuss/2789005/Python
class Solution: def maximum69Number (self, num: int) -> int: res = [str(i) for i in list(str(num))] for i in range(len(res)): if res[i] != '9': res[i] = '9' break return int(''.join(res))
maximum-69-number
Python
JSTM2022
0
2
maximum 69 number
1,323
0.821
Easy
19,777
https://leetcode.com/problems/maximum-69-number/discuss/2788958/Well-Explained-or-100-True-Solution
class Solution: def maximum69Number (self, num: int) -> int: num=str(num) l=[i for i in num] for i in range(len(l)): if l[i]=='6': l[i]='9' break return ''.join(map(str,l))
maximum-69-number
Well Explained | 100% True Solution
wht_hats_ani56
0
2
maximum 69 number
1,323
0.821
Easy
19,778
https://leetcode.com/problems/maximum-69-number/discuss/2788924/Easy-to-understand-python-solution-O(n)-worst-case-time-complexity
class Solution: def maximum69Number (self, num: int) -> int: if set(str(num)) == {'9'}: return num list_num = list(str(num)) for i in range(len(list_num)): if list_num[i] == '6': list_num[i] = '9' break return int(''.join(list_num))
maximum-69-number
Easy to understand python solution, O(n) worst case time complexity
sheetalpatne
0
3
maximum 69 number
1,323
0.821
Easy
19,779
https://leetcode.com/problems/maximum-69-number/discuss/2788920/Solution-in-Python.
class Solution: def maximum69Number (self, num: int) -> int: lst_num = list(str(num)) for i in range(len(lst_num)): if lst_num[i] == '6': lst_num[i] = '9' break return int(''.join(lst_num))
maximum-69-number
Solution in Python.
ahti1405
0
3
maximum 69 number
1,323
0.821
Easy
19,780
https://leetcode.com/problems/print-words-vertically/discuss/1277233/python-94.44-or-easy-or-with-comments
class Solution: def printVertically(self, s: str) -> List[str]: st=0 # track of index to take element from each word s=s.split() ans=[] y=0 for i in s: y=max(y,len(i)) while st<y: u=[] for i in s: if st<len(i): u.append(i[st]) else: u.append(' ')# adding spaces if word length is less while u[-1]==' ': # using stack operation to remove trailing spaces u.pop() ans.append(''.join(u)) st+=1# increasing index at each iteration return ans
print-words-vertically
python 94.44% | easy | with comments
chikushen99
2
140
print words vertically
1,324
0.604
Medium
19,781
https://leetcode.com/problems/print-words-vertically/discuss/1184093/Python-Solution-oror-93.38-faster
class Solution: def printVertically(self, s: str) -> List[str]: t = s.split(' ') l = 0 for i in t: if l < len(i): l = len(i) final = [] i = 0 for j in range(l): st = '' for word in t: if i < len(word) and word[i]: st += word[i] else: st = st + ' ' while len(st) >= 0: if st[-1] == ' ': st = st[:-1] else: break i += 1 final.append(st) return final
print-words-vertically
Python Solution || 93.38% faster
KiranUpase
1
104
print words vertically
1,324
0.604
Medium
19,782
https://leetcode.com/problems/print-words-vertically/discuss/2845275/Stripping-and-processing-words
class Solution: def printVertically(self, s: str) -> List[str]: # split the words by spaces # find the longest word in s (how how elements in result array) # iterate through the words and add the characters to each row (to get column words) # use a pointer that indicates the position of the char in the word and the position to add the char into # the result array. If it's in bounds add the char otherwise add the space and increment # once done, iterate again and trim all leading spaces in the rows # time O(m * n) m = num of words n = word size O(n) words = s.split() maxlen = len(max(words, key=len)) res = [""] * maxlen for word in words: i = 0 while i < maxlen: if i < len(word): res[i] += word[i] else: res[i] += " " i += 1 for i in range(maxlen): res[i] = res[i].rstrip() return res
print-words-vertically
Stripping and processing words
andrewnerdimo
0
1
print words vertically
1,324
0.604
Medium
19,783
https://leetcode.com/problems/print-words-vertically/discuss/2792933/Print-Vertically
class Solution: def printVertically(self, s: str) -> List[str]: # s="TO BE OR NOT TO BE" l=s.split(' ') # print(l) maxlen=max(len(ele)for ele in l) # print(maxlen) m=[] for i in range(maxlen): str='' for word in l: if i>=len(word): str+=' ' else: str+=word[i] m.append(str.rstrip()) return m
print-words-vertically
Print Vertically
shivansh2001sri
0
1
print words vertically
1,324
0.604
Medium
19,784
https://leetcode.com/problems/print-words-vertically/discuss/2792859/Efficient-Solution-in-Python-oror-Easy-Understanding-oror-Optimized-Code
class Solution: def printVertically(self, s: str) -> List[str]: s = s.split(); maxlen = 0; j = 0; for i in s: maxlen = max(maxlen, len(i)); row = maxlen; col = len(s); matrix = [[" "]*col for i in range(row)]; for strr in s: n = len(strr); for i in range(n): matrix[i][j] = strr[i]; j += 1; finalstr = ["".join(substr).rstrip() for substr in matrix]; return finalstr
print-words-vertically
Efficient Solution in Python || Easy Understanding || Optimized Code
avinashdoddi2001
0
2
print words vertically
1,324
0.604
Medium
19,785
https://leetcode.com/problems/print-words-vertically/discuss/2790006/Python3-Solution-99.80-faster
class Solution: def printVertically(self, s: str) -> List[str]: words = s.split() lenWords = len(words) maxChars = 0 for i, val in enumerate(words): maxChars = max(len(val), maxChars) res = [[] for _ in range(maxChars)] for i in range(maxChars): for word in words: try: res[i].append(word[i]) except: res[i].append(' ') return [''.join(val).rstrip() for val in res]
print-words-vertically
[Python3] Solution, 99.80% faster
user8780Q
0
4
print words vertically
1,324
0.604
Medium
19,786
https://leetcode.com/problems/print-words-vertically/discuss/2788237/Simple-python-solution
class Solution: def printVertically(self, s: str) -> List[str]: ls = s.split() maxlen = -1 for a in ls: if len(a) > maxlen: maxlen = len(a) arr2D = [] for a in ls: innerarr = list(a) if len(a) < maxlen: for i in range(maxlen-len(a)): innerarr.append(' ') arr2D.append(innerarr) returnarr = [] for i in range(len(arr2D[0])): string = '' for j in range(len(arr2D)): string += arr2D[j][i] returnarr.append(string.rstrip()) return returnarr
print-words-vertically
Simple python solution
Tonmoy-saha18
0
3
print words vertically
1,324
0.604
Medium
19,787
https://leetcode.com/problems/print-words-vertically/discuss/2787923/Python-or-33ms-or-Beats-92-or-Single-For-Loop-or-Only-Built-In-Libraries
class Solution: def printVertically(self, s: str) -> List[str]: mat = [] i = 0 j = 0 for ch in s: if ch == ' ': i = 0 j += 1 continue if i == len(mat): mat.append([' ' for _ in range(j)]) for _ in range(j - len(mat[i])): mat[i].append(' ') mat[i].append(ch) i += 1 return [''.join(i) for i in mat]
print-words-vertically
Python | 33ms | Beats 92% | Single For Loop | Only Built-In Libraries
Aayush65
0
2
print words vertically
1,324
0.604
Medium
19,788
https://leetcode.com/problems/print-words-vertically/discuss/2787882/Python
class Solution: def printVertically(self, s: str) -> List[str]: x=s.split() n=0 for i in x: a=len(i) if a>n: n=a m=len(x) matrix=[] #print(m,n) for i in range(n): matrix.append([' ']*m) k=0 for i in range(m): for j in range(len(x[k])): matrix[j][i]=x[k][j] k+=1 res=[] for i in range(n): strr=''.join(matrix[i]) strr=strr.rstrip() res.append(strr) return res
print-words-vertically
Python
Chetan_007
0
3
print words vertically
1,324
0.604
Medium
19,789
https://leetcode.com/problems/print-words-vertically/discuss/2787854/python-solution
class Solution: def printVertically(self, s: str) -> List[str]: array = s.split(" ") maxLen = 0 for a in array: if len(a) > maxLen: maxLen = len(a) ans=[""]*maxLen for i in range(maxLen): for j in array: if(i>=len(j)): ans[i]+=' ' else: ans[i]+=j[i] for i in range(len(ans)): ans[i]=ans[i].rstrip() return ans
print-words-vertically
python solution
Nileshsingh08
0
1
print words vertically
1,324
0.604
Medium
19,790
https://leetcode.com/problems/print-words-vertically/discuss/2712058/Runtime-O(total-words-*-max-word-length)
class Solution: def printVertically(self, s: str) -> List[str]: arr = s.split(" "); length = len(max(arr, key=len)) ans = [""] * length; for i in range(0, len(arr)): word = arr[i]; for j in range(0, length): if j >= len(arr[i]): ans[j] += " "; continue; ans[j] += word[j]; return [ans[i].rstrip() for i in range(length)];
print-words-vertically
Runtime O(total words * max word length)
Jaykant111
0
1
print words vertically
1,324
0.604
Medium
19,791
https://leetcode.com/problems/print-words-vertically/discuss/2508011/easy-python-solution
class Solution: def printVertically(self, s: str) -> List[str]: max_len = max([len(word) for word in s.split(' ')]) words = s.split(' ') output = [] for i in range(max_len) : val, flag = "", True for word in words : if i >= len(word) : val += " " else : if flag : space_count = len(val) flag = False val += word[i] if val[-1] == ' ' : val = ' '*space_count + val.strip() output.append(val) return output
print-words-vertically
easy python solution
sghorai
0
16
print words vertically
1,324
0.604
Medium
19,792
https://leetcode.com/problems/print-words-vertically/discuss/2110968/Python-Solution
class Solution: def printVertically(self, s: str) -> List[str]: #s = "TO BE OR NOT TO BE" #Output: ["TBONTB","OEROOE"," T"] s = s.split(" ") length = max([len(item) for item in s]) temp = [] for i in range(0,length): current = "" for j in range(0,len(s)): try: current += s[j][i] except: current += " " current = self.reduce(current) temp.append(current) return temp def reduce(self,current): while current[-1] == " ": current = current[0:-1] return current
print-words-vertically
Python Solution
xevb
0
29
print words vertically
1,324
0.604
Medium
19,793
https://leetcode.com/problems/print-words-vertically/discuss/2103265/python-3-oror-simple-solution
class Solution: def printVertically(self, s: str) -> List[str]: words = s.split() maxLen = max(map(len, words)) verticals = [] for i in range(maxLen): vertical = [] for word in words: vertical.append(word[i] if i < len(word) else ' ') verticals.append(''.join(vertical).rstrip()) return verticals
print-words-vertically
python 3 || simple solution
dereky4
0
35
print words vertically
1,324
0.604
Medium
19,794
https://leetcode.com/problems/print-words-vertically/discuss/1701890/Python-simple-solution
class Solution: def printVertically(self, s: str) -> List[str]: words = s.split(' ') n = len(words) m = 0 for w in words: m = max(m, len(w)) res = [[" " for _ in range(n)] for _ in range(m)] for j in range(n): word = words[j] for i in range(len(word)): res[i][j] = word[i] return ["".join(x).rstrip() for x in res]
print-words-vertically
Python simple solution
byuns9334
0
144
print words vertically
1,324
0.604
Medium
19,795
https://leetcode.com/problems/print-words-vertically/discuss/1413347/nearly-1-liner-in-Python-3-using-itertools.zip_longest
class Solution: def printVertically(self, s: str) -> List[str]: from itertools import zip_longest return list(''.join(k).rstrip() for k in zip_longest(*s.split(), fillvalue=' '))
print-words-vertically
nearly 1-liner in Python 3, using itertools.zip_longest
mousun224
0
79
print words vertically
1,324
0.604
Medium
19,796
https://leetcode.com/problems/print-words-vertically/discuss/1325235/Python3-beats-99-comments-in-code
class Solution: def printVertically(self, s: str) -> List[str]: words = s.split() # split into words for convenience ans = [] for i in range(len(words)): wordlen = len(words[i]) # length of word in question if wordlen > len(ans): # if the length of this word is longer than the length of ans, then: # we need to add the appropriate number of strings to ans so that we can fit this word vertically for k in range(wordlen-len(ans)): ans.append(' '*i) # the strings we add has to have an appropriate number of blank spaces for j in range(len(words[i])): # loop to add the characters to the strings in ans ans[j] += (' '*(i-len(ans[j]))) + words[i][j] # ' '*(i-len(ans[j])) is to add an appropriate number of blanks in case the word before was shorter than the current word return ans
print-words-vertically
Python3 beats 99%, comments in code
knguyen06
0
121
print words vertically
1,324
0.604
Medium
19,797
https://leetcode.com/problems/print-words-vertically/discuss/1302937/Python3-Simple-solution-faster-than-94-submissions
class Solution: def printVertically(self, s: str) -> list: splits = s.split(' ') max_index = len(max(s.split(' '), key=lambda s:len(s))) vertical = [] vertical_str = '' for index in range(0, max_index): for split in splits: if index >= len(split): vertical_str+=' ' else: char = split[index] vertical_str += char vertical_str = vertical_str.rstrip() vertical.append(vertical_str) vertical_str = '' return vertical
print-words-vertically
[Python3] Simple solution, faster than 94% submissions
GauravKK08
0
54
print words vertically
1,324
0.604
Medium
19,798
https://leetcode.com/problems/print-words-vertically/discuss/1113477/Python-clear-short-pythonic
class Solution: def printVertically(self, s: str) -> List[str]: s = s.split() output = [] for key in range(len(max(s, key=len))): output.append(''.join(s[x][key] if len(s[x]) > key else ' ' for x in range(len(s))).rstrip()) return output
print-words-vertically
[Python], clear, short, pythonic
cruim
0
95
print words vertically
1,324
0.604
Medium
19,799