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/escape-a-large-maze/discuss/1292945/Python3-bfs-and-dfs | class Solution:
def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:
blocked = set(map(tuple, blocked))
def fn(x, y, tx, ty):
"""Return True if (x, y) is not looped from (tx, ty)."""
seen = {(x, y)}
queue = [(x, y)]
level = 0
while queue:
level += 1
if level > 200: return True
newq = []
for x, y in queue:
if (x, y) == (tx, ty): return True
for xx, yy in (x-1, y), (x, y-1), (x, y+1), (x+1, y):
if 0 <= xx < 1e6 and 0 <= yy < 1e6 and (xx, yy) not in blocked and (xx, yy) not in seen:
seen.add((xx, yy))
newq.append((xx, yy))
queue = newq
return False
return fn(*source, *target) and fn(*target, *source) | escape-a-large-maze | [Python3] bfs & dfs | ye15 | 3 | 373 | escape a large maze | 1,036 | 0.341 | Hard | 16,900 |
https://leetcode.com/problems/escape-a-large-maze/discuss/1292945/Python3-bfs-and-dfs | class Solution:
def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:
blocked = set(map(tuple, blocked))
def dfs(sx, sy, tx, ty):
"""Return True if (x, y) is not looped from (tx, ty)."""
seen = {(sx, sy)}
stack = [(sx, sy)]
while stack:
x, y = stack.pop()
if abs(x - sx) + abs(y - sy) > 200 or (x, y) == (tx, ty): return True
for xx, yy in (x-1, y), (x, y-1), (x, y+1), (x+1, y):
if 0 <= xx < 1e6 and 0 <= yy < 1e6 and (xx, yy) not in blocked and (xx, yy) not in seen:
seen.add((xx, yy))
stack.append((xx, yy))
return False
return dfs(*source, *target) and dfs(*target, *source) | escape-a-large-maze | [Python3] bfs & dfs | ye15 | 3 | 373 | escape a large maze | 1,036 | 0.341 | Hard | 16,901 |
https://leetcode.com/problems/valid-boomerang/discuss/1985698/Python-3-Triangle-Area | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
x1, y1 = points[0]
x2, y2 = points[1]
x3, y3 = points[2]
area = abs(x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2))/2
return area != 0 | valid-boomerang | [Python 3] Triangle Area | hari19041 | 9 | 679 | valid boomerang | 1,037 | 0.374 | Easy | 16,902 |
https://leetcode.com/problems/valid-boomerang/discuss/2366828/Compare-slopes-python | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
a,b,c=points
return (b[1]-a[1])*(c[0]-b[0]) != (c[1]-b[1])*(b[0]-a[0]) | valid-boomerang | Compare slopes python | sunakshi132 | 2 | 135 | valid boomerang | 1,037 | 0.374 | Easy | 16,903 |
https://leetcode.com/problems/valid-boomerang/discuss/1264063/Python3-simple-%22one-liner%22-solution | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
return (points[1][1]-points[0][1]) * (points[2][0]-points[1][0]) != (points[1][0]-points[0][0]) * (points[2][1]-points[1][1]) | valid-boomerang | Python3 simple "one-liner" solution | EklavyaJoshi | 1 | 135 | valid boomerang | 1,037 | 0.374 | Easy | 16,904 |
https://leetcode.com/problems/valid-boomerang/discuss/2801586/Python3-or-Cross-product-or-Fast-than-99.41 | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
x_diff_01 = points[0][0] - points[1][0]
y_diff_01 = points[0][1] - points[1][1]
x_diff_12 = points[1][0] - points[2][0]
y_diff_12 = points[1][1] - points[2][1]
return (x_diff_01*y_diff_12) != (x_diff_12*y_diff_01) | valid-boomerang | Python3 | Cross product | Fast than 99.41% | YLW_SE | 0 | 5 | valid boomerang | 1,037 | 0.374 | Easy | 16,905 |
https://leetcode.com/problems/valid-boomerang/discuss/2759942/Python-1-line-code | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
return (points[0][0]*(points[1][1]-points[2][1])+ points[1][0]*(points[2][1]-points[0][1]) + points[2][0]*(points[0][1]-points[1][1]))!=0 | valid-boomerang | Python 1 line code | kumar_anand05 | 0 | 4 | valid boomerang | 1,037 | 0.374 | Easy | 16,906 |
https://leetcode.com/problems/valid-boomerang/discuss/2739288/Python3-Extended-to-any-number-of-Points-and-Dimensions | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
# get the directional pointer
pointer = []
for c1, c0 in zip(points[1], points[0]):
pointer.append(c1-c0)
# check whether those are equal
visited = set([tuple(points[0]), tuple(points[1])])
if len(visited) < 2:
return False
# go through the rest of the points
boomerang = False
for point in points[2:]:
# initialize a factor
factor = None
# check whether we already visited this
if tuple(point) in visited:
return False
visited.add(tuple(point))
# check whether we already found point not on the line
if boomerang:
continue
# check whether all points fit
for p, dire, start in zip(point, pointer, points[0]):
# check whether dire is zero, then p also needs
# to have the same coordinate as the point zero
if dire == 0:
if p != start:
boomerang = True
break
elif factor is not None and factor != (p-start)/dire:
boomerang = True
break
else:
factor = (p-start)/dire
return boomerang | valid-boomerang | [Python3] - Extended to any number of Points and Dimensions | Lucew | 0 | 3 | valid boomerang | 1,037 | 0.374 | Easy | 16,907 |
https://leetcode.com/problems/valid-boomerang/discuss/2642641/Python-Solution-or-Classic-Geometric-Computation-Based | class Solution:
# USE FORMULA TO CALCULATE AREA UNDER 3 POINTS
def isBoomerang(self, points: List[List[int]]) -> bool:
x1,y1 = points[0]
x2,y2 = points[1]
x3,y3 = points[2]
return abs(x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2)) != 0 | valid-boomerang | Python Solution | Classic Geometric Computation Based | Gautam_ProMax | 0 | 23 | valid boomerang | 1,037 | 0.374 | Easy | 16,908 |
https://leetcode.com/problems/valid-boomerang/discuss/1976464/Python-Solution | class Solution:
def isBoomerang(self, points: list[list[int]]) -> bool:
if ( (points[1][0] - points[0][0]) * (points[2][1] - points[1][1])
!= (points[1][1] - points[0][1]) * (points[2][0] - points[1][0]) ):
return True
else:
return False | valid-boomerang | Python Solution | EddieAtari | 0 | 76 | valid boomerang | 1,037 | 0.374 | Easy | 16,909 |
https://leetcode.com/problems/valid-boomerang/discuss/1912510/Python-one-line-solution | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
return (points[2][1] - points[1][1]) * (points[0][0] - points[1][0]) != (points[2][0] - points[1][0]) * (points[0][1] - points[1][1]) | valid-boomerang | Python one line solution | alishak1999 | 0 | 64 | valid boomerang | 1,037 | 0.374 | Easy | 16,910 |
https://leetcode.com/problems/valid-boomerang/discuss/1850057/1-Line-Python-Solution-oror-95-Faster-(32ms)-oror-Memory-less-than-50 | class Solution:
def isBoomerang(self, P: List[List[int]]) -> bool:
return P[0][0]*(P[1][1]-P[2][1])+P[1][0]*(P[2][1]-P[0][1])+P[2][0]*(P[0][1]-P[1][1])!=0 | valid-boomerang | 1-Line Python Solution || 95% Faster (32ms) || Memory less than 50% | Taha-C | 0 | 83 | valid boomerang | 1,037 | 0.374 | Easy | 16,911 |
https://leetcode.com/problems/valid-boomerang/discuss/1850057/1-Line-Python-Solution-oror-95-Faster-(32ms)-oror-Memory-less-than-50 | class Solution:
def isBoomerang(self, P: List[List[int]]) -> bool:
return (P[2][1]-P[1][1])*(P[0][0]-P[1][0])!=(P[2][0]-P[1][0])*(P[0][1]-P[1][1]) | valid-boomerang | 1-Line Python Solution || 95% Faster (32ms) || Memory less than 50% | Taha-C | 0 | 83 | valid boomerang | 1,037 | 0.374 | Easy | 16,912 |
https://leetcode.com/problems/valid-boomerang/discuss/1654901/python3-using-matrix-det | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
x1 = points[0][0]
y1 = points[0][1]
x2 = points[1][0]
y2 = points[1][1]
x3 = points[2][0]
y3 = points[2][1]
if x1*y2+y1*x3+x2*y3!=x3*y2+y3*x1+x2*y1:
return True
else:
return False | valid-boomerang | python3 using matrix det | Ngh2003 | 0 | 80 | valid boomerang | 1,037 | 0.374 | Easy | 16,913 |
https://leetcode.com/problems/valid-boomerang/discuss/1146896/Python3-finding-the-slope-approach-(faster-than-97) | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
p1, p2, p3 = points[0], points[1], points[2]
if p1 != p2 and p2 != p3 and p1 != p3 :
x1, y1, x2, y2, x3, y3 = p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]
try :
m1 = (y2 - y1) / (x2 - x1)
except ZeroDivisionError :
m1 = float('inf')
try :
m2 = (y3 - y2) / (x3 - x2)
except ZeroDivisionError :
m2 = float('inf')
if m1 != m2 :
return True
return False
else :
return False | valid-boomerang | Python3 finding the slope approach (faster than 97%) | adarsh__kn | 0 | 141 | valid boomerang | 1,037 | 0.374 | Easy | 16,914 |
https://leetcode.com/problems/valid-boomerang/discuss/784154/Python-or-Cross-product-or-100 | class Solution(object):
def isBoomerang(self, coordinates):
"""
:type coordinates: List[List[int]]
:rtype: bool
"""
save_res = 0
flag = False
diff_x = coordinates[1][0] - coordinates[0][0]
diff_y = coordinates[1][1] - coordinates[0][1]
for i in range(2, len(coordinates)):
x = diff_x
y = diff_y
diff_x = coordinates[i][0] - coordinates[i-1][0]
diff_y = coordinates[i][1] - coordinates[i-1][1]
x_dash = diff_x
y_dash = diff_y
res = x*y_dash - x_dash*y
if res!=0:
return True
return False | valid-boomerang | Python | Cross product | 100% | mihirrane | 0 | 96 | valid boomerang | 1,037 | 0.374 | Easy | 16,915 |
https://leetcode.com/problems/valid-boomerang/discuss/376298/Python-99.14-finding-the-distance-between-points | class Solution(object):
def isBoomerang(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
A, B, C = points
AB = ((A[0] - B[0])**2 + (A[1] - B[1])**2)**(0.5)
BC = ((B[0] - C[0])**2 + (B[1] - C[1])**2)**(0.5)
AC = ((A[0] - C[0])**2 + (A[1] - C[1])**2)**(0.5)
return not(AB == BC + AC or BC == AB + AC or AC == AB + BC) | valid-boomerang | Python 99.14% finding the distance between points | DenysCoder | 0 | 432 | valid boomerang | 1,037 | 0.374 | Easy | 16,916 |
https://leetcode.com/problems/valid-boomerang/discuss/350819/Solution-in-Python-3-(-one-line-) | class Solution:
def isBoomerang(self, p: List[List[int]]) -> bool:
return (p[2][1]-p[1][1])*(p[1][0]-p[0][0]) != (p[2][0]-p[1][0])*(p[1][1]-p[0][1])
- Junaid Mansuri | valid-boomerang | Solution in Python 3 ( one line ) | junaidmansuri | 0 | 360 | valid boomerang | 1,037 | 0.374 | Easy | 16,917 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/1270148/Recursive-approch-99.88-accuracy-Python | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
s = 0
def f(root):
if root is None: return
nonlocal s
f(root.right)
#print(s,root.val)
s = s + root.val
root.val = s
f(root.left)
f(root)
return root | binary-search-tree-to-greater-sum-tree | Recursive approch 99.88% accuracy[ Python ] | rstudy211 | 5 | 238 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,918 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/551946/Faster-than-92-or-Easy-to-understand-or-Simple-or-Python-Solution | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
self.convert_to_list(root)
self.modify_tree(root)
return root
def modify_tree(self, root):
def rec(root):
i = 0
if root:
rec(root.left)
index = self.list.index(root.val)
root.val = sum(self.list[index:])
rec(root.right)
return 0
rec(root)
def convert_to_list(self, root):
self.list = []
def rec(root):
if root:
rec(root.left)
self.list.append(root.val)
rec(root.right)
rec(root) | binary-search-tree-to-greater-sum-tree | Faster than 92% | Easy to understand | Simple | Python Solution | Mrmagician | 1 | 213 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,919 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/300198/Python-reverse-in-order-traversal-using-generator-function-(yield) | class Solution:
def reversed_order_traversal(self, node):
if node is not None:
yield from self.reversed_order_traversal(node.right)
yield node
yield from self.reversed_order_traversal(node.left)
def bstToGst(self, root: TreeNode) -> TreeNode:
current_sum = 0
for node in self.reversed_order_traversal(root):
current_sum += node.val
node.val = current_sum
return root | binary-search-tree-to-greater-sum-tree | Python reverse-in-order traversal, using generator function (yield) | Hai_dee | 1 | 287 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,920 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/2697168/Python3-Simple-Solution | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
arr = []
def DFS(r):
if r:
DFS(r.left)
arr.append(r.val)
DFS(r.right)
DFS(root)
d = defaultdict(int)
tmp = 0
for i in range(len(arr) - 1, -1, -1):
tmp += arr[i]
d[arr[i]] = tmp
def RES(r):
if r:
RES(r.left)
r.val = d[r.val]
RES(r.right)
RES(root)
return root | binary-search-tree-to-greater-sum-tree | Python3 Simple Solution | mediocre-coder | 0 | 4 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,921 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/2615263/Reverse-In-order-Traversal-Python-solution | class Solution:
def __init__(self):
self.greaterSum = 0
def bstToGst(self, root: TreeNode) -> TreeNode:
return self.inOrderTraverse(root)
def inOrderTraverse(self, root):
if (not root): return
# compute greater sum using the right subtree from a reverse(right-middlee-left) in-order traversal order
self.inOrderTraverse(root.right)
self.greaterSum += root.val
root.val = self.greaterSum
self.inOrderTraverse(root.left)
return root | binary-search-tree-to-greater-sum-tree | Reverse In-order Traversal Python solution | leqinancy | 0 | 14 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,922 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/2607564/Python3-or-Recursive | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
cur_sum = 0
def dfs(node):
nonlocal cur_sum
if not node:
return
dfs(node.right)
node.val += cur_sum # Keep traverse until arrive at the right node, update value
cur_sum = node.val # Remember the sum so far
dfs(node.left) # Continue on the left node
dfs(root)
return root | binary-search-tree-to-greater-sum-tree | Python3 | Recursive | Ploypaphat | 0 | 14 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,923 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/2531502/Easy-Python-Solution-or-O(n)-Time-or-O(1)-Space-or-dfs-or-Reverse-Inorder-Traversal | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
self.sum = 0
def dfs(node):
if not node:
return 0
dfs(node.right)
self.sum += node.val
node.val = self.sum
dfs(node.left)
dfs(root)
return root
``` | binary-search-tree-to-greater-sum-tree | Easy Python Solution | O(n) Time | O(1) Space | dfs | Reverse Inorder Traversal | coolakash10 | 0 | 7 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,924 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/1881868/Python-easy-and-intuitive-solution-using-inorder-traversal | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
stack = [root]
values = []
def inorder(node):
if node:
inorder(node.left)
values.append(node.val)
inorder(node.right)
inorder(root)
prefix = [0]
for val in values:
prefix.append(prefix[-1] + val)
s = sum(values)
d = {}
for i in range(len(values)):
val = values[i]
d[val] = i
stack = [root]
while stack:
node = stack.pop()
node.val = s - prefix[d[node.val]]
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root | binary-search-tree-to-greater-sum-tree | Python easy and intuitive solution using inorder traversal | byuns9334 | 0 | 33 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,925 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/1782718/Python3-solution-using-REVERSE-INORDER | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
def helper(root):
if not root:
return
helper(root.right)
self.s+=root.val
root.val=self.s
helper(root.left)
self.s=0
helper(root)
return root | binary-search-tree-to-greater-sum-tree | Python3 solution using REVERSE INORDER | Karna61814 | 0 | 32 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,926 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/1299739/python-Easy-Reverse-InOrder(right-greaterroot-greaterleft)-beats-99 | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
self.s=0
def customOrder(root):
if root:
customOrder(root.right)
self.s+=root.val
root.val=self.s
customOrder(root.left)
customOrder(root)
return root | binary-search-tree-to-greater-sum-tree | python Easy Reverse InOrder(right->root->left) beats 99% | prakharjagnani | 0 | 84 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,927 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/1012651/Python3-inorder-traversal | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
val = 0
node = root
stack = []
while stack or node:
if node:
stack.append(node)
node = node.right
else:
node = stack.pop()
node.val = val = node.val + val
node = node.left
return root | binary-search-tree-to-greater-sum-tree | [Python3] inorder traversal | ye15 | 0 | 60 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,928 |
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/1012651/Python3-inorder-traversal | class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
def fn(node, val):
"""Return updated node's value."""
if node.right: val = fn(node.right, val)
node.val = val = node.val + val
if node.left: val = fn(node.left, val)
return val
fn(root, 0)
return root | binary-search-tree-to-greater-sum-tree | [Python3] inorder traversal | ye15 | 0 | 60 | binary search tree to greater sum tree | 1,038 | 0.854 | Medium | 16,929 |
https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/391440/Two-Solutions-in-Python-3-(DP)-(Top-Down-and-Bottom-Up) | class Solution:
def minScoreTriangulation(self, A: List[int]) -> int:
SP, LA = [[0]*50 for i in range(50)], len(A)
def MinPoly(a,b):
L, m = b - a + 1, math.inf;
if SP[a][b] != 0 or L < 3: return SP[a][b]
for i in range(a+1,b): m = min(m, A[a]*A[i]*A[b] + MinPoly(a,i) + MinPoly(i,b))
SP[a][b] = m; return SP[a][b]
return MinPoly(0,LA-1) | minimum-score-triangulation-of-polygon | Two Solutions in Python 3 (DP) (Top Down and Bottom Up) | junaidmansuri | 2 | 791 | minimum score triangulation of polygon | 1,039 | 0.547 | Medium | 16,930 |
https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/391440/Two-Solutions-in-Python-3-(DP)-(Top-Down-and-Bottom-Up) | class Solution:
def minScoreTriangulation(self, A: List[int]) -> int:
SP, L = [[0]*50 for _ in range(50)], len(A)
for i in range(2,L):
for j in range(L-i):
s, e, SP[s][e] = j, j + i, math.inf
for k in range(s+1,e): SP[s][e] = min(SP[s][e], A[s]*A[k]*A[e] + SP[s][k] + SP[k][e])
return SP[0][L-1]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | minimum-score-triangulation-of-polygon | Two Solutions in Python 3 (DP) (Top Down and Bottom Up) | junaidmansuri | 2 | 791 | minimum score triangulation of polygon | 1,039 | 0.547 | Medium | 16,931 |
https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/1179823/Python3-top-down-dp | class Solution:
def minScoreTriangulation(self, values: List[int]) -> int:
@cache
def fn(lo, hi):
"""Return minimum score triangulation of values[lo:hi]."""
if lo+3 > hi: return 0
ans = inf
for mid in range(lo+1, hi-1):
ans = min(ans, values[lo]*values[mid]*values[hi-1] + fn(lo, mid+1) + fn(mid, hi))
return ans
return fn(0, len(values)) | minimum-score-triangulation-of-polygon | [Python3] top-down dp | ye15 | 1 | 95 | minimum score triangulation of polygon | 1,039 | 0.547 | Medium | 16,932 |
https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/2827663/Minimum-Score-Triangulation-of-Polygon-Dynamic-Programming | class Solution:
def minScoreTriangulation(self, v: List[int]) -> int:
dp = [[0 for i in range(len(v))] for j in range(len(v))]
n = len(v)
for i in range(n-1,-1,-1):
for j in range(i+2,n):
ans = float('inf')
for k in range(i+1,j):
ans = min(ans, v[i]*v[j]*v[k] + dp[i][k] + dp[k][j])
dp[i][j] = ans
return dp[0][n-1] | minimum-score-triangulation-of-polygon | Minimum Score Triangulation of Polygon Dynamic Programming | sarthakchawande14 | 0 | 1 | minimum score triangulation of polygon | 1,039 | 0.547 | Medium | 16,933 |
https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/2774814/bottom-up-approach-with-graph-explaination | class Solution:
def minScoreTriangulation(self, values: List[int]) -> int:
n = len(values)
dp = [[0 for _ in range(n)] for _ in range(n)]
for L in range(2, n):
for i in range(n-L):
j = i + L
dp[i][j] = float('inf')
for k in range(i+1, j):
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + values[i]*values[k]*values[j])
return dp[0][n-1] | minimum-score-triangulation-of-polygon | bottom-up approach with graph explaination | Fayeyf | 0 | 2 | minimum score triangulation of polygon | 1,039 | 0.547 | Medium | 16,934 |
https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/2034905/PYTHON-SOL-oror-RECURSION-%2B-MEMO-oror-EXPLAINED-oror-WITH-PICTURES-oror | class Solution:
def recursion(self,start,end):
if start >= end :
return 0
if self.dp[start][end] != -1 : return self.dp[start][end]
best = float('inf')
for mid in range(start,end):
tmp = self.recursion(start,mid) + self.recursion(mid+1,end) + \
self.values[start-1]*self.values[mid]*self.values[end]
if tmp < best: best = tmp
self.dp[start][end] = best
return best
def minScoreTriangulation(self, values: List[int]) -> int:
n = len(values)
self.dp = [[-1 for i in range(n)] for j in range(n)]
self.values = values
return self.recursion(1,n-1) | minimum-score-triangulation-of-polygon | PYTHON SOL || RECURSION + MEMO || EXPLAINED || WITH PICTURES || | reaper_27 | 0 | 82 | minimum score triangulation of polygon | 1,039 | 0.547 | Medium | 16,935 |
https://leetcode.com/problems/moving-stones-until-consecutive-ii/discuss/1488487/Python-Sliding-window-with-detailed-expalanation | class Solution:
def numMovesStonesII(self, stones: list[int]) -> list[int]:
"""
1. For the higher bound, it is determined by either moving the leftmost
to the right side, or by moving the rightmost to the left side:
1.1 If moving leftmost to the right side, the available moving
positions are A[n - 1] - A[1] + 1 - (n - 1) =
A[n - 1] - A[1] - n + 2
1.2 If moving rightmost to the left side, the available moving
positions are A[n - 2] - A[0] + 1 - (n - 1) =
A[n - 2] - A[0] - n + 2.
2. For the lower bound, we could use sliding window to find a window
that contains the most consecutive stones (A[i] - A[i - 1] = 1):
2.1 Generally the moves we need are the same as the number of
missing stones in the current window.
2.3 When the window is already consecutive and contains all the
n - 1 stones, we need at least 2 steps to move the last stone
into the current window. For example, 1,2,3,4,10:
2.3.1 We need to move 1 to 6 first as we are not allowed to
move 10 to 5 as it will still be an endpoint stone.
2.3.2 Then we need to move 10 to 5 and now the window becomes
2,3,4,5,6.
"""
A, N = sorted(stones), len(stones)
maxMoves = max(A[N - 1] - A[1] - N + 2, A[N - 2] - A[0] - N + 2)
minMoves = N
# Calculate minimum moves through sliding window.
start = 0
for end in range(N):
while A[end] - A[start] + 1 > N:
start += 1
if end - start + 1 == N - 1 and A[end] - A[start] + 1 == N - 1:
# Case: N - 1 stones with N - 1 positions.
minMoves = min(minMoves, 2)
else:
minMoves = min(minMoves, N - (end - start + 1))
return [minMoves, maxMoves] | moving-stones-until-consecutive-ii | [Python] Sliding window with detailed expalanation | eroneko | 4 | 390 | moving stones until consecutive ii | 1,040 | 0.557 | Medium | 16,936 |
https://leetcode.com/problems/moving-stones-until-consecutive-ii/discuss/1294599/Python3-sliding-window | class Solution:
def numMovesStonesII(self, stones: List[int]) -> List[int]:
stones.sort()
high = max(stones[-1] - stones[1], stones[-2] - stones[0]) - (len(stones) - 2)
ii, low = 0, inf
for i in range(len(stones)):
while stones[i] - stones[ii] >= len(stones): ii += 1
if i - ii + 1 == stones[i] - stones[ii] + 1 == len(stones) - 1: low = min(low, 2)
else: low = min(low, len(stones) - (i - ii + 1))
return [low, high] | moving-stones-until-consecutive-ii | [Python3] sliding window | ye15 | 0 | 165 | moving stones until consecutive ii | 1,040 | 0.557 | Medium | 16,937 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1676693/Python3-Simple-4-Loops-or-O(n)-Time-or-O(1)-Space | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
x = y = 0
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
i = 0
while True:
for do in instructions:
if do == 'G':
x += directions[i][0]
y += directions[i][1]
elif do == 'R':
i = (i + 1) % 4
else:
i = (i - 1) % 4
if i == 0:
return x == 0 and y == 0 | robot-bounded-in-circle | β
[Python3] Simple 4 Loops | O(n) Time | O(1) Space | PatrickOweijane | 5 | 623 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,938 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/850464/Python-3-or-Simulation-or-Explanation | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
direc, pos = 0, [0, 0]
for c in instructions:
if c == "L": direc = (direc + 1) % 4
elif c == "R": direc = (direc - 1) % 4
elif c == "G":
if direc == 0: pos[1] += 1
elif direc == 1: pos[0] -= 1
elif direc == 2: pos[1] -= 1
else: pos[0] += 1
return pos == [0, 0] or direc != 0 | robot-bounded-in-circle | Python 3 | Simulation | Explanation | idontknoooo | 4 | 750 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,939 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1158977/Python-Very-Intuitive-and-Easy-to-understand | class Solution:
cur_dir = 'N'
def isRobotBounded(self, instructions: str) -> bool:
self.cur_dir = 'N'
cur_pos = [0,0]
for ins in instructions:
if ins == 'G':
self.ChangePos(cur_pos)
else:
self.ChangeDirection(ins)
if cur_pos[0] == 0 and cur_pos[1] == 0:
return True
if self.cur_dir != 'N':
return True
return False
def ChangePos(self,cur_pos):
if self.cur_dir == 'N':
cur_pos[1] += 1
elif self.cur_dir == 'S':
cur_pos[1] -= 1
elif self.cur_dir == 'W':
cur_pos[0] -= 1
elif self.cur_dir == 'E':
cur_pos[0] += 1
#think of a compass...and all possiblities of change in direction
def ChangeDirection(self,d):
if self.cur_dir == 'N' and d == 'L':
self.cur_dir = 'W'
elif self.cur_dir == 'N' and d == 'R':
self.cur_dir = 'E'
elif self.cur_dir == 'S' and d == 'L':
self.cur_dir = 'E'
elif self.cur_dir == 'S' and d == 'R':
self.cur_dir = 'W'
elif self.cur_dir == 'W' and d == 'L':
self.cur_dir = 'S'
elif self.cur_dir == 'W' and d == 'R':
self.cur_dir = 'N'
elif self.cur_dir == 'E' and d == 'L':
self.cur_dir = 'N'
elif self.cur_dir == 'E' and d == 'R':
self.cur_dir = 'S' | robot-bounded-in-circle | Python - Very Intuitive and Easy to understand | sn95 | 3 | 424 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,940 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1676745/Python3-LINEAR-()-Explained | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
pos, head = (0, 0), 0
for ch in instructions:
if ch == "G":
pos = (pos[0] + dirs[head][0], pos[1] + dirs[head][1])
elif ch == "L":
head = (head - 1) % 4
else:
head = (head + 1) % 4
return pos == (0, 0) or head != 0 | robot-bounded-in-circle | βοΈ [Python3] LINEAR (β§ββ¦)/β€, Explained | artod | 2 | 572 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,941 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1676591/Simple-4-loops-in-Python | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
def do_instruction(i, j, dir):
for char in instructions:
if char == 'G':
if dir == 0:
i -= 1
elif dir == 1:
j -= 1
elif dir == 2:
i += 1
else:
j += 1
elif char == 'L':
dir = (dir + 1) % 4
else:
dir = (dir - 1) % 4
return i, j, dir
i, j, dir = 0, 0, 0
for _ in range(4):
i, j, dir = do_instruction(i, j, dir)
if i == 0 and j == 0:
return True
return False | robot-bounded-in-circle | Simple 4-loops in Python | kryuki | 2 | 261 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,942 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1676581/Python-solution-with-complex-numbers | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
dirs = {"L": 0 + 1j, "R": 0 - 1j}
pos = 0j
face = 1j
for _ in range(4):
for c in instructions:
if c in "LR":
face *= dirs[c]
else:
pos += face
return pos == 0j | robot-bounded-in-circle | Python solution with complex numbers | mjgallag | 2 | 152 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,943 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/2298635/Python-Straightforward-O(n)-Solution | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
hashmap={}
start=[0,0]
facing="N"
LA={"N":"W","W":"S","S":"E","E":"N"}
RC={"N":"E","E":"S","S":"W","W":"N"}
res=[]
for i in instructions:
if i=="G":
if facing=="N": start[1] += 1
elif facing=="E": start[0] += 1
elif facing=="W": start[0] -= 1
elif facing=="S": start[1] -= 1
elif i=="L":
facing=LA[facing]
elif i=="R":
facing=RC[facing]
if start==[0,0] or facing!="N": return True
else: return False | robot-bounded-in-circle | Python Straightforward O(n) Solution | srikarakkina | 1 | 138 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,944 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/2199554/Python-solution | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
def move(s,direction):
if direction=="N":
s[1]+=1
elif direction=="E":
s[0]+=1
elif direction=="W":
s[0]-=1
else:
s[1]-=1
def get_directionl(curr_dir):
if curr_dir=="N":
return "W"
elif curr_dir=="E":
return "N"
elif curr_dir=="W":
return "S"
else:
return "E"
def get_directionr(curr_dir):
if curr_dir=="N":
return "E"
elif curr_dir=="E":
return "S"
elif curr_dir=="W":
return "N"
else:
return "W"
s = [0,0]
d = "N"
for i in instructions:
if i=="G":
move(s,d)
elif i=="L":
d = get_directionl(d)
else:
d = get_directionr(d)
return (s[0]==0 and s[1]==0) or d!="N" | robot-bounded-in-circle | Python solution | Brillianttyagi | 1 | 135 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,945 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/2037746/PYTHON-SOL-oror-WELL-EXPLAINED-oror-SIMPLE-oror-LINEAR-TIME-oror-LOOP-oror | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
curDirection = 'N'
L = {'N':'W','W':'S','S':'E','E':'N'}
R = {'N':'E','E':'S','S':'W','W':'N'}
moves = {'N':(-1,0),'S':(1,0),'E':(0,1),'W':(0,-1)}
xaxis,yaxis = 0,0
for instruction in instructions:
if instruction == 'G':
addx,addy = moves[curDirection]
xaxis += addx
yaxis += addy
elif instruction == 'L':
curDirection = L[curDirection]
else:
curDirection = R[curDirection]
if xaxis == 0 and yaxis == 0: return True
if curDirection != 'N':return True
return False | robot-bounded-in-circle | PYTHON SOL || WELL EXPLAINED || SIMPLE || LINEAR TIME || LOOP || | reaper_27 | 1 | 147 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,946 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1717490/Python3-Using-complex-number-to-simplify-the-code | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
d = 1j
p = 0
for i in instructions * 4:
if i == 'L': d *= 1j
if i == 'R': d *= -1j
if i == 'G': p += d
return p == 0 | robot-bounded-in-circle | [Python3] Using complex number to simplify the code | BigTailWolf | 1 | 100 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,947 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1677463/Simple-and-Very-Easy-Python-Solution | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
x, y = 0, 0
dx, dy = 0, 1
for i in instructions :
if i == 'L' : #We have to turn Left
dx, dy = -dy, dx
elif i == 'R' : #We have to turn Right
dx, dy = dy, -dx
elif i == 'G' : #we have to move forward
x+= dx
y+= dy
if (x, y) == (0, 0):
return True
if (dx, dy) != (0, 1):
return True
return False | robot-bounded-in-circle | Simple and Very Easy Python Solution | aady_02 | 1 | 82 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,948 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1676972/Python3-Solution-runtime%3A-24ms-faster-than-96.05 | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
di, pos = 0, [0, 0]
for ins in instructions:
if ins == "L": di = (di + 1) % 4
elif ins == "R": di = (di - 1) % 4
elif ins == "G":
if di == 0: pos[1] += 1
elif di == 1: pos[0] -= 1
elif di == 2: pos[1] -= 1
else: pos[0] += 1
return pos == [0, 0] or di != 0 | robot-bounded-in-circle | Python3 Solution runtime: 24ms faster than 96.05% | nomanaasif9 | 1 | 34 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,949 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1581170/Python3-or-Faster-%3A-96.71-or-No-Maths-or-Simple-Solution-or-Only-Using-Direction-Concept | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
# N-> North, S-> South, E-> East, W-> West
# R-> Right, L-> Left
directions = {'N': {'R': 'E', 'L': 'W'}, 'E': {'L': 'N', 'R': 'S'},
'W': {'L': 'S', 'R': 'N'}, 'S': {'R': 'W', 'L': 'E'}}
start = 0
start1 = 0
initial = 'N'
for direction in instructions:
if direction == 'G':
if initial == 'N':
start += 1
elif initial == 'S':
start -= 1
elif initial == 'W':
start1 += 1
elif initial == 'E':
start1 -= 1
else:
initial = directions[initial][direction]
return (start == 0 and start1 == 0) or initial != 'N' | robot-bounded-in-circle | Python3 | Faster : 96.71 | No Maths | Simple Solution | Only Using Direction Concept | Call-Me-AJ | 1 | 180 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,950 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1225502/PythonPython3-Robot-Bounded-In-Circle | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
direction = {
'N+L': 'W',
'W+L': 'S',
'S+L': 'E',
'E+L': 'N',
'N+R': 'E',
'E+R': 'S',
'S+R': 'W',
'W+R': 'N'
}
idx = -1
len_ins = len(instructions)
#visited = set()
start = (0, 0, 'N')
for ins in instructions:
# visited.add(start)
x, y, d = start
if ins == 'G':
if d == 'N':
y += 1
elif d == 'W':
x -= 1
elif d == 'S':
y -= 1
else:
x += 1
else:
d = direction[d+'+'+ins]
start = (x, y, d)
x,y,d = start
return (x == 0 and y ==0) or d != 'N' | robot-bounded-in-circle | [Python/Python3] Robot Bounded In Circle | newborncoder | 1 | 315 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,951 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/2645369/Simulation | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
def follow(x, y, k, i):
d = [(1, 0), (0, 1), (-1, 0), (0, -1)]
for c in i:
if c == "G":
x, y = x + d[k][0], y + d[k][1]
elif c == "L":
k = (k-1)%4
else:
k = (k+1)%4
return x, y, k
x, y, k = 0, 0, 0
for _ in range(4):
x, y, k = follow(x, y, k, instructions)
return x == y == 0 | robot-bounded-in-circle | Simulation | tomfran | 0 | 6 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,952 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/2352774/Python-Easy-and-intuitive-solution-(96) | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
pos, d = [0,0], "N"
def move(d, pos, instructions):
for i in instructions:
if i == "G":
if d == "N": pos[1] += 1
elif d == "S": pos[1] -= 1
elif d == "W": pos[0] -= 1
else: pos[0] += 1
elif i == "L":
if d == "N": d = "W"
elif d == "W": d = "S"
elif d == "S": d = "E"
else: d = "N"
else:
if d == "N": d = "E"
elif d == "W": d = "N"
elif d == "S": d = "W"
else: d = "S"
return (d, pos)
for i in range(4):
d, pos = (move(d, pos, instructions))
return True if pos == [0,0] else False | robot-bounded-in-circle | [Python] Easy and intuitive solution (96%) | SabeerN | 0 | 124 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,953 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/2171241/Python3-Clean-and-Easy | class Solution:
def readInstruction(self, robot, instr):
if instr == "G":
robot[0][0] += robot[1][0]
robot[0][1] += robot[1][1]
elif instr == "R":
robot[1][0], robot[1][1] = robot[1][1], -1 * robot[1][0]
elif instr == "L":
robot[1][0], robot[1][1] = -1 * robot[1][1], robot[1][0]
def isRobotBounded(self, instructions: str) -> bool:
robot = ([0, 0], [0, 1])
for _ in range(4):
for instr in instructions:
self.readInstruction(robot, instr)
if robot[0] == [0, 0]:
return True
return False | robot-bounded-in-circle | Python3 Clean & Easy | hcks | 0 | 82 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,954 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1678782/Rick-provides-Python-Solution-28ms-or-Super-easy-to-understand | class Solution:
def isRobotBounded(self, ins: str) -> bool:
dir1=['N','E','S','W']
dir2=[]
pos=[0,0]
temp,di=0,0
while(True):
for i in ins:
if i=='G':
#pos[(di+1)%2]+=(-1 if di>1 else 1)
if di==0:
pos[1]+=1
elif di==1:
pos[0]+=1
elif di==2:
pos[1]-=1
elif di==3:
pos[0]-=1
elif i=='L':
if di==0:
di=3
else:
di-=1
elif i=='R':
if di==3:
di=0
else:
di+=1
if pos==[0,0]:
return True
elif di==temp:
return False | robot-bounded-in-circle | Rick provides Python Solution 28ms | Super easy to understand | RickSanchez101 | 0 | 40 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,955 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1678541/Python-Just-one-Loop-O(N)-or-O(1) | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
# 0 for North, 1 for East, 2 for South and 3 for West
direction = 0
Gs = 0
position = [0, 0]
for instruction in instructions:
if instruction == "G":
axis = int(direction % 2 == 0)
quantity = 1 if direction > 1 else -1
position[axis] += quantity
continue
elif instruction == "L":
direction = (direction - 1) % 4
else:
direction = (direction + 1) % 4
# We just want to check wether our final position after one loop is either 0 or our direction is north.
# This is correct because we know that if we end up looking at a different direction we know for sure that we will come back
# The corner case happens when we end up looking north but our robot ends in (0, 0). Something like LLLL or GGLLGGLL, so we have to keep track of the position.
return (position[0] == 0 and position[1] == 0) or direction != 0 | robot-bounded-in-circle | Python Just one Loop O(N) | O(1) | Jujusp | 0 | 59 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,956 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1676732/Python-simple-with-only-one-loop | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
direction = 0 #up:0 right:1 down:2 left:3
x,y = 0,0
for i in instructions:
if i=='L':
if direction==0:
direction = 3
else:
direction -= 1
elif i=='R':
if direction==3:
direction = 0
else:
direction += 1
else:
if direction==0:
y += 1
elif direction==1:
x += 1
elif direction==2:
y -= 1
else:
x -= 1
if x==0 and y==0:
return True
if direction!=0:
return True
return False | robot-bounded-in-circle | Python simple with only one loop | 1579901970cg | 0 | 36 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,957 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1630330/Python3-Simple | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
"""
(x, y)
right down left up
if right x + 1
if down y - 1
if left x - 1
if up y + 1
"""
right = 0
down = 1
left = 2
up = 3
curr_direction = right
x_position = 0
y_position = 0
for i in range(4):
for instruction in instructions:
if instruction == "L":
curr_direction -= 1
if curr_direction == -1:
curr_direction = up
elif instruction == "R":
curr_direction += 1
if curr_direction == 4:
curr_direction = right
elif instruction == "G":
if curr_direction == right:
x_position += 1
elif curr_direction == down:
y_position -= 1
elif curr_direction == left:
x_position -= 1
elif curr_direction == up:
y_position += 1
if x_position == 0 and y_position == 0:
return True
return False | robot-bounded-in-circle | Python3 Simple | kanukam123 | 0 | 97 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,958 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1365227/Simple-python3-solution | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
origin = [0,0]
direction = 0 # N=0, E=1, S=2, W=3
# there's four directions, 4 loops are sufficient for robot to return initial state
instructions = instructions*4
# run the instructions
for ins in instructions:
if ins == 'G':
if direction == 0: origin[0]+=1
if direction == 1: origin[1]+=1
if direction == 2: origin[0]-=1
if direction == 3: origin[1]-=1
elif ins == 'L':
if direction == 0: direction = 3
else: direction -= 1
elif ins == 'R':
if direction == 3: direction = 0
else: direction +=1
# determine if it is at (0,0) and pointing north
return origin == [0,0] and direction == 0 | robot-bounded-in-circle | Simple python3 solution | Onlycst | 0 | 112 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,959 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1362854/Python-96-Faster-simple | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
directions = {}
directions[(1, 0)] = dict(L=(0, 1), R=(0, -1)) # East initial step
directions[(0, 1)] = dict(L=(-1, 0), R=(1, 0)) # North
directions[(-1, 0)] = dict(L=(0, -1), R=(0, 1)) # West
directions[(0, -1)] = dict(L=(1, 0), R=(-1, 0)) # South
curr_dir = (0, 1)
pos = [0, 0]
for ins in instructions:
if ins == "G":
pos[0] += curr_dir[0]
pos[1] += curr_dir[1]
else:
curr_dir = directions[curr_dir][ins]
return pos==[0, 0] or curr_dir != (0, 1) | robot-bounded-in-circle | Python 96% Faster, simple | gsbhardwaj27 | 0 | 112 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,960 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1044569/Python3-One-pass | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
def go(ins_index, direc, pos):
"""
direc: 0,1,2,3 => up, right, down, left
"""
if ins_index == len(instructions):
return (direc, pos)
if instructions[ins_index] == 'R':
direc = (direc+1)%4
elif instructions[ins_index] == 'L':
direc = (direc-1)%4
elif instructions[ins_index] == 'G':
pos = (pos[0]+directs[direc][0], pos[1]+directs[direc][1])
else:
raise Exception('wtf')
return go(ins_index+1, direc, pos)
directs = [(0,1), (1,0), (0,-1), (-1,0)]
stop = go(0, 0, (0,0))
return (stop[0]==0 and stop[1] == (0,0)) or stop[0]!=0 | robot-bounded-in-circle | [Python3] One pass | charlie11 | 0 | 95 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,961 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/851316/Python-Solution | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
direction, location = 'N', [0, 0]
l_convert = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
r_convert = {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}
loc_convert = {'N': [0, 1], 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0]}
for i in instructions:
if i == 'G':
location[0] += loc_convert[direction][0]
location[1] += loc_convert[direction][1]
elif i == 'R':
direction = r_convert[direction]
elif i == "L":
direction = l_convert[direction]
return location == [0, 0] or direction != 'N' | robot-bounded-in-circle | Python Solution | marzi_ash | 0 | 43 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,962 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/851257/Python3-simulation | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
x = y = 0
dx, dy = 0, 1
for ss in instructions:
if ss == "G": x, y = x+dx, y+dy
elif ss == "L": dx, dy = -dy, dx
else: dx, dy = dy, -dx
return (x, y) == (0, 0) or (dx, dy) != (0, 1) | robot-bounded-in-circle | [Python3] simulation | ye15 | 0 | 52 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,963 |
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1445004/Python3Python-Simple-solution-w-comments | class Solution:
def isRobotBounded(self, instructions: str) -> bool:
# Dictionary, which outputs change in direction
# given the current direction and instruction
directions = {0: {"G": 0, "L": 3, "R": 1}, # North
1: {"G": 1, "L": 0, "R": 2}, # East
2: {"G": 2, "L": 1, "R": 3}, # South
3: {"G": 3, "L": 2, "R": 0}} # West
# Start position
start = (0,0) # (x,y)
# Function which will run robot once
def moveRobot(curr, direction):
# Loop for each instruction
for instruction in instructions:
# Set position
if instruction == "G":
if direction == 0: # North
curr = (curr[0],curr[1]+1)
elif direction == 1: # East
curr = (curr[0]+1,curr[1])
elif direction == 2: # South
curr = (curr[0],curr[1]-1)
elif direction == 3: # West
curr = (curr[0]-1,curr[1])
else:
pass
# Set direction
direction = directions[direction][instruction]
return (curr, direction)
# Move robot from start position and pointing to North
curr, direction = moveRobot(start,0)
# Case 1:
# If robot return to start then it won't leave a cetrain area
if (curr == start):
return True
# Case 2:
# If robot is not pointing towards north, it means it has changed
# direction, so in next iteration it will change direction again,
# and in next iteration again, and so on, so it will remain it
# a certain bounded area no matter what.
if (direction != 0):
return True
return False | robot-bounded-in-circle | [Python3/Python] Simple solution w/ comments | ssshukla26 | -1 | 209 | robot bounded in circle | 1,041 | 0.553 | Medium | 16,964 |
https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/557619/**Python-Simple-DFS-solution-70-80-** | class Solution:
def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]:
G = defaultdict(list)
for path in paths:
G[path[0]].append(path[1])
G[path[1]].append((path[0]))
colored = defaultdict()
def dfs(G, V, colored):
colors = [1, 2, 3, 4]
for neighbour in G[V]:
if neighbour in colored:
if colored[neighbour] in colors:
colors.remove(colored[neighbour])
colored[V] = colors[0]
for V in range(1, N + 1):
dfs(G, V, colored)
ans = []
for V in range(len(colored)):
ans.append(colored[V + 1])
return ans | flower-planting-with-no-adjacent | **Python Simple DFS solution 70 - 80 %** | art35part2 | 6 | 846 | flower planting with no adjacent | 1,042 | 0.504 | Medium | 16,965 |
https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/412718/Python3-graph | class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
graph = {} # graph as adjacency list
for u, v in paths:
graph.setdefault(u-1, []).append(v-1)
graph.setdefault(v-1, []).append(u-1)
ans = [0]*n
for i in range(n):
ans[i] = ({1,2,3,4} - {ans[ii] for ii in graph.get(i, [])}).pop()
return ans | flower-planting-with-no-adjacent | [Python3] graph | ye15 | 3 | 537 | flower planting with no adjacent | 1,042 | 0.504 | Medium | 16,966 |
https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/1636308/Linear-solution-93-speed | class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
neighbors = defaultdict(set)
for a, b in paths:
neighbors[a].add(b)
neighbors[b].add(a)
ans = [0] * n
for i in range(1, n + 1):
available = {1, 2, 3, 4}
for neighbor in neighbors[i]:
if ans[neighbor - 1] in available:
available.remove(ans[neighbor - 1])
ans[i - 1] = available.pop()
return ans | flower-planting-with-no-adjacent | Linear solution, 93% speed | EvgenySH | 2 | 161 | flower planting with no adjacent | 1,042 | 0.504 | Medium | 16,967 |
https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/379115/Solution-in-Python-3-(six-lines) | class Solution:
def gardenNoAdj(self, n: int, p: List[List[int]]) -> List[int]:
G, B, A = [set([1,2,3,4]) for i in range(n)], [[] for i in range(n)], []
for i in p: B[i[0]-1].append(i[1]), B[i[1]-1].append(i[0])
for i in range(n):
A.append(G[i].pop())
for j in B[i]: G[j-1].discard(A[i])
return A
- Junaid Mansuri
(LeetCode ID)@hotmail.com | flower-planting-with-no-adjacent | Solution in Python 3 (six lines) | junaidmansuri | 2 | 830 | flower planting with no adjacent | 1,042 | 0.504 | Medium | 16,968 |
https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/1989732/Python-oror-graph-16-line-solution | class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
graph = collections.defaultdict(list)
for a, b in paths:
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
res = [1] * n
for i in range(n):
color = set()
for nei in graph[i]:
color.add(res[nei])
if res[i] in color:
for typ in range(1, 5):
if typ not in color:
res[i] = typ
break
return res | flower-planting-with-no-adjacent | Python || graph 16-line solution | gulugulugulugulu | 1 | 73 | flower planting with no adjacent | 1,042 | 0.504 | Medium | 16,969 |
https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/2273319/Easy-To-Understand-Python-Solution | class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
adj = {i:[] for i in range(1,n+1)}
res = [-1]*n
for i in paths:
adj[i[0]].append(i[1])
adj[i[1]].append(i[0])
adj = sorted(adj.items(),key = lambda item:len(item[1]),reverse=True)
for src,neighs in adj:
pos = [1,2,3,4]
for n in neighs:
if res[n-1] in pos:
pos.remove(res[n-1])
res[src-1] = pos.pop()
return res | flower-planting-with-no-adjacent | Easy To Understand Python Solution | harsh30199 | 0 | 38 | flower planting with no adjacent | 1,042 | 0.504 | Medium | 16,970 |
https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/2037840/PYTHON-SOL-oror-EXPLAINED-WITH-PICTURES-oror-DFS-oror-SIMPLE-oror-GRAPH-oror-COLORING | class Solution:
def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:
# n gardens 1 to n
# paths [x,y] bidirectional path between garden x and y
# in each garden plant one of 4 types of flowers
# at most 3 paths coming into or leaving it
# choose flower type -> any two gardens connected by path have different flowers
# return any choice of answers : answer[i] = flower in (i+1)th garden
nodes = [x for x in range(n)]
colour = [None]*n
edges = {x:{} for x in range(n)}
for x,y in paths:
edges[x-1][y-1] = True
edges[y-1][x-1] = True
for node in range(n):
adj = edges[node]
blocked = [False]*n
size = 4
for x in adj:
if colour[x] != None:blocked[colour[x]-1] = True
if blocked[0] == False:
colour[node] = 1
elif blocked[1] == False:
colour[node] = 2
elif blocked[2] == False:
colour[node] = 3
elif blocked[3] == False:
colour[node] = 4
return colour | flower-planting-with-no-adjacent | PYTHON SOL || EXPLAINED WITH PICTURES || DFS || SIMPLE || GRAPH || COLORING | reaper_27 | 0 | 115 | flower planting with no adjacent | 1,042 | 0.504 | Medium | 16,971 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/1621079/Python-Easy-DP-with-Visualization-and-examples | class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
dp = [0]*n
# handle the first k indexes differently
for j in range(k): dp[j]=max(arr[:j+1])*(j+1)
# we can get rid of index i by running i times
for j in range(k,n):
curr = []
for m in range(k):
curr.append(dp[j-m-1] + max(arr[(j-m):(j+1)]) * (m+1))
dp[j] = max(curr)
return dp[-1] | partition-array-for-maximum-sum | [Python] Easy DP with Visualization and examples | sashaxx | 56 | 1,300 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,972 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/2041761/PYTHON-SOL-oror-WELL-EXPLAINED-oror-EASY-oror-RECURSION-%2B-MEMO-oror | class Solution:
def recursion(self,idx,arr,n,maxx,size,k):
if idx == n:
return maxx * size
if (idx,size,maxx) in self.dp: return self.dp[(idx,size,maxx)]
ch1 = self.recursion(idx+1,arr,n,max(maxx,arr[idx]),size+1,k) if size < k else 0
ch2 = self.recursion(idx+1,arr,n,arr[idx],1,k) + maxx*size
best = ch1 if ch1 > ch2 else ch2
self.dp[(idx,size,maxx)] = best
return best
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
# we will try partitioning in every way possible
self.dp = {}
return self.recursion(1,arr,len(arr),arr[0],1,k) | partition-array-for-maximum-sum | PYTHON SOL || WELL EXPLAINED || EASY || RECURSION + MEMO || | reaper_27 | 2 | 200 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,973 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/1456159/Simple-Python-O(nk)-dynamic-programming-solution | class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
# let dp[i] denote the maximum sum for the
# first i elements of arr
# i.e arr[0]...arr[i-1]
n = len(arr)
dp = [0]*(n+1)
for i in range(1, n+1):
window_max = 0
for window_size in range(1, k+1):
if i-window_size < 0: break
window_max = max(window_max, arr[i-window_size])
dp[i] = max(dp[i], dp[i-window_size]+window_max*window_size)
return dp[-1] | partition-array-for-maximum-sum | Simple Python O(nk) dynamic programming solution | Charlesl0129 | 1 | 314 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,974 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/2820398/Python-Simple-or-Recursive-or-Iterative-or-MCM-or-Front-Partition | class Solution:
def maxSumAfterPartitioning(self, arr: List[int], K: int) -> int:
length = len(arr)
@cache
def recurse(i):
if i >= length: return 0
res = 0
for count, k in enumerate(range(i, min(i+K, length)),1):
temp = max(arr[i:k+1])*(count) + recurse(k+1)
res = max(res, temp)
return res
return recurse(0) | partition-array-for-maximum-sum | β
[Python] Simple | Recursive | Iterative | MCM | Front Partition | girraj_14581 | 0 | 1 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,975 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/2820398/Python-Simple-or-Recursive-or-Iterative-or-MCM-or-Front-Partition | class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
dp = [0 for i in range(n+1)]
for i in range(1, n + 1):
current_max = 0
for j in range(1, min(i, k) + 1):
current_max = max(current_max, arr[i - j])
dp[i] = max(dp[i], dp[i - j] + current_max * j)
return dp[n] | partition-array-for-maximum-sum | β
[Python] Simple | Recursive | Iterative | MCM | Front Partition | girraj_14581 | 0 | 1 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,976 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/2727144/Python-Simple-Python-Solution-100-Optimal-Solution | class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
dp = [-1 for _ in range(n)]
def solve(i):
if i == n : return 0
if dp[i] != -1 : return dp[i]
length = 0
maxim = 0
ansmax = 0
for j in range(i, min(n, i+k)):
length += 1
maxim = max(maxim, arr[j])
sumi = length*maxim + solve(j+1)
ansmax = max(ansmax, sumi)
dp[i] = ansmax
return dp[i]
return solve(0) | partition-array-for-maximum-sum | [ Python ] β
Simple Python Solution β
β
β
100% Optimal Solution | vaibhav0077 | 0 | 16 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,977 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/2727144/Python-Simple-Python-Solution-100-Optimal-Solution | class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
dp = [0 for _ in range(n+1)]
for i in range(n-1, -1 ,-1):
length = 0
maxim = 0
ansmax = 0
for j in range(i, min(n, i+k)):
length += 1
maxim = max(maxim, arr[j])
sumi = length*maxim + dp[j+1]
ansmax = max(ansmax, sumi)
dp[i] = ansmax
return dp[0] | partition-array-for-maximum-sum | [ Python ] β
Simple Python Solution β
β
β
100% Optimal Solution | vaibhav0077 | 0 | 16 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,978 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/2228705/Python-easy-to-read-and-understand-or-DP | class Solution:
def solve(self, nums, index, k):
if index == len(nums):
return 0
if index in self.d:
return self.d[index]
res = 0
max_num = 0
for i in range(index, min(len(nums),index+k)):
max_num = max(max_num, nums[i])
max_fill = max_num * (i-index+1)
rem = max_fill + self.solve(nums, i+1, k)
res = max(res, rem)
self.d[index] = res
return res
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
self.d = {}
return self.solve(arr, 0, k) | partition-array-for-maximum-sum | Python easy to read and understand | DP | sanial2001 | 0 | 126 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,979 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/1445952/python-bottom-up-dp-easy-understandable. | class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
dp = [0] * (n+1)
for i in range(1, n+1):
j = (i-1)
m = 0
temp = 0
while j >= 0 and (i-j) <= k:
m = max(m, arr[j])
temp = max(temp, dp[j] + m * (i-j))
j -= 1
dp[i] = temp
return dp[n] | partition-array-for-maximum-sum | python bottom up dp easy understandable. | ashish_chiks | 0 | 183 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,980 |
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/1015136/Python3-dp | class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
@lru_cache(None)
def fn(i):
"""Return maximum sum of arr[:i]."""
if i == 0: return 0 # boundary condition
ans = 0
for kk in range(1, min(i, k)+1):
ans = max(ans, fn(i-kk) + max(arr[ii] for ii in range(i-kk, i)) * kk)
return ans
return fn(len(arr)) | partition-array-for-maximum-sum | [Python3] dp | ye15 | 0 | 97 | partition array for maximum sum | 1,043 | 0.712 | Medium | 16,981 |
https://leetcode.com/problems/longest-duplicate-substring/discuss/2806471/Python-Easy-or-Simple-or-Binary-Solution | class Solution:
def longestDupSubstring(self, s: str) -> str:
length = len(s)
l,r = 0, length-1
result = []
while l<r:
mid = (l+r)//2
d = {}
max_string = ""
for i in range(length-mid):
if d.get(s[i:i+mid+1],0):
max_string = s[i:i+mid+1]
break
d[s[i:i+mid+1]] = 1
if max_string:
l = mid+1
result.append(max_string)
else:
r = mid
return max(result,key=len) if result else "" | longest-duplicate-substring | Python Easy | Simple | Binary Solution | girraj_14581 | 0 | 2 | longest duplicate substring | 1,044 | 0.307 | Hard | 16,982 |
https://leetcode.com/problems/longest-duplicate-substring/discuss/2584996/Simple-python-O(N-logN)-solution | class Solution:
def longestDupSubstring(self, s: str) -> str:
def checkDuplicate(window):
visit = set()
for i in range(0, len(s) - window):
substring = s[i : i + window + 1]
if substring in visit:
return substring
visit.add(substring)
return None
l, r = 0, len(s) - 1
res = ""
while l < r:
mid = l + (r - l) // 2
duplicate = checkDuplicate(mid)
if duplicate:
res = duplicate
l = mid + 1
else:
r = mid
return res | longest-duplicate-substring | Simple python O(N logN) solution | shubhamnishad25 | 0 | 59 | longest duplicate substring | 1,044 | 0.307 | Hard | 16,983 |
https://leetcode.com/problems/longest-duplicate-substring/discuss/2451825/Python-easy-to-read-and-understand-or-all-tecniques | class Solution:
def longestDupSubstring(self, s: str) -> str:
n = len(s)
res = ''
for g in range(n):
i = 0
seen = set()
for j in range(g, n):
if s[i:j+1] in seen:
res = s[i:j+1]
else:
seen.add(s[i:j+1])
i += 1
return res | longest-duplicate-substring | Python easy to read and understand | all tecniques | sanial2001 | 0 | 136 | longest duplicate substring | 1,044 | 0.307 | Hard | 16,984 |
https://leetcode.com/problems/longest-duplicate-substring/discuss/2043032/What-a-mess-(This-Solution-passed-after-7-TLEs) | class Solution:
def longestDupSubstring(self, S: str) -> str:
hi, lo = len(S) - 1, 0
ans = ''
while lo <= hi:
mid = (hi + lo) // 2
substring_set = set()
M = memoryview(S.encode('utf-8'))
for i in range(mid, len(S) + 1):
sub = M[i-mid:i]
if sub in substring_set:
ans = str(sub, 'utf-8')
lo = mid+1
break
else:
substring_set.add(sub)
else:
hi = mid - 1
return ans | longest-duplicate-substring | What a mess (This Solution passed after 7 TLEs) | P3rf3ct0 | 0 | 143 | longest duplicate substring | 1,044 | 0.307 | Hard | 16,985 |
https://leetcode.com/problems/longest-duplicate-substring/discuss/1548046/Python3-rolling-hash | class Solution:
def longestDupSubstring(self, s: str) -> str:
mod = 1_000_000_007
def fn(k):
"""Return duplicated substring of length k."""
p = pow(26, k, mod)
hs = 0
seen = {}
for i, ch in enumerate(s):
hs = (26*hs + ord(ch) - 97) % mod
if i >= k: hs = (hs - (ord(s[i-k])-97)*p) % mod # rolling hash
if i+1 >= k:
if hs in seen and s[i+1-k:i+1] in seen[hs]: return s[i+1-k:i+1] # resolve hash collision
seen.setdefault(hs, set()).add(s[i+1-k:i+1])
return ""
lo, hi = 0, len(s)-1
while lo < hi:
mid = lo + hi + 1 >> 1
if fn(mid): lo = mid
else: hi = mid - 1
return fn(lo) | longest-duplicate-substring | [Python3] rolling hash | ye15 | 0 | 84 | longest duplicate substring | 1,044 | 0.307 | Hard | 16,986 |
https://leetcode.com/problems/longest-duplicate-substring/discuss/1547968/Python3-solution-binary-search-no-rolling-hash | class Solution:
def longestDupSubstring(self, s: str) -> str:
results = set()
window = len(s)//2
largest = ""
while window > len(largest):
for right in range(window, len(s)+1):
substr = s[right-window:right]
if substr in results:
if len(substr) > len(largest):
largest = substr
window += (len(s)-window)//2+1
results.clear()
continue
else:
results.add(substr)
else:
if window == len(largest) + 1:
break
window = max(window//2, len(largest)+1)
return largest | longest-duplicate-substring | Python3 solution, binary search, no rolling hash | brandonso1 | 0 | 181 | longest duplicate substring | 1,044 | 0.307 | Hard | 16,987 |
https://leetcode.com/problems/last-stone-weight/discuss/1921241/Python-Beginner-friendly-Optimisation-Process-with-Explanation | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones.sort()
while stones:
s1 = stones.pop() # the heaviest stone
if not stones: # s1 is the remaining stone
return s1
s2 = stones.pop() # the second-heaviest stone; s2 <= s1
if s1 > s2:
# we need to insert the remaining stone (s1-s2) into the list
pass
# else s1 == s2; both stones are destroyed
return 0 # if no more stones remain | last-stone-weight | [Python] Beginner-friendly Optimisation Process with Explanation | zayne-siew | 91 | 5,800 | last stone weight | 1,046 | 0.647 | Easy | 16,988 |
https://leetcode.com/problems/last-stone-weight/discuss/1921241/Python-Beginner-friendly-Optimisation-Process-with-Explanation | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones.sort()
while stones:
s1 = stones.pop() # the heaviest stone
if not stones: # s1 is the remaining stone
return s1
s2 = stones.pop() # the second-heaviest stone; s2 <= s1
if s1 > s2:
# the remaining stone will be s1-s2
# loop through stones to find the index to insert the stone
for i in range(len(stones)+1):
if i == len(stones) or stones[i] >= s1-s2:
stones.insert(i, s1-s2)
break
# else s1 == s2; both stones are destroyed
return 0 # if no more stones remain | last-stone-weight | [Python] Beginner-friendly Optimisation Process with Explanation | zayne-siew | 91 | 5,800 | last stone weight | 1,046 | 0.647 | Easy | 16,989 |
https://leetcode.com/problems/last-stone-weight/discuss/1921241/Python-Beginner-friendly-Optimisation-Process-with-Explanation | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones.sort()
while stones:
s1 = stones.pop() # the heaviest stone
if not stones: # s1 is the remaining stone
return s1
s2 = stones.pop() # the second-heaviest stone; s2 <= s1
if s1 > s2:
# the remaining stone will be s1-s2
# binary-insert the remaining stone into stones
insort_left(stones, s1-s2)
# else s1 == s2; both stones are destroyed
return 0 # if no more stones remain | last-stone-weight | [Python] Beginner-friendly Optimisation Process with Explanation | zayne-siew | 91 | 5,800 | last stone weight | 1,046 | 0.647 | Easy | 16,990 |
https://leetcode.com/problems/last-stone-weight/discuss/1921241/Python-Beginner-friendly-Optimisation-Process-with-Explanation | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
# first, negate all weight values in-place
for i, s in enumerate(stones):
stones[i] = -s
heapify(stones) # pass all negated values into the min-heap
while stones:
s1 = -heappop(stones) # the heaviest stone
if not stones: # s1 is the remaining stone
return s1
s2 = -heappop(stones) # the second-heaviest stone; s2 <= s1
if s1 > s2:
heappush(stones, s2-s1) # push the NEGATED value of s1-s2; i.e., s2-s1
# else s1 == s2; both stones are destroyed
return 0 # if no more stones remain | last-stone-weight | [Python] Beginner-friendly Optimisation Process with Explanation | zayne-siew | 91 | 5,800 | last stone weight | 1,046 | 0.647 | Easy | 16,991 |
https://leetcode.com/problems/last-stone-weight/discuss/437380/Python-Simple-Solution | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones.sort()
while len(stones)>1:
t = stones.pop()
u = stones.pop()
if t==u:
continue
else:
stones.append(t-u)
stones.sort()
return stones[0] if stones else 0 | last-stone-weight | Python Simple Solution | saffi | 5 | 358 | last stone weight | 1,046 | 0.647 | Easy | 16,992 |
https://leetcode.com/problems/last-stone-weight/discuss/1357203/Easy-Python-Solution(99.91) | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
while len(stones) != 1:
stones.sort()
if len(stones)>2:
if stones[-1]==stones[-2]:
del stones[-1]
del stones[-1]
elif stones[-1]>stones[-2]:
stones[-1]-=stones[-2]
del stones[-2]
else:
return stones[-1]-stones[-2]
return stones[0] | last-stone-weight | Easy Python Solution(99.91%) | Sneh17029 | 4 | 538 | last stone weight | 1,046 | 0.647 | Easy | 16,993 |
https://leetcode.com/problems/last-stone-weight/discuss/1922677/Python-Simple-Python-Solution | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
while len(stones)>1:
sort_stones = sorted(stones)
small_num, large_num = sort_stones[-2], sort_stones[-1]
if small_num == large_num :
stones = sort_stones[:-2]
else:
sort_stones.remove(small_num)
sort_stones.remove(large_num)
sort_stones.append(large_num - small_num)
stones = sort_stones
if len(stones)==1:
return stones[0]
else:
return 0 | last-stone-weight | [ Python ]β
Simple Python Solution π₯³ | ASHOK_KUMAR_MEGHVANSHI | 3 | 171 | last stone weight | 1,046 | 0.647 | Easy | 16,994 |
https://leetcode.com/problems/last-stone-weight/discuss/2103047/PYTHON-or-Simple-python-solution | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones = sorted(stones)
while len(stones) > 1:
if stones[-1] == stones[-2]:
stones.remove(stones[-2])
stones.remove(stones[-1])
else:
stones[-1] = stones[-1] - stones[-2]
stones.remove(stones[-2])
stones = sorted(stones)
return stones[0] if stones else 0 | last-stone-weight | PYTHON | Simple python solution | shreeruparel | 2 | 71 | last stone weight | 1,046 | 0.647 | Easy | 16,995 |
https://leetcode.com/problems/last-stone-weight/discuss/2250010/Python-Pop-and-Sort-oror-Fast-Short-and-Simple | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
while(len(stones)>1):
stones.sort()
stones.append(abs(stones.pop() - stones.pop()))
return(stones[0]) | last-stone-weight | Python Pop and Sort || Fast , Short and Simple | Yodawgz0 | 1 | 51 | last stone weight | 1,046 | 0.647 | Easy | 16,996 |
https://leetcode.com/problems/last-stone-weight/discuss/1924258/Python3-Solution-(-) | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones.sort()
while True:
try:
# if the index error happens on this line, it will return x = 0
x = stones.pop()
# if the index error happens on this line, it will return what x equaled in the line above
y = stones.pop()
leftover = x - y
if leftover:
stones.append(leftover)
stones.sort()
x = 0
except IndexError:
return x
``` | last-stone-weight | πΏ Python3 Solution π
π΄π
π
π²π»π΄π°π
( Ν‘ποΈβ―ΝΚ Ν‘ποΈ) | IvetteDF | 1 | 30 | last stone weight | 1,046 | 0.647 | Easy | 16,997 |
https://leetcode.com/problems/last-stone-weight/discuss/1921691/Python-beginner-friendly-solution-using-sorting | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
while len(stones) > 1:
stones.sort()
s1 = stones.pop()
s2 = stones.pop()
stones.append(abs(s1 - s2))
return stones[0] | last-stone-weight | Python beginner friendly solution using sorting | alishak1999 | 1 | 88 | last stone weight | 1,046 | 0.647 | Easy | 16,998 |
https://leetcode.com/problems/last-stone-weight/discuss/1921593/python-3-solution-oror-using-list-oror-sorting-oror-without-heap-oror-faster-approach | class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
if len(stones)==1:
return stones[0]
stones.sort(reverse=True)
p=0
while p+1<len(stones):
if stones[p]==stones[p+1]:
stones.pop(p)
stones.pop(p)
else:
temp=stones.pop(p)
stones.append(abs(stones.pop(p)-temp))
stones.sort(reverse=True)
print(stones)
if len(stones)==0:
return 0
return stones[0] | last-stone-weight | python 3 solution || using list || sorting || without heap || faster approach | nileshporwal | 1 | 27 | last stone weight | 1,046 | 0.647 | Easy | 16,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.