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/print-words-vertically/discuss/979823/Intuitive-approach-by-using-dict-and-scanning
class Solution: def printVertically(self, s: str) -> List[str]: lines = s.split() max_length, num_line = max(map(lambda e: len(e), lines)), len(lines) vert_dict = {i:[] for i in range(max_length)} for line in lines: # Make sure each line is of same length line += " " * (max_length - len(line)) for i, c in enumerate(line): vert_dict[i].append(c) vert_lines = ["".join(vert_dict[i]).rstrip() for i in range(len(vert_dict))] return list(filter(lambda e: e, vert_lines))
print-words-vertically
Intuitive approach by using dict and scanning
puremonkey2001
0
28
print words vertically
1,324
0.604
Medium
19,800
https://leetcode.com/problems/print-words-vertically/discuss/598667/Simple-Python-Solution-Runtime-28ms
class Solution: def printVertically(self, s: str) -> List[str]: x=s.split(" ") print(x) result=[] ml=0 mi=0 for i in range(len(x)): if len(x[i])>ml: ml=len(x[i]) mi=i print(ml) print(mi) for i in range(ml): y="" for j in range(len(x)): if i>=len(x[j]): y+=" " else: y+=x[j][i] result.append(y) fresult=[] for i in range(len(result)): fresult.append(result[i].rstrip()) return fresult print(result)
print-words-vertically
Simple Python Solution Runtime- 28ms
Ayu-99
0
110
print words vertically
1,324
0.604
Medium
19,801
https://leetcode.com/problems/print-words-vertically/discuss/594919/Python-3-(matrix)
class Solution(object): def printVertically(self, s): """ :type s: str :rtype: List[str] """ words = s.split(" ") height = max([len(x) for x in words]) width = len(words) matrix = [[' ' for i in range(width)] for j in range(height)] row, col = 0, 0 for x in words: for ch in x: matrix[row][col] = ch row += 1 row = 0 col += 1 res = [] for x in matrix: res.append("".join(x).rstrip()) return res
print-words-vertically
Python 3 (matrix)
ermolushka2
0
85
print words vertically
1,324
0.604
Medium
19,802
https://leetcode.com/problems/print-words-vertically/discuss/492082/Python3-Transpose
class Solution: def printVertically(self, s: str) -> List[str]: words = s.split() m, n = len(words), max(map(len, words)) ans = [[" "]*m for _ in range(n)] for i in range(m): for j in range(len(words[i])): ans[j][i] = words[i][j] return ["".join(x).rstrip() for x in ans]
print-words-vertically
[Python3] Transpose
ye15
0
56
print words vertically
1,324
0.604
Medium
19,803
https://leetcode.com/problems/print-words-vertically/discuss/484370/Python-3-(beats-100)-(two-lines)
class Solution: def printVertically(self, s: str) -> List[str]: A, S = [], s.split() M = max(map(len,S)) for i in range(M): c = '' for s in S: c += ' ' if i >= len(s) else s[i] A.append(c.rstrip()) return A
print-words-vertically
Python 3 (beats 100%) (two lines)
junaidmansuri
0
178
print words vertically
1,324
0.604
Medium
19,804
https://leetcode.com/problems/print-words-vertically/discuss/484370/Python-3-(beats-100)-(two-lines)
class Solution: def printVertically(self, s: str) -> List[str]: M = max(map(len,s.split())) return [''.join(v).rstrip() for v in map(''.join,zip(*[s+' '*(M-len(s)) for s in s.split()]))] - Junaid Mansuri - Chicago, IL
print-words-vertically
Python 3 (beats 100%) (two lines)
junaidmansuri
0
178
print words vertically
1,324
0.604
Medium
19,805
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/484504/Python-3-(beats-100)-(five-lines)-(recursive)
class Solution: def removeLeafNodes(self, R: TreeNode, t: int) -> TreeNode: def RLN(R): if R == None: return None R.left, R.right = RLN(R.left), RLN(R.right) return None if R.val == t and R.left == R.right else R return RLN(R) - Junaid Mansuri - Chicago, IL
delete-leaves-with-a-given-value
Python 3 (beats 100%) (five lines) (recursive)
junaidmansuri
2
302
delete leaves with a given value
1,325
0.747
Medium
19,806
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/2220062/python-3-or-simple-dfs
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: def helper(root): if root is None: return True left, right = helper(root.left), helper(root.right) if left: root.left = None if right: root.right = None return left and right and root.val == target return root if not helper(root) else None
delete-leaves-with-a-given-value
python 3 | simple dfs
dereky4
1
50
delete leaves with a given value
1,325
0.747
Medium
19,807
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/485021/Python3-super-simple-recursive-solution
class Solution: def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if not root: return root root.left = self.removeLeafNodes(root.left, target) root.right = self.removeLeafNodes(root.right, target) if root.val == target and not root.left and not root.right: return return root
delete-leaves-with-a-given-value
Python3 super simple recursive solution
jb07
1
36
delete leaves with a given value
1,325
0.747
Medium
19,808
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/2725430/Python-Solution-or-Easy-to-Understand
class Solution(object): def removeLeafNodes(self, root, target): def deleteNode(root, t): flag = False if root.val == t and root.left is None and root.right is None: self.flag2 = True return False q = deque() q.append(root) while q: for _ in range(len(q)): p = q.popleft() if p.left: if p.left.val == t and p.left.left is None and p.left.right is None: p.left = None flag = True else: q.append(p.left) if p.right: if p.right.val == t and p.right.left is None and p.right.right is None: p.right = None flag = True else: q.append(p.right) return flag self.flag2 = False delete = True while delete: delete = deleteNode(root, target) if self.flag2: return None return root
delete-leaves-with-a-given-value
Python Solution | Easy to Understand
its_krish_here
0
6
delete leaves with a given value
1,325
0.747
Medium
19,809
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/2698444/Python3-Simple-Solution
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: def DFS(r): if r: r.left = DFS(r.left) r.right = DFS(r.right) if not r.left and not r.right and r.val == target: return None return r else: return None return DFS(root)
delete-leaves-with-a-given-value
Python3 Simple Solution
mediocre-coder
0
4
delete leaves with a given value
1,325
0.747
Medium
19,810
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/2640993/Python3-Faster-than-85-oror-Recursive-Solution-oror-Using-DFS
class Solution: def removeLeafNodes(self, root: Optional[TreeNode],t: int) -> Optional[TreeNode]: def solve(root): if not root: return None root.left = solve(root.left) root.right = solve(root.right) if root.left == None and root.right == None and t == root.val: return None return root return solve(root) #Please Upvote if you understand the solution...
delete-leaves-with-a-given-value
Python3 Faster than 85% || Recursive Solution || Using DFS
hoo__mann
0
16
delete leaves with a given value
1,325
0.747
Medium
19,811
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/2539330/Python-Clear-but-Concise-DFS
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: # go into the tree and return root if still there return None if dfs(root, target) else root def dfs(node, target): # if node is None we return false # as it has not been deleted # 1) stop condition if node is None: return False # dig deeper into the tree # 2) no logic before traversal necessary delete_left = dfs(node.left, target) delete_right = dfs(node.right, target) # delete nodes if they want it # 3) logic after information about subtree if delete_left: node.left = None if delete_right: node.right = None # check whether we need to be deleted # 4) return value creation if node.val == target and node.left is None and node.right is None: return True return False
delete-leaves-with-a-given-value
[Python] - Clear but Concise DFS
Lucew
0
15
delete leaves with a given value
1,325
0.747
Medium
19,812
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/2419754/Python-plain-DFS
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: def dfs(node): if not node: return None node.left = dfs(node.left) node.right = dfs(node.right) if not node.left and not node.right and node.val == target: return None return node return dfs(root)
delete-leaves-with-a-given-value
Python plain DFS
Abhi_009
0
28
delete leaves with a given value
1,325
0.747
Medium
19,813
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/2337330/Python-simple-dfs-solution-(time-space-optimized)
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: res = 0 def dfs(node): nonlocal target nonlocal res if not node: return None if node: node_left = dfs(node.left) node_right = dfs(node.right) if not node_left: node.left = None if not node_right: node.right = None if not node_left and not node_right and node.val == target: return None return node dfs(root) if root.val == target and not root.left and not root.right: return None return root
delete-leaves-with-a-given-value
Python simple dfs solution (time, space optimized)
byuns9334
0
36
delete leaves with a given value
1,325
0.747
Medium
19,814
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/2315525/Python3-Postorder-traversal
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: def remove(root): if not root: return None root.left = remove(root.left) root.right = remove(root.right) if not root.left and not root.right and root.val == target: return None return root return remove(root)
delete-leaves-with-a-given-value
[Python3] Postorder traversal
Gp05
0
14
delete leaves with a given value
1,325
0.747
Medium
19,815
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/2064118/Simple-Python-Post-Order-Traversal-2-Pass-(Mark%2BDelete)
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: # mark nodes for deletion. Use post-order traversal to look whether the children are marked to be deleted delete = defaultdict(lambda: False) def recMark(node): if node: recMark(node.left) recMark(node.right) if node.val == target and ((not node.left or delete[node.left]) and (not node.right or delete[node.right])): delete[node] = True recMark(root) # delete nodes. Use dummy root to handle cases where we need to delete the root def recDelete(node): if node: if delete[node.left]: node.left = None else: recDelete(node.left) if delete[node.right]: node.right = None else: recDelete(node.right) dummy_root = TreeNode(0, root) recDelete(dummy_root) return dummy_root.left
delete-leaves-with-a-given-value
Simple Python, Post-Order Traversal, 2 Pass (Mark+Delete)
boris17
0
29
delete leaves with a given value
1,325
0.747
Medium
19,816
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/1526105/Python-DFS-Faster-Than-90
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: def removeLeafNodeDFS(node, target): removeLeft, removeRight = True, True if node.left is None and node.right is None: if node.val == target: return True return False if node.left: removeLeft = removeLeafNodeDFS(node.left, target) if node.right: removeRight = removeLeafNodeDFS(node.right, target) if removeLeft and removeRight and node.val == target: node.left = None node.right = None return True if removeLeft: node.left = None if removeRight: node.right = None return False removeWholeTree = removeLeafNodeDFS(root, target) if removeWholeTree: return None return root
delete-leaves-with-a-given-value
Python DFS Faster Than 90%
peatear-anthony
0
111
delete leaves with a given value
1,325
0.747
Medium
19,817
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/1481755/Python-Clean-Postorder-DFS
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: def delete(node = root): if not node: return None L, R = delete(node.left), delete(node.right) if not (L or R) and (node.val == target): return None node.left, node.right = L, R return node return delete()
delete-leaves-with-a-given-value
[Python] Clean Postorder DFS
soma28
0
66
delete leaves with a given value
1,325
0.747
Medium
19,818
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/1408407/Python3-Two-recursive-solution-with-results
class Solution: def traversal(self, node, target): if node == None : return False l = self.traversal(node.left, target) if not l: node.left = None r = self.traversal(node.right, target) if not r: node.right = None if not l and not r and node.val == target: return False return True def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: if self.traversal(root, target): return root return None
delete-leaves-with-a-given-value
[Python3] Two recursive solution with results
maosipov11
0
46
delete leaves with a given value
1,325
0.747
Medium
19,819
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/1408407/Python3-Two-recursive-solution-with-results
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: if root == None: return None root.left = self.removeLeafNodes(root.left, target) root.right = self.removeLeafNodes(root.right, target) if root.val != target or root.left or root.right: return root return None
delete-leaves-with-a-given-value
[Python3] Two recursive solution with results
maosipov11
0
46
delete leaves with a given value
1,325
0.747
Medium
19,820
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/1317022/Intuition-and-Post-Order-recursive-Python-Solution-clean-6liner-5liner-...-2liner
class Solution: def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if not root: return None if root.left: root.left = self.removeLeafNodes(root.left, target) if root.right: root.right = self.removeLeafNodes(root.right, target) # I am leaf node - - - - - - - - - and I have value target if not root.left and not root.right and root.val == target: return None return root def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if not root: return None root.left = self.removeLeafNodes(root.left, target) root.right = self.removeLeafNodes(root.right, target) # I am leaf node - - - - - - - - - and I have value target if not root.left and not root.right and root.val == target: return None return root def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if root: root.left = self.removeLeafNodes(root.left, target) root.right = self.removeLeafNodes(root.right, target) # I am leaf node - - - - - - - - - and I have value target if not root.left and not root.right and root.val == target: return None return root def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if root: root.left, root.right = self.removeLeafNodes(root.left, target), self.removeLeafNodes(root.right, target) # I am leaf node - - - - - - - - - and I have value target if not root.left and not root.right and root.val == target: return None return root def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if root: root.left, root.right = self.removeLeafNodes(root.left, target), self.removeLeafNodes(root.right, target) # Null if I am leaf node - - - - - - - - - and I have value target return None if (root and not root.left and not root.right and root.val == target) else root
delete-leaves-with-a-given-value
Intuition & Post Order recursive Python Solution, clean 6liner, 5liner, ... 2liner
yozaam
0
29
delete leaves with a given value
1,325
0.747
Medium
19,821
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/836382/python-easy-recursive-code-2-solutions
class Solution: def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: def helper(node, target): if node.left: node.left = helper(node.left, target) if node.right: node.right = helper(node.right, target) return None if node.left == node.right == None and node.val == target else node return helper(root,target)
delete-leaves-with-a-given-value
python easy recursive code 2 solutions
akashgkrishnan
0
64
delete leaves with a given value
1,325
0.747
Medium
19,822
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/765943/Simple-Python-DFS-Recursion
class Solution: # Time: O(n) # Space: O(h) def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if self.dfs(root, target): return None return root def dfs(self, node, target): if not node: return False if self.dfs(node.left, target): node.left = None if self.dfs(node.right, target): node.right = None if not node.left and not node.right and node.val == target: return True return False
delete-leaves-with-a-given-value
Simple Python DFS Recursion
whissely
0
130
delete leaves with a given value
1,325
0.747
Medium
19,823
https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/485514/Python3-Recursion-Solution
class Solution: def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: def helper(node): if node: node.left = helper(node.left) node.right = helper(node.right) if not node.left and not node.right and node.val == target: return None else: return node return helper(root)
delete-leaves-with-a-given-value
Python3 Recursion Solution
nightybear
0
42
delete leaves with a given value
1,325
0.747
Medium
19,824
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/484299/Python-%3A-O(N)
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: jumps = [0]*(n+1) for i in range(n+1): l, r = max(0,i-ranges[i]), min(n,i+ranges[i]) jumps[l] = max(jumps[l],r-l) step = start = end = 0 while end < n: start, end = end+1, max(i+jumps[i] for i in range(start, end+1)) if start > end: return -1 step += 1 return step
minimum-number-of-taps-to-open-to-water-a-garden
Python : O(N)
fallenranger
22
2,500
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,825
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/1593681/Python3Java-Greedy-O(n)-or-Explanation
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: taps = [0] * len(ranges) for i,r in enumerate(ranges): left = max(0, i - r) taps[left] = max(taps[left], i + r) total = reach = nextReach = 0 for i, r in enumerate(taps): nextReach = max(nextReach, r) if i == reach: if nextReach == reach: return -1 total += 1 reach = nextReach if (nextReach >= n): break return total
minimum-number-of-taps-to-open-to-water-a-garden
[Python3/Java] Greedy O(n) | Explanation
mardlucca
6
539
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,826
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/1110610/Simple-and-easy-to-understand.
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: start, end = 0, 0 taps = 0 while end< n: for i in range(len(ranges)): if i-ranges[i] <= start and i+ ranges[i]>end: end = i + ranges[i] if start == end: return -1 taps +=1 start = end return taps
minimum-number-of-taps-to-open-to-water-a-garden
Simple and easy to understand.
avanishtiwari
6
1,000
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,827
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/2411492/python-dp-solution-(extended-jump-game-II)
class Solution: def minTaps(self, n: int, arr: List[int]) -> int: #make array 'dp' to perform jump game II dp = [0]*(n+1) for i in range(n+1) : idxl = max(0, i-arr[i]) idxr = min(n, i+arr[i]) dp[idxl] = max(dp[idxl], idxr-idxl) # Now just implement jump game II if dp[0] == 0 : return -1; jump = dp[0] currjump = dp[0] res = 1 for i in range(1, n+1) : currjump = max(currjump-1, dp[i]) jump -= 1 if jump == 0 and i != n : res += 1 jump = currjump if jump == 0 and i < n : return -1 return res
minimum-number-of-taps-to-open-to-water-a-garden
python dp solution (extended jump game II)
runtime-terror
1
202
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,828
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/1460070/Python3-O(n)-Jump-Game-II-with-comments
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: # Convert to right sided sprinklers # Instead of picturing sprinklers at the center of their range # picture them at the left most possible position in their range for i in range(len(ranges)): r = ranges[i] # Remove the sprinkler from its current position ranges[i] = 0 left_placement = max(0, i - r) right_range = i + r - left_placement # If multiple sprinklers are compteing for same spot # we ignore all except the sprinkler with the max range ranges[left_placement] = max(ranges[left_placement], right_range) # Ranges has now been converted to the same format as Jump Game II # Similar to https://leetcode.com/problems/jump-game-ii/ max_reach = jump_limit = jumps = 0 for pos in range(len(ranges)): if pos > max_reach: return -1 if pos > jump_limit: jump_limit = max_reach jumps += 1 max_reach = max(max_reach, pos + ranges[pos]) return jumps
minimum-number-of-taps-to-open-to-water-a-garden
[Python3] [O(n)] Jump Game II with comments
mmonitor
1
300
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,829
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/1449220/python3-clean-solution
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: dp = [0] + [n + 1] * n for i, x in enumerate(ranges): for j in range(max(i - x, 0), min(i + x, n)): dp[j + 1] = min(dp[j + 1], dp[max(0, i - x)] + 1) return dp[n] if dp[n] < n + 1 else -1
minimum-number-of-taps-to-open-to-water-a-garden
python3 clean solution
BichengWang
1
224
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,830
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/1443915/Python3-Explained-Simple-Greedy-Solution
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: ml=0 #minimum_left mr=0 #maximum_right taps=0 while mr<n: for i in range(n+1): if i-ranges[i]<=ml and i+ranges[i]>=mr: mr=i+ranges[i] if ml==mr: #if minimum==maximum even after scanning the whole array means there is some interval which cannot be covered because if it was possible maximum would have updated itself. return -1 taps+=1 ml=mr return taps
minimum-number-of-taps-to-open-to-water-a-garden
[Python3] Explained Simple Greedy Solution
swapnilsingh421
1
215
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,831
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/2592657/Python-or-NOoOb-or-Flipkart-or-DP-or-Recursion-or-JUst-look-once-or
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: memo = {} def dp(area,idx,left,right): if idx>n: if left<=0 and right>=n: return 0 else: return 999999999 elif right<area[idx][0]: return 999999999 elif (idx,left,right) in memo: return memo[(idx,left,right)] else: memo[(idx,left,right)] = min(dp(area,idx+1,min(left,area[idx][0]),max(right,area[idx][1]))+1,dp(area,idx+1,left,right)) return memo[(idx,left,right)] area = [] for i in range(len(ranges)): x = i-ranges[i] if x<=0: x = 0 area.append([x,i+ranges[i] if i+ranges[i]<=n else n]) area.sort() ans = dp(area,0,0,0) return ans if ans<999999999 else -1
minimum-number-of-taps-to-open-to-water-a-garden
Python | NOoOb | Flipkart | DP | Recursion | JUst look once |
Brillianttyagi
0
78
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,832
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/1916157/Python-3-O(n)-Greedy-solution
class Solution: def minTaps(self, n: int, A: List[int]) -> int: dic={} for i,j in enumerate(A): k=max(0,i-j) v=min(n,j+i) dic[k]=max(v,dic.get(i,0)) #print(dic) if 0 not in dic: return -1 max_len=dic[0] if max_len==n: return 1 ans=1 curr_max=max_len for i in range(1,len(A)): if i > max_len: return -1 curr_max=max(curr_max,dic.get(i,0)) if curr_max==n: return ans+1 if i==max_len: ans+=1 max_len=curr_max
minimum-number-of-taps-to-open-to-water-a-garden
Python 3, O(n) Greedy solution
amit_upadhyay
0
202
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,833
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/1870624/Python-or-Greedy
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: arr=[] #1. Adding the ranges in arr for i in range(len(ranges)): arr.append([i-ranges[i],i+ranges[i]]) #2. Sorting the arr with smallest first and if same small element then largest first i.e. [1,2],[1,1] arr.sort(key=lambda item:(item[0],-item[1])) i=0 maxy=-inf maxind=0 #3.Initial search for the elements that covers 0 and has longest right coordinate range while i<=n and arr[i][0]<=0: if arr[i][1]>=maxy: maxy=arr[i][1] maxind=i i+=1 i=maxind cnt=1 if maxy!=-inf and maxy>=n:#Incase we cover all range then return 1 return cnt while i<=n: a,b=arr[i] j=i+1 maxy=-inf maxind=i while j<=n:#Iterating through all the elements that intersect with the current a,b and has longest range p,q=arr[j] if q>=a and p<=b: if q>=maxy: maxy=q maxind=j j+=1 else: break cnt+=1 if maxy>=n:#If we reach the end or more than that return cnt if maxy==-inf or maxy<=b:#If we can't go beyond our b return -1 else: i=maxind return -1
minimum-number-of-taps-to-open-to-water-a-garden
Python | Greedy
heckt27
0
130
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,834
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/1540360/153-ms-faster-than-68.51-of-Python3-Easy-for-beginers
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: res = 0 tmp = [] for i in range(len(ranges)): tmp.append([i - ranges[i] ,i + ranges[i]]) l ,r, j = 0, 0, 0 tmp.sort() while r < n and j < len(tmp): res += 1 l = r while r < n and j < len(tmp) and l >= tmp[j][0]: r = max(r, tmp[j][1]) j += 1 if l == r: return -1 return res
minimum-number-of-taps-to-open-to-water-a-garden
153 ms, faster than 68.51% of Python3 Easy for beginers
zixin123
0
287
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,835
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/927242/Python-Intuitive-and-clean-solution-O(N-log-N)
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: intervals = [] for i in range(len(ranges)): intervals.append([i-ranges[i] if i-ranges[i] >= 0 else 0,i+ranges[i]]) intervals.sort() max_range = next_max_range = cnt = i = 0 while i < len(intervals): if max_range >= n: return cnt if intervals[i][0] <= max_range: while i < len(intervals) and intervals[i][0] <= max_range: next_max_range = max(next_max_range, intervals[i][1]) i += 1 else: return -1 max_range = next_max_range cnt += 1 return cnt
minimum-number-of-taps-to-open-to-water-a-garden
[Python] Intuitive and clean solution - O(N log N)
vasu6
0
199
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,836
https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/1511651/Swipe-line-fast-solution
class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: intervals = [(0, ranges[0])] for i in range(1, n + 1): l, r = max(i - ranges[i], 0), i + ranges[i] if intervals[-1][1] < r: while intervals and intervals[-1][0] >= l: intervals.pop() if not intervals: intervals.append((l, r)) elif intervals[-1][1] < n and l <= intervals[-1][1]: intervals.append((intervals[-1][1], r)) return len(intervals) if intervals[-1][1] >= n else -1
minimum-number-of-taps-to-open-to-water-a-garden
Swipe line fast solution
BichengWang
-1
142
minimum number of taps to open to water a garden
1,326
0.477
Hard
19,837
https://leetcode.com/problems/break-a-palindrome/discuss/846873/Python-3-or-Greedy-one-pass-or-Explanations
class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(palindrome) if n == 1: return '' for i, c in enumerate(palindrome): if c != 'a' and ((i != n // 2 and n % 2) or not n % 2): return palindrome[:i] + 'a' + palindrome[i+1:] else: return palindrome[:-1] + 'b'
break-a-palindrome
Python 3 | Greedy one pass | Explanations
idontknoooo
7
1,300
break a palindrome
1,328
0.531
Medium
19,838
https://leetcode.com/problems/break-a-palindrome/discuss/2415118/Python-easy-to-read-and-understand-or-greedy
class Solution: def breakPalindrome(self, s: str) -> str: n = len(s) if n == 1: return '' for i in range(n//2): if s[i] != 'a': return s[:i] + 'a' + s[i+1:] return s[:-1] + 'b'
break-a-palindrome
Python easy to read and understand | greedy
sanial2001
4
700
break a palindrome
1,328
0.531
Medium
19,839
https://leetcode.com/problems/break-a-palindrome/discuss/489748/Clean-Python-3-three-lines
class Solution: def breakPalindrome(self, palindrome: str) -> str: for i in range(len(palindrome) // 2): if palindrome[i] != 'a': return palindrome[:i] + 'a' + palindrome[i+1:] return '' if len(palindrome) == 1 else palindrome[:-1] + 'b'
break-a-palindrome
Clean Python 3 three lines
lenchen1112
4
623
break a palindrome
1,328
0.531
Medium
19,840
https://leetcode.com/problems/break-a-palindrome/discuss/2685519/Python-Elegant-and-Short
class Solution: """ Time: O(n) Memory: O(n) """ def breakPalindrome(self, palindrome: str) -> str: if len(palindrome) == 1: return '' n = len(palindrome) letters = list(palindrome) for i in range(n // 2): if letters[i] > 'a': letters[i] = 'a' break else: letters[-1] = 'b' return ''.join(letters)
break-a-palindrome
Python Elegant & Short
Kyrylo-Ktl
2
39
break a palindrome
1,328
0.531
Medium
19,841
https://leetcode.com/problems/break-a-palindrome/discuss/2362114/Python
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome) == 1: return "" for i in range(len(palindrome)//2): if palindrome[i] != 'a': return palindrome[:i] + 'a' + palindrome[i+1:] return palindrome[:-1] + 'b'
break-a-palindrome
Python
blue_sky5
2
489
break a palindrome
1,328
0.531
Medium
19,842
https://leetcode.com/problems/break-a-palindrome/discuss/1364895/python-or-better-than-95-orsimple
class Solution: def breakPalindrome(self, palindrome: str) -> str: n=len(palindrome) if n==1: return "" if n%2==0: for j,i in enumerate(palindrome): if i!="a": return palindrome[:j]+"a"+palindrome[j+1:] return palindrome[:-1]+"b" else: for j,i in enumerate(palindrome): if j!=n//2 and i!="a": return palindrome[:j]+"a"+palindrome[j+1:] return palindrome[:-1]+"b"
break-a-palindrome
python | better than 95% |simple
heisenbarg
2
354
break a palindrome
1,328
0.531
Medium
19,843
https://leetcode.com/problems/break-a-palindrome/discuss/492301/Python-3-(three-lines)-(beats-~99)
class Solution: def breakPalindrome(self, P: str) -> str: for i in range(len(P)//2): if P[i] != 'a': return P[:i]+'a'+P[i+1:] return P[:-1]+'b' if len(P) > 1 else '' - Junaid Mansuri - Chicago, IL
break-a-palindrome
Python 3 (three lines) (beats ~99%)
junaidmansuri
2
615
break a palindrome
1,328
0.531
Medium
19,844
https://leetcode.com/problems/break-a-palindrome/discuss/2687643/Python-oror-Simple-and-fast-oror-Beats-95.7
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome)==1: # Only case where we cannot replace a character to make it "not a plaindrome" return '' palindrome = list(palindrome) for i in range(len(palindrome)//2): # We only have to check for half of the string because the rest will be exactly the same if palindrome[i] != 'a': # First character that is not 'a' will be replace with 'a' to give lexicographically smallest palindrome[i] = 'a' return ''.join(palindrome) # Here we can also use string slicing, but using a list then .join() is faster else: ''' Suppose we are not able to find a character that is not 'a' in the first half Ex: aaabaaa. Then simply change the last character with 'b' ''' palindrome[-1]='b' return ''.join(palindrome)
break-a-palindrome
Python || Simple and fast || Beats 95.7%
Graviel77
1
43
break a palindrome
1,328
0.531
Medium
19,845
https://leetcode.com/problems/break-a-palindrome/discuss/2687311/C%2B%2B-solution-beats-100-in-time-or-Python-solution-or-greedy-solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: palindrome=list(palindrome) for i in range(int(len(palindrome)/2)): if palindrome[i]!="a": palindrome[i]='a' return "".join(palindrome) palindrome[len(palindrome)-1] = 'b' if len(palindrome)>1: return "".join(palindrome) else: return ""
break-a-palindrome
✅C++ solution [beats 100% in time] | ☑️ Python solution | [greedy solution]
crimsonKn1ght
1
10
break a palindrome
1,328
0.531
Medium
19,846
https://leetcode.com/problems/break-a-palindrome/discuss/2685737/python-solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome)==1: return "" n, m = len(palindrome)-1, len(palindrome) while n>=0 and palindrome[n] == "a": n-=1 if n >= 0 and (m%2==0 or n!=m//2): palindrome = palindrome[:m-n-1]+"a"+palindrome[m-n:] else: palindrome = palindrome[:m-1]+"b" return palindrome
break-a-palindrome
python solution
tesfish
1
10
break a palindrome
1,328
0.531
Medium
19,847
https://leetcode.com/problems/break-a-palindrome/discuss/2685006/Python-or-Step-by-Step-Explanation-or-Intuition-and-Optimaization
class Solution: def breakPalindrome(self, palindrome: str) -> str: n=len(palindrome) # if its only any single letter we cant replace it still and make it non-palindrome # so just return empty string if n==1: return "" # to get lexographilcally smallest non palindrome # we have to observe that it would be contain 'a' first # but if its already have 'a' initially then # the next non-'a' would be replaced with 'a' st="" for i in range(n): if palindrome[i]!='a': st+='a' st+=palindrome[i+1:] if st!=st[::-1]: return st else: break st+=palindrome[i] # but what if all are already 'a' 'aaaaaa' # we need to change last letter with 'b' while still making it smallest lexographically return palindrome[:-1]+'b' # WITHOUT EXTRA SPACE # instead of using extra space for 'st' # what was corner case was that 'aba' # when we changed b it became palindrome 'aaa' # so with using extra space we had to check if it was palindrom or not # but if we just check upto half of that string we could avoid that condition # as it will conclude either that if we traverse upto half and no change is there # it means either whole string is 'aaaa' or middle character is non-'a' # in both case we have to change then last character only # so we can ignore the condition with just taking loop upto n//2-1 # and remove that st and its palindrome check n=len(palindrome) if n==1: return '' for i in range(n//2): if palindrome[i]!='a': return palindrome[:i]+'a'+palindrome[i+1:] # if conditions are 'aabaa' or 'aaaa' change last character with b return palindrome[:-1]+'b'
break-a-palindrome
Python | Step by Step Explanation | Intuition and Optimaization
varun21vaidya
1
43
break a palindrome
1,328
0.531
Medium
19,848
https://leetcode.com/problems/break-a-palindrome/discuss/2684423/PYTHON-or-SIMPLE-SOLUTION-WITH-EXPLANATION..
class Solution: def breakPalindrome(self, s: str) -> str: #checking for palindrome... def palin(s): i=0 j=len(s)-1 while i<j: if s[i]==s[j]: i+=1 j-=1 else: return False return True #stats..................... if len(s)==1: return "" else: # st=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] x="" for i in range(len(s)): if s[i]!="a": #changing the current element with a x=s[:i]+"a"+s[i+1:] #checking palindrome after changing if palin(x): continue else: return x #if it is still palindrome then change the last letter....👍 if palin(x): return s[:-1]+"b" #HAPPY CODING...🥳🥳🥳🥳🥳
break-a-palindrome
PYTHON | SIMPLE SOLUTION WITH EXPLANATION..❤️
narendra_036
1
48
break a palindrome
1,328
0.531
Medium
19,849
https://leetcode.com/problems/break-a-palindrome/discuss/2684214/Python-or-Pretty-Simple-and-clean-solution-with-comments
class Solution: def breakPalindrome(self, palindrome: str) -> str: lst = list(palindrome) # if there is noway to make it non-palindromic if len(lst) < 2: return '' # checking till mid if not a make it a for i in range(len(lst)//2): if lst[i] != 'a': lst[i] = 'a' return ''.join(lst) # else make the last char 'b' lst[len(lst) - 1] = 'b' return ''.join(lst)
break-a-palindrome
Python | Pretty Simple and clean solution with comments
__Asrar
1
22
break a palindrome
1,328
0.531
Medium
19,850
https://leetcode.com/problems/break-a-palindrome/discuss/2103141/python-3-oror-greedy-solution-oror-O(n)O(1)
class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(palindrome) if n == 1: return '' for i in range(n // 2): if palindrome[i] != 'a': return palindrome[:i] + 'a' + palindrome[i+1:] return palindrome[:-1] + 'b'
break-a-palindrome
python 3 || greedy solution || O(n)/O(1)
dereky4
1
280
break a palindrome
1,328
0.531
Medium
19,851
https://leetcode.com/problems/break-a-palindrome/discuss/1482099/PYTHON-Beats-99.03
class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(palindrome) if not n > 1: return "" for char in range(((n-1)//2)+1): if not palindrome[char] == "a": if (not n%2==0) and (char == (n-1)//2): break palindrome = palindrome[0:char] + "a" + palindrome[char+1:n] return palindrome palindrome = palindrome[0:n-1] + "b" return palindrome
break-a-palindrome
[PYTHON] Beats 99.03%
amanpathak2909
1
279
break a palindrome
1,328
0.531
Medium
19,852
https://leetcode.com/problems/break-a-palindrome/discuss/2846482/Python-way
class Solution: def breakPalindrome(self, palindrome: str) -> str: len_palindrome = len(palindrome) if len_palindrome == 1: return "" list_palindrome = list(palindrome) for i in range(len_palindrome // 2): if palindrome[i] != "a": list_palindrome[i] = "a" return "".join(list_palindrome) list_palindrome[-1] = "b" return "".join(list_palindrome)
break-a-palindrome
Python way
namashin
0
2
break a palindrome
1,328
0.531
Medium
19,853
https://leetcode.com/problems/break-a-palindrome/discuss/2833673/Greedy-%2B-edge-case-python-simple-solution
class Solution: def breakPalindrome(self, palindrome: str): if len(palindrome) == 1: return '' elif (palindrome.count('a') == len(palindrome) - 1 and len(palindrome) % 2) or set(palindrome) == {'a'}: string_builder = list(palindrome) string_builder[-1] = 'b' return ''.join(string_builder) else: string_builder = list(palindrome) N = len(string_builder) i = 0 while i < N: if string_builder[i] != 'a': string_builder[i] = 'a' break i += 1 return ''.join(string_builder)
break-a-palindrome
Greedy + edge case / python simple solution
Lara_Craft
0
2
break a palindrome
1,328
0.531
Medium
19,854
https://leetcode.com/problems/break-a-palindrome/discuss/2736651/Simple-solution-O(n)-beats-72-for-runtime-and-90-for-memory
class Solution: def breakPalindrome(self, palindrome: str) -> str: m = len(palindrome) i = 0 if m <= 1: return "" else: while i < m//2 : if palindrome[i] == "a": i=i+1 else: res = palindrome[:i]+"a"+palindrome[i+1:] i = m if i == m//2: return palindrome[:m-1]+"b" else : return res
break-a-palindrome
Simple solution O(n) - beats 72% for runtime and 90% for memory
Alit10
0
2
break a palindrome
1,328
0.531
Medium
19,855
https://leetcode.com/problems/break-a-palindrome/discuss/2704502/WEEB-DOES-PYTHONC%2B%2B
class Solution: def breakPalindrome(self, s: str) -> str: if len(s) == 1: return "" result = "" flag = False for i in range(len(s)-1): if s[i] != "a" and not flag and i != len(s)//2: result += "a" flag = True else: result += s[i] if s[-1] == "a" and not flag: result += "b" else: result += s[-1] return result
break-a-palindrome
WEEB DOES PYTHON/C++
Skywalker5423
0
4
break a palindrome
1,328
0.531
Medium
19,856
https://leetcode.com/problems/break-a-palindrome/discuss/2697083/python-easy-solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome) < 2: return "" for i in range(len(palindrome)//2): if palindrome[i] != 'a': return palindrome[:i] +'a' +palindrome[i+1:] return palindrome[:-1]+'b'
break-a-palindrome
python easy solution
karanjadaun22
0
15
break a palindrome
1,328
0.531
Medium
19,857
https://leetcode.com/problems/break-a-palindrome/discuss/2690665/Python-Simple-Solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: s2=palindrome s1=list(palindrome) for i in range(len(s1)): if s1[i]!="a": c=s1[i] s1[i]='a' if s1 != s1[::-1]: return "".join(s1) s1[i]=c if s1[len(s1)-1] == "a": s1[len(s1)-1] = "b" if s1 == s1[::-1]: return "" return "".join(s1) return ""
break-a-palindrome
Python Simple Solution
VijayGupta09
0
10
break a palindrome
1,328
0.531
Medium
19,858
https://leetcode.com/problems/break-a-palindrome/discuss/2688024/Python
class Solution: def breakPalindrome(self, s: str) -> str: if len(s) == 1: return '' for i in range(len(s) // 2): if s[i] != 'a': s = s[:i] + 'a' + s[i + 1:] return s s = s[:-1] + 'b' return s
break-a-palindrome
Python
JSTM2022
0
8
break a palindrome
1,328
0.531
Medium
19,859
https://leetcode.com/problems/break-a-palindrome/discuss/2687578/Faster-than-80-easy-brute-force-in-PYTHON!!
class Solution: def breakPalindrome(self, palindrome: str) -> str: l=len(palindrome) if l>1: for i in range(l//2): new=list(palindrome) if ord(new[i])>97: new[i]='a' return ''.join(new) new[l-1]='b' return ''.join(new) else: return ""
break-a-palindrome
Faster than 80%, easy brute force in PYTHON!!
rawatprashant2121
0
17
break a palindrome
1,328
0.531
Medium
19,860
https://leetcode.com/problems/break-a-palindrome/discuss/2687482/Best-python-solution-easy-to-understand-T.C-0(n)
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome)<=1:return "" p = list(palindrome) for i in range(len(p)//2): if p[i]!="a": p[i]="a" break else: p[-1]="b" return "".join(p)
break-a-palindrome
Best python solution easy to understand T.C = 0(n)
kartik_5051
0
3
break a palindrome
1,328
0.531
Medium
19,861
https://leetcode.com/problems/break-a-palindrome/discuss/2687429/94-Accepted-or-Simple-and-Easy-to-Understand-or-Python
class Solution(object): def breakPalindrome(self, palindrome): if len(palindrome) == 1: return "" n = len(palindrome) // 2 for i in range(n): if palindrome[i] != "a": return palindrome[:i] + "a" + palindrome[i+1:] return palindrome[:-1] + "b"
break-a-palindrome
94% Accepted | Simple and Easy to Understand | Python
its_krish_here
0
48
break a palindrome
1,328
0.531
Medium
19,862
https://leetcode.com/problems/break-a-palindrome/discuss/2687310/greedy-solution-python-with-explaination
class Solution: def breakPalindrome(self,s: str) -> str: n =len(s) s=list(s) if n ==1: return '' s1=-1 if n%2==1: s1=n//2 c=0 for i in range(n): if i!=s1: if s[i]!='a': s[i]='a' c=1 break if c==0: if s[-1]!='b': s[-1]='b' else: s[-1]=='c' return ''.join(s)
break-a-palindrome
greedy solution python with explaination
abhayCodes
0
16
break a palindrome
1,328
0.531
Medium
19,863
https://leetcode.com/problems/break-a-palindrome/discuss/2687299/I-hated-this-questions-phrasing
class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(palindrome) if n==1: return "" for i in range(n//2): if palindrome[i] != 'a': return palindrome[:i]+'a'+palindrome[i+1:] return palindrome[:-1] + 'b'
break-a-palindrome
I hated this questions phrasing
logostheorist
0
1
break a palindrome
1,328
0.531
Medium
19,864
https://leetcode.com/problems/break-a-palindrome/discuss/2687093/Easy-Solution-using-Python-3
class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(palindrome)//2 c = "a" for i in range (n): if palindrome[i] != c: x = palindrome[:i] + c + palindrome[i+1:] return x if c*n == palindrome[:n] and len(palindrome) > 1: return palindrome[:len(palindrome)-1] + "b" else: return ""
break-a-palindrome
Easy Solution using Python 3
prankurgupta18
0
43
break a palindrome
1,328
0.531
Medium
19,865
https://leetcode.com/problems/break-a-palindrome/discuss/2686989/Python3-or-Easy-to-Understand-or-Efficient-or-Explained
class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(pali) # for single character palindrome if n == 1: return '' # make list to access it easily pali = list(palindrome) for i in range(n): if pali[i] != 'a': pali[i] = 'a' break if pali != pali[::-1]: # after replacing with 'a', if it is not palindrome again return ''.join(pali) else: pali = list(palindrome) pali[-1] = 'b' return ''.join(pali)
break-a-palindrome
✅Python3 | Easy to Understand | Efficient | Explained
thesauravs
0
25
break a palindrome
1,328
0.531
Medium
19,866
https://leetcode.com/problems/break-a-palindrome/discuss/2686918/Python3!-As-short-as-it-gets!
class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(palindrome) if n == 1: return "" non_a = [i for i, a in enumerate(palindrome) if a != 'a'] non_a = n//2 if len(non_a) == 0 else non_a[0] new_str = palindrome[:non_a] + 'a' + palindrome[non_a+1:] return new_str if any(new_str[i] != new_str[n-i-1] for i in range(n//2)) else palindrome[:-1] + 'b'
break-a-palindrome
😎Python3! As short as it gets!
aminjun
0
59
break a palindrome
1,328
0.531
Medium
19,867
https://leetcode.com/problems/break-a-palindrome/discuss/2686870/python-easy-solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: for i in range(len(palindrome)//2): if palindrome[i]!="a": return palindrome[:i]+"a"+palindrome[i+1:] return palindrome[:-1]+"b" if len(palindrome)>1 else ""
break-a-palindrome
python easy solution
Narendrasinghdangi
0
5
break a palindrome
1,328
0.531
Medium
19,868
https://leetcode.com/problems/break-a-palindrome/discuss/2686687/Python-solution-with-EXPLANATION-EASY-to-UNDERSTAND
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome) == 1: return "" # edge case palindrome = list(palindrome) for i in range(len(palindrome)//2): if palindrome[i] != "a": palindrome[i] = "a" break else: palindrome[-1] = "b" return "".join(palindrome)
break-a-palindrome
Python solution with EXPLANATION [EASY to UNDERSTAND]
Abhishekh21
0
3
break a palindrome
1,328
0.531
Medium
19,869
https://leetcode.com/problems/break-a-palindrome/discuss/2686338/Python-Solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome) <= 1: return "" letters = "abcdefghijklmnopqrstuvwxyz" result = "" finished = False for t, char in enumerate(palindrome): if char != 'a' and not finished and t != len(palindrome) // 2: idx = letters.index(char) char = "a" finished = True result += char if result == palindrome: # Only a:s return result[:-1] + "b" return result
break-a-palindrome
Python Solution
AxelDovskog
0
5
break a palindrome
1,328
0.531
Medium
19,870
https://leetcode.com/problems/break-a-palindrome/discuss/2685682/Simple-Solution-in-Python
class Solution(object): def breakPalindrome(self, palindrome): if len(palindrome)==1: return '' for i in range(len(palindrome)//2): if palindrome[i]>'a': return palindrome[:i] + 'a' + palindrome[i+1:] return palindrome[:-1] + 'b'
break-a-palindrome
Simple Solution in Python
A14K
0
11
break a palindrome
1,328
0.531
Medium
19,871
https://leetcode.com/problems/break-a-palindrome/discuss/2685147/python-solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: n=len(palindrome) if n==1: return "" s="" for i in range(n): if palindrome[i]!='a': s+='a' s+=palindrome[i+1:] if s!=s[::-1]: return s else: break s+=palindrome[i] return palindrome[:-1]+'b'
break-a-palindrome
python solution
shashank_2000
0
59
break a palindrome
1,328
0.531
Medium
19,872
https://leetcode.com/problems/break-a-palindrome/discuss/2685141/Easy-Solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: for i in range(len(palindrome) // 2): if palindrome[i] != "a": return (palindrome[:i] + 'a' + palindrome[i + 1:]) return (palindrome[:-1] + 'b') if len(palindrome) != 1 else ""
break-a-palindrome
Easy Solution
user6770yv
0
3
break a palindrome
1,328
0.531
Medium
19,873
https://leetcode.com/problems/break-a-palindrome/discuss/2685102/Python-(Faster-than-97)-or-Easy-to-understand-O(N)-Solution-(Greedy)
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome) == 1: return "" i = 0 palindrome = list(palindrome) while i < (len(palindrome) // 2): if palindrome[i] == 'a': i += 1 else: palindrome[i] = 'a' return ''.join(palindrome) palindrome[-1] = 'b' return ''.join(palindrome)
break-a-palindrome
Python (Faster than 97%) | Easy to understand O(N) Solution (Greedy)
KevinJM17
0
4
break a palindrome
1,328
0.531
Medium
19,874
https://leetcode.com/problems/break-a-palindrome/discuss/2684854/Easy-Python-Solution-with-Explanation
class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(palindrome) if n == 1: return "" # check till first half only for i in range(n//2): # character is not 'a', like b,c etc if palindrome[i] != 'a': # simply replace it with 'a',to keep lexicographical order # and break the palindrome return palindrome[:i] + 'a' + palindrome[i+1:] # This case means it contains aaa... only # just replace last character with b return palindrome[:n-1] + 'b'
break-a-palindrome
Easy Python Solution with Explanation
Ridikulus
0
2
break a palindrome
1,328
0.531
Medium
19,875
https://leetcode.com/problems/break-a-palindrome/discuss/2684832/Python-solution-with-easy-to-understand-explanation.
class Solution: def breakPalindrome(self, palindrome: str) -> str: palindrome = list(palindrome) n = len(palindrome) if(n<=1): return '' for i in range(n//2): if(palindrome[i]!='a'): palindrome[i]='a' return ''.join(palindrome) palindrome[n-1]='b' return ''.join(palindrome)
break-a-palindrome
Python solution with easy to understand explanation.
yashkumarjha
0
5
break a palindrome
1,328
0.531
Medium
19,876
https://leetcode.com/problems/break-a-palindrome/discuss/2684507/Fast-92-greedy-python3-solution-or-n2-time
class Solution: # O(n) time, # O(n) space, # Approach: greedy, def breakPalindrome(self, palindrome: str) -> str: mid = len(palindrome)//2 if len(palindrome) == 1: return "" pali_lst = list(palindrome) for i in range(mid): if pali_lst[i] != 'a': pali_lst[i] = 'a' return ''.join(pali_lst) pali_lst[-1] = 'b' return ''.join(pali_lst)
break-a-palindrome
Fast 92% greedy python3 solution | n//2 time
destifo
0
52
break a palindrome
1,328
0.531
Medium
19,877
https://leetcode.com/problems/break-a-palindrome/discuss/2684412/Python-Simple-or-O(n)-or-99
class Solution: def breakPalindrome(self, palindrome: str) -> str: pali_list = list(palindrome) n = len(pali_list) if n == 1: return '' for idx in range(n): if pali_list[idx] != 'a' and idx != n//2: pali_list[idx] = 'a' break else: pali_list[-1] = 'b' return ''.join(pali_list)
break-a-palindrome
Python Simple | O(n) | 99%
Nibba2018
0
56
break a palindrome
1,328
0.531
Medium
19,878
https://leetcode.com/problems/break-a-palindrome/discuss/2684354/Python-or-Easy-If-Else-Statements-(Greedy)
class Solution: def breakPalindrome(self, palindrome: str) -> str: # res="" s=list(palindrome) n=len(s) if n==1: return "" for i in range(n): if s[i]!="a": if n%2==1: if i!=n//2: s[i]="a" return "".join(s) else: s[i]="a" return "".join(s) s[-1]="b" return "".join(s)
break-a-palindrome
Python | Easy If Else Statements (Greedy)
Prithiviraj1927
0
35
break a palindrome
1,328
0.531
Medium
19,879
https://leetcode.com/problems/break-a-palindrome/discuss/2684343/Simple-Python-Solution-or-Greedy-or-81-Faster
class Solution: def breakPalindrome(self, palindrome: str) -> str: n=len(palindrome) if n==1: return '' pal=list(palindrome) for i in range(n//2 + 1): if pal[i]!='a': temp=pal[i] pal[i]='a' if pal==pal[::-1]: pal[i]=temp else: return ''.join(pal) pal[-1]='b' return ''.join(pal)
break-a-palindrome
Simple Python Solution | Greedy | 81% Faster
Siddharth_singh
0
4
break a palindrome
1,328
0.531
Medium
19,880
https://leetcode.com/problems/break-a-palindrome/discuss/2684305/Easy-and-optimal-faster
class Solution: def breakPalindrome(self, palindrome: str) -> str: n=len(palindrome) if(n==1): return "" for i in range(0,n//2): if(palindrome[i]!='a'): return palindrome[:i]+'a'+palindrome[i+1:] return palindrome[0:-1]+'b'
break-a-palindrome
Easy and optimal faster
Raghunath_Reddy
0
2
break a palindrome
1,328
0.531
Medium
19,881
https://leetcode.com/problems/break-a-palindrome/discuss/2684281/C%2B%2BPython-Linear-Time-Solution
class Solution: def breakPalindrome(self, s: str) -> str: n = len(s) if n == 1: return "" for i in range(0,n): j = n - 1 - i if i == j: continue if s[i] != 'a': return s[:i] + 'a' + s[i+1:] return s[:-1] + "b"
break-a-palindrome
C++/Python Linear Time Solution
MrFit
0
15
break a palindrome
1,328
0.531
Medium
19,882
https://leetcode.com/problems/break-a-palindrome/discuss/2684203/Python-or-easy
class Solution: def breakPalindrome(self, palindrome: str) -> str: l = len(palindrome) if l <= 1: return "" i = 0 while i < l: if palindrome[i] == "a": i += 1 else: s = palindrome[:i] + "a" + palindrome[i+1:] if s == s[::-1]: i += 1 else: return s return palindrome[:l-1] + "b"
break-a-palindrome
Python | easy
Akhil_krish_na
0
2
break a palindrome
1,328
0.531
Medium
19,883
https://leetcode.com/problems/break-a-palindrome/discuss/2684139/Linear-Time-Python3-Solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: N = len(palindrome) if N == 1: return "" res = list(palindrome) flag = False for i in range(N): if res[i] != 'a': if N % 2 != 0 and i == N // 2: continue res[i] = 'a' flag = True break if flag: return "".join(res) else: res[-1] = 'b' return "".join(res)
break-a-palindrome
🔥Linear Time Python3 Solution
mediocre-coder
0
8
break a palindrome
1,328
0.531
Medium
19,884
https://leetcode.com/problems/break-a-palindrome/discuss/2684124/Python-Focus-on-simplicity-and-readability
class Solution: def breakPalindrome(self, p: str) -> str: """ 1. Iterate till len(palindrome)//2 and find the index of the first non 'a' character in the palindrome 2. Set the character from the index above to 'a' 3. If zero non 'a' characters were encountered, set the last character to 'b' """ if len(p) == 1: return "" p = list(p) first_non_a = None for i, c in enumerate(p[:len(p) // 2]): if c != 'a': first_non_a = i break if first_non_a is not None: p[first_non_a] = 'a' else: p[-1] = 'b' return ''.join(p)
break-a-palindrome
[Python] Focus on simplicity and readability
throovi
0
13
break a palindrome
1,328
0.531
Medium
19,885
https://leetcode.com/problems/break-a-palindrome/discuss/2683898/Easy-to-understand-100-Accepted-Python3-solution.
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome) < 2: return "" out = [] # inputArr = list(palindrome) chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] curMin = "z"*len(palindrome) for i in range(len(palindrome)): inputArr = list(palindrome) for j in range(len(chars)): inputArr[i] = chars[j] if inputArr != inputArr[::-1]: current = "".join(inputArr) curMin = min(curMin, current) return curMin
break-a-palindrome
Easy to understand 100% Accepted Python3 solution.
ShivangVora1206
0
1
break a palindrome
1,328
0.531
Medium
19,886
https://leetcode.com/problems/break-a-palindrome/discuss/2683853/Python-or-10-line-or-Easy-Understanding-or-Simple-Solution
class Solution: def breakPalindrome(self, palindrome: str) -> str: if len(palindrome)<=1: return '' cmin='zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz' for i in range(len(palindrome)): x = list(palindrome) for j in range(97,123): x[i] = chr(j) rejoin = ''.join(x) if rejoin!=palindrome and rejoin!=rejoin[::-1]: cmin = min(cmin,rejoin) return cmin
break-a-palindrome
🔥 Python | 10-line | Easy-Understanding | Simple Solution
ShubhamVora1206
0
38
break a palindrome
1,328
0.531
Medium
19,887
https://leetcode.com/problems/break-a-palindrome/discuss/2683840/Python-oror-Easily-Understood-oror-Faster-than-96-oror-with-EXPLAINATION
class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(palindrome) # there is no way to replace a single character to make "a" not a palindrome # because no matter what we change, it is still a palindrome if n == 1: return '' # let's think about n = 2 case, e.g. "bb" # in this case, to acheive the lexicographically smallest one # we should replace from the left and the best character to use is "a" # for "bb", we replace the first "b" to "a" to become "ab" # let's think about another n = 2 case, e.g. "aa" # in this case, to acheive the lexicographically smallest one # we should replace from the left and the best character to use is "a" # however, for "aa", we cannot use "a" here and the best character to use is "b" now # for "aa", we replace the second "a" to "b" to become "ab" # why not replace the first "a"? because "ba" is not smallest. for i in range(n // 2): # here we know that as long as palindrome[i] is not "a", we skip it if palindrome[i] != 'a': # otherwise, we replace the first character that is not "a" return palindrome[:i] + 'a' + palindrome[i + 1:] # by the time it reaches here, the only possible case is all the characters in palindrome is "a" # e.g. "aaaaaa" so that we haven't changed anything in above logic # in this case, as mentioned above, the best character to use is "b" # and we should replace the last character to achieve the smallest one possible return palindrome[:-1] + 'b'
break-a-palindrome
🔥 Python || Easily Understood ✅ || Faster than 96% || with EXPLAINATION
rajukommula
0
27
break a palindrome
1,328
0.531
Medium
19,888
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/920657/Python3-simple-solution
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: d = defaultdict(list) for i in range(len(mat)): for j in range(len(mat[0])): d[i-j].append(mat[i][j]) for k in d.keys(): d[k].sort() for i in range(len(mat)): for j in range(len(mat[0])): mat[i][j] = d[i-j].pop(0) return mat
sort-the-matrix-diagonally
Python3 simple solution
ermolushka2
8
463
sort the matrix diagonally
1,329
0.836
Medium
19,889
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2494052/Python-Elegant-and-Short-or-Two-solutions-or-Hashmap-Generators
class Solution: """ Time: O(n*m*log(max(n,m)) Memory: O(n*m) """ def diagonalSort(self, matrix: List[List[int]]) -> List[List[int]]: n, m = len(matrix), len(matrix[0]) diags = defaultdict(list) for i in range(n): for j in range(m): diags[i - j].append(matrix[i][j]) for k in diags: diags[k].sort(reverse=True) for i in range(n): for j in range(m): matrix[i][j] = diags[i - j].pop() return matrix
sort-the-matrix-diagonally
Python Elegant & Short | Two solutions | Hashmap / Generators
Kyrylo-Ktl
4
209
sort the matrix diagonally
1,329
0.836
Medium
19,890
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2494052/Python-Elegant-and-Short-or-Two-solutions-or-Hashmap-Generators
class Solution: """ Time: O(n*m*log(max(n,m)) Memory: O(n + m) """ def diagonalSort(self, matrix: List[List[int]]) -> List[List[int]]: n, m = len(matrix), len(matrix[0]) diagonals = [(i, 0) for i in range(n - 1, 0, -1)] + [(0, j) for j in range(m)] for row, col in diagonals: for val in sorted(self._diagonal_generator(row, col, matrix)): matrix[row][col] = val row += 1 col += 1 return matrix @staticmethod def _diagonal_generator(r: int, c: int, matrix: List[List[int]]): while r < len(matrix) and c < len(matrix[0]): yield matrix[r][c] r += 1 c += 1
sort-the-matrix-diagonally
Python Elegant & Short | Two solutions | Hashmap / Generators
Kyrylo-Ktl
4
209
sort the matrix diagonally
1,329
0.836
Medium
19,891
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2493644/python3-or-easy-understanding-or-explained-or-sort
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: lst = [] n, m = len(mat), len(mat[0]) # leftmost column for i in range(n): lst.append([i, 0]) # rightmost row for i in range(m): lst.append([0, i]) lst.pop(0) for x, y in lst: arr = [] i, j = x, y # getting the diagonal elements while i < n and j < m: arr.append(mat[i][j]) i, j = i+1, j+1 arr.sort() # sort the elements i, j = x, y # setting the element in sorted order while i < n and j < m: mat[i][j] = arr.pop(0) i, j = i+1, j+1 return mat
sort-the-matrix-diagonally
python3 | easy-understanding | explained | sort
H-R-S
2
56
sort the matrix diagonally
1,329
0.836
Medium
19,892
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2493515/Python-sorting-one-diag-at-a-time-or-O(min(MN))-space-or-explained
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: r,c = len(mat), len(mat[0]) for sr,sc in list(zip(range(r-1,-1,-1),[0 for _ in range(r)])) + list(zip([0 for _ in range(c-1)],range(1,c))): diag = [] i,j = sr, sc while j<c and i<r: bruh.append(mat[i][j]) i+=1 j+=1 diag.sort() i,j = sr, sc count = 0 while j<c and i<r: mat[i][j] = diag[count] count+=1 i+=1 j+=1 return mat
sort-the-matrix-diagonally
Python sorting one diag at a time | O(min(M,N)) space | explained
mync
2
57
sort the matrix diagonally
1,329
0.836
Medium
19,893
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2703872/Python3-Solution
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: r_len = len(mat) c_len = len(mat[0]) positions = [(i,0) for i in range(r_len-1, -1, -1)] + [(0,i) for i in range(1,c_len)] ans = [] for p in positions: x = [] i = 0 while i+p[0] < r_len and i+p[1] < c_len: x.append(mat[p[0]+i][p[1]+i]) i += 1 ans = ans + sorted(x) for p in positions: i = 0 while i+p[0] < r_len and i+p[1] < c_len: mat[p[0]+i][p[1]+i] = ans.pop(0) i += 1 return mat
sort-the-matrix-diagonally
Python3 Solution
sipi09
1
33
sort the matrix diagonally
1,329
0.836
Medium
19,894
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/2497235/python-straight-forward-answer-with-very-good-efficiency
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: x1=0 y1=0 for i in range(len(mat[0])): xx=x1 yy=y1 val=[] idx=[] while xx in range(len(mat[0])) and yy in range(len(mat)): val.append(mat[yy][xx]) idx.append((yy,xx)) yy+=1 xx+=1 val.sort() for i in range(len(val)): mat[idx[i][0]][idx[i][1]]=val[i] x1+=1 x1=0 y1=1 for i in range(1,len(mat)): xx=x1 yy=y1 val=[] idx=[] while xx in range(len(mat[0])) and yy in range(len(mat)): val.append(mat[yy][xx]) idx.append((yy,xx)) yy+=1 xx+=1 val.sort() for i in range(len(val)): mat[idx[i][0]][idx[i][1]]=val[i] y1+=1 return mat
sort-the-matrix-diagonally
python straight forward answer with very good efficiency
benon
1
33
sort the matrix diagonally
1,329
0.836
Medium
19,895
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1885706/Python-easy-to-read-and-understand-or-hashmap
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: d = collections.defaultdict(list) m, n = len(mat), len(mat[0]) for i in range(m): for j in range(n): d[i-j].append(mat[i][j]) for key in d: d[key].sort() for i in range(m): for j in range(n): mat[i][j] = d[i-j].pop(0) return mat
sort-the-matrix-diagonally
Python easy to read and understand | hashmap
sanial2001
1
90
sort the matrix diagonally
1,329
0.836
Medium
19,896
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/1275894/Python3-solution-using-dictionary
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: diagonal = {} for i in range(len(mat)): for j in range(len(mat[0])): diagonal[i-j] = diagonal.get(i-j,[])+[mat[i][j]] for i in diagonal.values(): i.sort() for i in range(len(mat)): for j in range(len(mat[0])): mat[i][j] = diagonal[i-j].pop(0) return mat
sort-the-matrix-diagonally
Python3 solution using dictionary
EklavyaJoshi
1
118
sort the matrix diagonally
1,329
0.836
Medium
19,897
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/869285/Python3-Extra-Clean-with-built-in-sort()-oror-99-helper-function-and-multithreadable
class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: if not mat: return [[]] m = len(mat) n = len(mat[0]) def helper_sort(x,y, mat): collector = [] inds = [] while True: if x >= m or y >= n: break collector.append(mat[x][y]) inds.append((x,y)) #unneeded storage, but makes it a bit cleaner x, y = x+1, y+1 collector.sort() #return the values to the array for i, (x,y) in enumerate(inds): mat[x][y] = collector[i] #Sort each column diagonals = [(0,i) for i in range(n)] + [(i,0) for i in range(1,m)] #multithreadable for x,y in diagonals: helper_sort(x,y, mat) return mat
sort-the-matrix-diagonally
Python3, Extra Clean with built in sort() || 99%, helper function, and multithreadable
fzbuzz
1
124
sort the matrix diagonally
1,329
0.836
Medium
19,898
https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/492314/Python-3-(four-lines)-(beats-~97)
class Solution: def diagonalSort(self, G: List[List[int]]) -> List[List[int]]: M, N, D = len(G), len(G[0]), collections.defaultdict(list) for i,j in itertools.product(range(M),range(N)): D[i-j].append(G[i][j]) for k in D: D[k].sort(reverse = True) return [[D[i-j].pop() for j in range(N)] for i in range(M)] - Junaid Mansuri - Chicago, IL
sort-the-matrix-diagonally
Python 3 (four lines) (beats ~97%)
junaidmansuri
1
573
sort the matrix diagonally
1,329
0.836
Medium
19,899