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/flip-binary-tree-to-match-preorder-traversal/discuss/982172/Python3-recursive-dfs | class Solution:
def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
ans = []
stack = [root]
k = 0
while stack:
node = stack.pop()
if node:
if node.val != voyage[k]: return [-1] # impossible
k += 1
if node.right and node.right.val == voyage[k]:
if node.left: ans.append(node.val)
stack.extend([node.left, node.right])
else:
stack.extend([node.right, node.left])
return ans | flip-binary-tree-to-match-preorder-traversal | [Python3] recursive dfs | ye15 | -1 | 92 | flip binary tree to match preorder traversal | 971 | 0.499 | Medium | 15,700 |
https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/discuss/982172/Python3-recursive-dfs | class Solution:
def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
ans = []
stack = [root]
i = 0
while stack:
node = stack.pop()
if node:
if node.val != voyage[i]: return [-1]
i += 1
if node.left and node.right and voyage[i] == node.right.val:
ans.append(node.val)
node.left, node.right = node.right, node.left
stack.extend([node.right, node.left])
return ans | flip-binary-tree-to-match-preorder-traversal | [Python3] recursive dfs | ye15 | -1 | 92 | flip binary tree to match preorder traversal | 971 | 0.499 | Medium | 15,701 |
https://leetcode.com/problems/equal-rational-numbers/discuss/405505/Python-3-(beats-~99)-(six-lines) | class Solution:
def isRationalEqual(self, S: str, T: str) -> bool:
L, A = [len(S), len(T)], [S,T]
for i,p in enumerate([S,T]):
if '(' in p:
I = p.index('(')
A[i] = p[0:I] + 7*p[I+1:L[i]-1]
return abs(float(A[0])-float(A[1])) < 1E-7
- Junaid Mansuri | equal-rational-numbers | Python 3 (beats ~99%) (six lines) | junaidmansuri | 1 | 119 | equal rational numbers | 972 | 0.43 | Hard | 15,702 |
https://leetcode.com/problems/equal-rational-numbers/discuss/2840497/Fraction-Expansion-using-Stack-python | class Solution:
def isRationalEqual(self, s: str, t: str) -> bool:
repeat = 1000
res = []
for word in (s, t):
stack = []
for char in word:
if char == ")":
nums = ""
char = ""
while char != "(" and stack:
nums += char
char = stack.pop(-1)
stack.append( nums[::-1] * repeat )
else:
stack.append(char)
res.append(("".join(stack))[:100])
return float(res[0]) == float(res[1])
``` | equal-rational-numbers | Fraction Expansion using Stack python | complete_noob | 0 | 4 | equal rational numbers | 972 | 0.43 | Hard | 15,703 |
https://leetcode.com/problems/equal-rational-numbers/discuss/1584870/Python3-brute-force | class Solution:
def isRationalEqual(self, s: str, t: str) -> bool:
def fn(s):
"""Return normalized string."""
if "." not in s: return s # edge case - xxx
xxx, frac = s.split('.')
if not frac: return xxx # edge case - xxx.
if '(' in frac:
nonrep, rep = frac.split('(')
rep = rep.rstrip(')')
while nonrep and rep and nonrep[-1] == rep[-1]: # normalize repeating part
nonrep = nonrep[:-1]
rep = rep[-1] + rep[:-1]
if len(rep) > 1 and len(set(rep)) == 1: rep = rep[0] # edge case (11)
if rep[:2] == rep[2:]: rep = rep[:2] # edge case (1212)
if rep == "0": rep = "" # edge case - (0)
if rep == "9": # edge case - (9)
rep = ""
if nonrep: nonrep = nonrep[:-1] + str(int(nonrep[-1]) + 1)
else: xxx = str(int(xxx) + 1)
frac = ""
if rep: frac = f"({rep})"
if nonrep: frac = nonrep + frac
if '(' not in frac: # remove trailing 0's
while frac and frac[-1] == '0': frac = frac[:-1]
return xxx + "." + frac if frac else xxx
return fn(s) == fn(t) | equal-rational-numbers | [Python3] brute force | ye15 | 0 | 48 | equal rational numbers | 972 | 0.43 | Hard | 15,704 |
https://leetcode.com/problems/equal-rational-numbers/discuss/1584870/Python3-brute-force | class Solution:
def isRationalEqual(self, s: str, t: str) -> bool:
fn = lambda x: float(x[:i] + x[i+1:-1] * 17 if (i := x.find('(')) >= 0 else float(x))
return fn(s) == fn(t) | equal-rational-numbers | [Python3] brute force | ye15 | 0 | 48 | equal rational numbers | 972 | 0.43 | Hard | 15,705 |
https://leetcode.com/problems/equal-rational-numbers/discuss/1543790/Convert-to-float-96-speed | class Solution:
def to_float(self, n: str) -> float:
if "." not in n:
return float(n)
whole, dec = n.split(".")
if dec:
if "(" in dec:
idx_bracket = dec.index("(")
return float(f"{whole}.{dec[:idx_bracket]}{dec[idx_bracket + 1: -1] * 17}")
return float(f"{whole}.{dec}")
return float(f"{whole}.")
def isRationalEqual(self, s: str, t: str) -> bool:
return abs(self.to_float(s) - self.to_float(t)) < 1e-16 | equal-rational-numbers | Convert to float, 96% speed | EvgenySH | 0 | 31 | equal rational numbers | 972 | 0.43 | Hard | 15,706 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1647325/Python3-ONE-LINER-Explained | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
return sorted(points, key = lambda p: p[0]**2 + p[1]**2)[0:k] | k-closest-points-to-origin | ✔️ [Python3] ONE-LINER, Explained | artod | 9 | 2,000 | k closest points to origin | 973 | 0.658 | Medium | 15,707 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/659991/Python3-oneliner-using-sorted()-and-lambda-which-beats-98 | class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
return sorted(points, key=lambda p: p[0]*p[0] + p[1]*p[1])[:K] | k-closest-points-to-origin | [Python3] oneliner using sorted() and lambda which beats 98% | gshguru | 5 | 265 | k closest points to origin | 973 | 0.658 | Medium | 15,708 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2566908/Python3-1-Liner! | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
return [points[i] for d, i in sorted([(math.sqrt(x**2 + y**2), i) for i, [x, y] in enumerate(points)])[:k]] | k-closest-points-to-origin | Python3 1 Liner! | ryangrayson | 3 | 165 | k closest points to origin | 973 | 0.658 | Medium | 15,709 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/663130/Python3-3-approaches%3A-sort-heap-quick-select | class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
return sorted(points, key=lambda x: x[0]**2 + x[1]**2)[:K] | k-closest-points-to-origin | [Python3] 3 approaches: sort, heap, quick select | ye15 | 3 | 123 | k closest points to origin | 973 | 0.658 | Medium | 15,710 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/663130/Python3-3-approaches%3A-sort-heap-quick-select | class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
return nsmallest(K, points, key=lambda x: x[0]**2 + x[1]**2) | k-closest-points-to-origin | [Python3] 3 approaches: sort, heap, quick select | ye15 | 3 | 123 | k closest points to origin | 973 | 0.658 | Medium | 15,711 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/663130/Python3-3-approaches%3A-sort-heap-quick-select | class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
pq = [] # max-heap
for x, y in points:
heappush(pq, (-x*x-y*y, x, y))
if len(pq) > K: heappop(pq)
return [(x, y) for _, x, y in pq] | k-closest-points-to-origin | [Python3] 3 approaches: sort, heap, quick select | ye15 | 3 | 123 | k closest points to origin | 973 | 0.658 | Medium | 15,712 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/663130/Python3-3-approaches%3A-sort-heap-quick-select | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
def partition(lo, hi):
"""Return partition of dist[lo:hi]."""
i, j = lo+1, hi-1
while i <= j:
if dist[i] < dist[lo]: i += 1
elif dist[j] > dist[lo]: j -= 1
else:
dist[i], dist[j] = dist[j], dist[i]
i += 1
j -= 1
dist[lo], dist[j] = dist[j], dist[lo]
return j
dist = [x*x+y*y for x, y in points]
shuffle(dist)
lo, hi = 0, len(dist)
while lo < hi:
mid = partition(lo, hi)
if mid + 1 < k: lo = mid + 1
elif mid + 1 == k: break
else: hi = mid
return [[x, y] for x, y in points if x*x + y*y <= dist[mid]] | k-closest-points-to-origin | [Python3] 3 approaches: sort, heap, quick select | ye15 | 3 | 123 | k closest points to origin | 973 | 0.658 | Medium | 15,713 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1648926/Python3-O(n-%2B-klogn)-Time-or-O(n)-Space-or-3-Lines-or-Using-Heapify-and-Heappop | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
points = [(p[0]**2 + p[1]**2, p) for p in points]
heapify(points)
return [heappop(points)[1] for _ in range(k)] | k-closest-points-to-origin | [Python3] O(n + klogn) Time | O(n) Space | 3 Lines | Using Heapify & Heappop | PatrickOweijane | 2 | 279 | k closest points to origin | 973 | 0.658 | Medium | 15,714 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1048732/PythonPython3-or-K-Closest-Points-to-Origin-or-One-Liner | class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
if K == len(points):
return points
return [j for j in sorted(points, key=lambda x: x[0]*x[0] + x[1]*x[1])[:K]] | k-closest-points-to-origin | [Python/Python3] | K Closest Points to Origin | One-Liner | newborncoder | 2 | 554 | k closest points to origin | 973 | 0.658 | Medium | 15,715 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1048732/PythonPython3-or-K-Closest-Points-to-Origin-or-One-Liner | class Solution:
def kClosest(self, points, K):
return heapq.nsmallest(K, points, key=lambda x: x[0] * x[0] + x[1] * x[1]) | k-closest-points-to-origin | [Python/Python3] | K Closest Points to Origin | One-Liner | newborncoder | 2 | 554 | k closest points to origin | 973 | 0.658 | Medium | 15,716 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2280045/Python-1-Liner | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
return [p[1] for p in sorted([(p[0] ** 2 + p[1] ** 2 ,p) for p in points], key=lambda t: t[0])[:k]] | k-closest-points-to-origin | Python 1-Liner | amaargiru | 1 | 66 | k closest points to origin | 973 | 0.658 | Medium | 15,717 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2097489/Python3-Simple-Solution-Using-Minheap | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
res=[]
for p in points:
res.append((p[0]**2+p[1]**2,p))
return [item[1] for item in heapq.nsmallest(k,res)] | k-closest-points-to-origin | [Python3] Simple Solution Using Minheap | Jason_Zhong | 1 | 62 | k closest points to origin | 973 | 0.658 | Medium | 15,718 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1939385/PYTHON-SOL-oror-HEAP-oror-EXPLAINED-oror-SIMPLE-oror | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
heap = []
n = len(points)
if k > n : k = n
for point in points:
x,y = point
dis = x**2 + y**2
if len(heap) < k:
heapq.heappush(heap,(-dis,x,y))
else:
if dis < -heap[0][0] :
heapq.heappop(heap)
heapq.heappush(heap,(-dis,x,y))
ans = []
while heap:
dis , x ,y = heapq.heappop(heap)
dis = -dis
ans.append([x,y])
return ans | k-closest-points-to-origin | PYTHON SOL || HEAP || EXPLAINED || SIMPLE || | reaper_27 | 1 | 103 | k closest points to origin | 973 | 0.658 | Medium | 15,719 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1928410/Python-Solution-or-Sort-List-A-Based-on-List-B-or-Clean-Code | class Solution:
def findDistance(self,point):
return (point[0] - 0)**2 + (point[1] - 0)**2
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
return sorted(points,key=self.findDistance)[:k] | k-closest-points-to-origin | Python Solution | Sort List A Based on List B | Clean Code | Gautam_ProMax | 1 | 31 | k closest points to origin | 973 | 0.658 | Medium | 15,720 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1536248/Python-90%2B%2B-Faster-easy-sort-solution | class Solution:
def kClosest(self, p: List[List[int]], k: int) -> List[List[int]]:
def magic(e):
x, y = e[0], e[1]
return x ** 2 + y ** 2
p.sort(key = magic)
return p[:k] | k-closest-points-to-origin | Python 90%++ Faster easy sort solution | aaffriya | 1 | 416 | k closest points to origin | 973 | 0.658 | Medium | 15,721 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1371231/Python-Quickselect-template | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
def partition(left, right, pivot_index):
pivot = points[pivot_index]
points[pivot_index], points[right] = points[right], points[pivot_index]
index = left
for i in range(left, right):
if points[i][0]**2 + points[i][1]**2 <= pivot[0]**2 + pivot[1]**2:
points[index], points[i] = points[i], points[index]
index += 1
points[index], points[right] = points[right], points[index]
return index
def quick(left = 0, right = len(points)-1):
if left > right: return
pivot_index = random.randint(left, right)
index = partition(left, right, pivot_index)
if index == k: return
elif index > k: quick(left, index-1)
else: quick(index+1, right)
quick()
return points[:k] | k-closest-points-to-origin | [Python] Quickselect template | soma28 | 1 | 161 | k closest points to origin | 973 | 0.658 | Medium | 15,722 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1099684/Python3-Heap-solution.-beats-93 | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
h = []
for i,j in points:
dist = i*i + j*j
heapq.heappush(h,(dist,i,j))
res = []
for x in range(k):
dist,i,j = heapq.heappop(h)
res.append((i,j))
return res | k-closest-points-to-origin | [Python3] Heap solution. beats 93% | tilak_ | 1 | 114 | k closest points to origin | 973 | 0.658 | Medium | 15,723 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/1047015/Python-3-1-Liner-using-SORT-and-LAMBDA. | class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
return sorted(points, key = lambda A: A[0]**2 + A[1]**2)[:K] | k-closest-points-to-origin | [Python 3] - 1 Liner using SORT & LAMBDA. | mb557x | 1 | 66 | k closest points to origin | 973 | 0.658 | Medium | 15,724 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/701378/Python-3K-Closest-Points-to-Origin.-Beats-98.-math.sort(-). | class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
points.sort(key=lambda nums: math.sqrt(nums[0]**2 + nums[1]**2 ))
return points[:K] | k-closest-points-to-origin | [Python 3]K Closest Points to Origin. Beats 98%. math.sort( ). | tilak_ | 1 | 197 | k closest points to origin | 973 | 0.658 | Medium | 15,725 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/393955/Two-Solutions-in-Python-3-(Sort-and-Heap)-(one-line) | class Solution:
def kClosest(self, P: List[List[int]], K: int) -> List[List[int]]:
return sorted(P, key = lambda x: x[0]**2 + x[1]**2)[:K] | k-closest-points-to-origin | Two Solutions in Python 3 (Sort and Heap) (one line) | junaidmansuri | 1 | 431 | k closest points to origin | 973 | 0.658 | Medium | 15,726 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/393955/Two-Solutions-in-Python-3-(Sort-and-Heap)-(one-line) | class Solution:
def kClosest(self, P: List[List[int]], K: int) -> List[List[int]]:
return heapq.nsmallest(K, P, key = lambda x: x[0]**2 + x[1]**2)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | k-closest-points-to-origin | Two Solutions in Python 3 (Sort and Heap) (one line) | junaidmansuri | 1 | 431 | k closest points to origin | 973 | 0.658 | Medium | 15,727 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2842873/PYTHON-oror-HEAP-oror-SOLUTION | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
### method 1
# heap = []
# for i in points:
# val = pow(i[0]**2+i[1]**2,1/2)
# heapq.heappush(heap,(val,i))
# res = []
# while len(res)<k and heap!=[]:
# v = heapq.heappop(heap)
# res.append(v[1])
# return res;
#method 2
return heapq.nsmallest(k, points, lambda x: x[0] * x[0] + x[1] * x[1]) | k-closest-points-to-origin | PYTHON || HEAP || SOLUTION | cheems_ds_side | 0 | 4 | k closest points to origin | 973 | 0.658 | Medium | 15,728 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2842267/Easy-or-Lambda-function-based-solution-or-O(nlogn)-complexity | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
def distance(x,y):
return (x**2 + y**2) ** 0.5
points.sort(key = lambda i : distance(i[0], i[1]))
return points[:k] | k-closest-points-to-origin | Easy | Lambda function based solution | O(nlogn) complexity | Aadya12 | 0 | 3 | k closest points to origin | 973 | 0.658 | Medium | 15,729 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2828436/PYTHON-or-Time-Complexity-beats-98.18 | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
stack=[]
temp=[]
for idx,i in enumerate(points):
dis=sqrt(i[0]*i[0]+i[1]*i[1])
i.append(dis)
points=sorted(points, key=lambda i:i[2])
for i in range(0,k):
temp.append(points[i][0])
temp.append(points[i][1])
stack.append(temp)
temp=[]
return stack | k-closest-points-to-origin | PYTHON | Time Complexity beats 98.18 % | BARAHI1998 | 0 | 1 | k closest points to origin | 973 | 0.658 | Medium | 15,730 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2808186/Python-min-heap | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
minHeap = []
origin = [0, 0]
for p in points:
distance = self.calculateDistance(origin, p)
heapq.heappush(minHeap, [distance, p])
res = []
while k > 0:
res.append(heapq.heappop(minHeap)[1])
k -= 1
return res
def calculateDistance(self, p1, p2):
return math.sqrt((p1[0]-p2[0]) ** 2 + (p1[1]-p2[1]) ** 2) | k-closest-points-to-origin | Python min heap | zananpech9 | 0 | 3 | k closest points to origin | 973 | 0.658 | Medium | 15,731 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2788082/Python3-oror-Sorting-two-liner | class Solution(object):
def kClosest(self, points, k):
points.sort(key= lambda x: x[0]**2 + x[1]**2)
return points[:k] | k-closest-points-to-origin | Python3 || Sorting two liner | kgirma363 | 0 | 4 | k closest points to origin | 973 | 0.658 | Medium | 15,732 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2782796/Python-Solution | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
hm={}
for x in points:
temp=(x[0]**2+x[1]**2)**0.5
if temp in hm.keys():
hm[temp].append(x)
else:
hm[temp]=[]
hm[temp].append(x)
key=[item for item in sorted(hm.keys())]
res=hm[key[0]]
for x in key[1:]:
res+=hm[x]
return res[:k] | k-closest-points-to-origin | Python Solution | annazhengzhu | 0 | 5 | k closest points to origin | 973 | 0.658 | Medium | 15,733 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2779110/heap-approach-python | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
# O(n*log(k)), O(k)
pnt = []
for x, y in points:
dis = (abs(x - 0) ** 2) + (abs(y - 0) ** 2)
pnt.append([dis, x, y])
res = []
heapq.heapify(pnt)
for i in range(k):
dis, x, y = heapq.heappop(pnt)
res.append([x, y])
return res | k-closest-points-to-origin | heap approach python | sahilkumar158 | 0 | 1 | k closest points to origin | 973 | 0.658 | Medium | 15,734 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2701097/K-Closest-Points-to-Origin-or-Max-heapor-Python3-or-Java | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
points.sort(key= lambda p: p[0]*p[0]+p[1]*p[1] )
return points[:k] | k-closest-points-to-origin | K Closest Points to Origin | Max heap| Python3 | Java | NitishKumarVerma | 0 | 10 | k closest points to origin | 973 | 0.658 | Medium | 15,735 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2701097/K-Closest-Points-to-Origin-or-Max-heapor-Python3-or-Java | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
maxheap = []
for x,y in points:
d = math.sqrt(x**2 + y**2)
if len(maxheap)<k:
heapq.heappush(maxheap,(-d,[x,y]))
else:
if maxheap[0][0]< -d:
heapq.heappushpop(maxheap,(-d,[x,y]))
return [el[1] for el in maxheap] | k-closest-points-to-origin | K Closest Points to Origin | Max heap| Python3 | Java | NitishKumarVerma | 0 | 10 | k closest points to origin | 973 | 0.658 | Medium | 15,736 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2669851/My-awful-solution!-(No-heap-just-binary-sort.) | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
my_dict = {}
closest_points = [[0,0]*len(points)]
distance_list = []
for point in points: #Construct lookup table for points.
(x, y) = point[0], point[1]
dist = point[0]*point[0] + point[1] * point[1]
my_dict[(x, y)] = dist
low = 0
high = 0
#Sort points using binary sort.
for point in points:
key = (point[0], point[1])
insert_dist = my_dict[key]
high = len(closest_points)
low = 0
mid = int((high + low) / 2)
while high - low > 1:
if insert_dist == distance_list[mid-1]:
mid = mid-1
break
if insert_dist < distance_list[mid-1]: #Distance is shorter than
high = mid
mid = int((high+low)/2)
if insert_dist > distance_list[mid-1]:
low = mid
mid = int((high+low)/2)
distance_list.insert(mid, insert_dist)
closest_points.insert(mid, key)
return closest_points[:k] | k-closest-points-to-origin | My awful solution! (No heap, just binary sort.) | mephiticfire | 0 | 4 | k closest points to origin | 973 | 0.658 | Medium | 15,737 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2652917/Heaps-(one-line-of-code)-O(n-log(k)) | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
k_l = heapq.nsmallest(k, points, key=lambda x: x[0]**2+x[1]**2)
return k_l | k-closest-points-to-origin | Heaps (one line of code) O(n log(k)) | anjul_tyagi | 0 | 5 | k closest points to origin | 973 | 0.658 | Medium | 15,738 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2446092/K-Closest-Points-to-Origin-oror-Python3 | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
points.sort(key = lambda x: x[0] ** 2 + x[1] ** 2)
return points[:k] | k-closest-points-to-origin | K Closest Points to Origin || Python3 | vanshika_2507 | 0 | 37 | k closest points to origin | 973 | 0.658 | Medium | 15,739 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2431882/Python-3%3A-O(n-%2B-klog-n)-Solution | class Solution:
def getDistance(self, point):
x, y = point
return x*x + y*y
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
heap = [[self.getDistance(point), point] for point in points]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in range(k)] | k-closest-points-to-origin | Python 3: O(n + klog n) Solution | edward0414 | 0 | 80 | k closest points to origin | 973 | 0.658 | Medium | 15,740 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2373403/Python-or-97-faster-or-Easy-3-lines-of-code-using-heap | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
dis_point_lst = [(p[0]**2 + p[1]**2,p) for p in points]
heapq.heapify(dis_point_lst)
return [heapq.heappop(dis_point_lst)[1] for _ in range(k)] | k-closest-points-to-origin | Python | 97% faster | Easy 3 lines of code using heap | __Asrar | 0 | 116 | k closest points to origin | 973 | 0.658 | Medium | 15,741 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2344498/Python-runtime-94.93-memory-20.53 | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
ans = []
for point in points:
ans.append(point)
self.heapifyUp(ans, len(ans)-1)
if len(ans) > k:
ans[0], ans[-1] = ans[-1], ans[0]
ans.pop()
self.heapifyDown(ans, 0)
return ans
def heapifyDown(self, ans, index):
if index < len(ans):
pointDis = ans[index][0]*ans[index][0] + ans[index][1]*ans[index][1]
leftDis = rightDis = -1
if index*2 + 1 < len(ans):
left = ans[index*2 + 1]
leftDis = left[0]*left[0] + left[1]*left[1]
if index*2 + 2 < len(ans):
right = ans[index*2 + 2]
rightDis = right[0]*right[0] + right[1]*right[1]
if pointDis < max(leftDis, rightDis):
if leftDis >= rightDis:
ans[index], ans[index*2 + 1] = ans[index*2 + 1], ans[index]
self.heapifyDown(ans, index*2 + 1)
else:
ans[index], ans[index*2 + 2] = ans[index*2 + 2], ans[index]
self.heapifyDown(ans, index*2 + 2)
def heapifyUp(self, ans, index):
if index > 0:
point = ans[index]
pointDis = point[0]*point[0] + point[1]*point[1]
parent = ans[(index-1)//2]
parentDis = parent[0]*parent[0] + parent[1]*parent[1]
if pointDis > parentDis:
ans[index], ans[(index-1)//2] = ans[(index-1)//2], ans[index]
self.heapifyUp(ans, (index-1)//2) | k-closest-points-to-origin | Python, runtime 94.93%, memory 20.53% | tsai00150 | 0 | 77 | k closest points to origin | 973 | 0.658 | Medium | 15,742 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2338805/easy-python-solution | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
distance = []
for point in points :
dis = pow((pow((0-point[0]), 2) + pow((0-point[1]), 2)), 0.5)
distance.append([point, dis])
distance.sort(key = lambda x : x[1])
ans = []
for i in range(k) :
ans.append(distance[i][0])
return ans | k-closest-points-to-origin | easy python solution | sghorai | 0 | 50 | k closest points to origin | 973 | 0.658 | Medium | 15,743 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2237442/Python-2-liner-O(n-log-n)-96th-percentile-speed | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
points.sort(key=lambda point: point[0] ** 2 + point[1] ** 2) # if x <= y, sqrt(x) <= sqrt(y) -- so we don't have to apply sqrt for sorting
return points[:k] | k-closest-points-to-origin | Python 2-liner, O(n log n), 96th percentile speed | linusmixson | 0 | 35 | k closest points to origin | 973 | 0.658 | Medium | 15,744 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2220231/Python-easy-1-line-Solution-or-Beats-99 | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
return sorted(points, key = lambda x: x[0] * x[0] + x[1] * x[1])[:k]
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
heap=[]
for (x,y) in points:
dist= -(x**2+y**2)
if len(heap)==k:
heapq.heappushpop(heap,(dist,x,y))
else:
heapq.heappush(heap,(dist,x,y))
return ([(x,y) for (dist,x,y) in heap]) | k-closest-points-to-origin | Python easy 1 line Solution | Beats 99% | lonewaker | 0 | 50 | k closest points to origin | 973 | 0.658 | Medium | 15,745 |
https://leetcode.com/problems/k-closest-points-to-origin/discuss/2167976/Python-one-liner.-Beat-99-when-I-ran-it | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
return sorted(points, key = lambda x: x[0] ** 2 + x[1] ** 2)[:k] | k-closest-points-to-origin | Python one-liner. Beat 99% when I ran it | sak_agarwal | 0 | 93 | k closest points to origin | 973 | 0.658 | Medium | 15,746 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/1060120/Python3-O(N)-HashMap-and-Prefix-Sum | class Solution:
def subarraysDivByK(self, A: List[int], k: int) -> int:
dic = collections.defaultdict(int)
dic[0] = 1
ans = 0
presum = 0
for num in A:
presum += num
ans += dic[presum%k]
dic[presum%k] += 1
return ans
``` | subarray-sums-divisible-by-k | Python3 O(N) HashMap and Prefix Sum | coffee90 | 9 | 590 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,747 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/1969775/PYTHON-SOL-oror-WELL-EXPLAINED-oror-INTUTION-EXPLAINED-oror-DICTIONARY-%2B-PREFIX-SUM-oror | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
d = defaultdict(lambda:0)
d[0] = 1
n = len(nums)
summ = 0
ans = 0
for i in range(n):
summ += nums[i]
ans += d[summ%k]
d[summ%k] += 1
return ans | subarray-sums-divisible-by-k | PYTHON SOL || WELL EXPLAINED || INTUTION EXPLAINED || DICTIONARY + PREFIX SUM || | reaper_27 | 6 | 604 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,748 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/1679181/Python-3-Prefix-sum-solution | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
count = collections.defaultdict(int)
count[0] = 1
sum_num = 0
ans = 0
for num in nums:
sum_num += num
if (sum_num % k) in count:
ans += count[sum_num % k]
count[sum_num % k] += 1
return ans | subarray-sums-divisible-by-k | Python 3 Prefix sum solution | AndrewHou | 3 | 512 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,749 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2779403/python-3-line-O(n)-I-have-no-idea-what-I-wrote-but-it-works... | class Solution:
# subarray [i, j] is divisible by k iff sum([0, j]) % k equals to
# sum([0, i]) % k. this gives me idea to use hashtable. I hash
# the remainders of sums at each index. Then we compare and count
# them. I'd never write code like this at work though, completely
# unreadable, 0 chance to pass the review...
def subarraysDivByK(self, nums: List[int], k: int) -> int:
sums = [0]
for n in nums: sums.append(sums[-1] + n)
return sum([v * (v - 1) // 2 for v in Counter([n % k for n in sums]).values()]) | subarray-sums-divisible-by-k | python 3 line O(n), I have no idea what I wrote but it works... | tinmanSimon | 2 | 486 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,750 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2688641/Python3-Solution-or-Prefix-Sum-or-O(N) | class Solution:
def subarraysDivByK(self, A, K):
csum, ans = 0, 0
D = [0] * K
D[0] = 1
for i in A:
csum = (csum + i) % K
ans += D[csum]
D[csum] += 1
return ans | subarray-sums-divisible-by-k | ✔ Python3 Solution | Prefix Sum | O(N) | satyam2001 | 2 | 1,200 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,751 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2185923/python-3-or-prefix-sum-or-O(n)O(k) | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
modCount = collections.Counter([0])
res = 0
prefix = 0
for num in nums:
prefix = (prefix + num) % k
res += modCount[prefix]
modCount[prefix] += 1
return res | subarray-sums-divisible-by-k | python 3 | prefix sum | O(n)/O(k) | dereky4 | 2 | 485 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,752 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2131998/Prefix-Sum-in-Python-with-working-explanation | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
count = [0] * k
s = 0
for x in nums:
s += x % k
count[s % k] += 1
result = count[0]
for c in count:
result += (c * (c - 1)) // 2
return result | subarray-sums-divisible-by-k | Prefix Sum in Python with working explanation | DanishKhanbx | 2 | 127 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,753 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2103243/Python3-using-Dictionary | class Solution:
def subarraysDivByK(self, arr: List[int], k: int) -> int:
dic = {0:1}
curr_sum = 0
subArrays = 0
for i in range(len(arr)):
curr_sum+=arr[i]
rem = curr_sum % k
if rem<0:
rem+=k
if rem in dic:
subArrays+=dic[rem]
dic[rem]+=1
else:
dic[rem]=1
return subArrays | subarray-sums-divisible-by-k | Python3 using Dictionary | abhiswc29 | 2 | 245 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,754 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/1432257/Simple-Python-Solution | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
pre=[0]
hs={0:1}
c=0
for i in range(len(nums)):
z=pre[-1]+nums[i]
c=c+hs.get(z%k,0)
hs[z%k]=hs.get(z%k,0)+1
pre.append(z)
return c | subarray-sums-divisible-by-k | Simple Python Solution | nmk0462 | 2 | 325 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,755 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/1835958/Python-easy-to-read-and-understand-or-prefix-sum | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
d = {0: 1}
sums, ans = 0, 0
for i in range(len(nums)):
sums += nums[i]
if sums%k in d:
ans += d[sums%k]
d[sums%k] = d.get(sums%k, 0) + 1
return ans | subarray-sums-divisible-by-k | Python easy to read and understand | prefix sum | sanial2001 | 1 | 425 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,756 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2846095/EASY-SOLUTION-oror-HASHMAP-oror-PREFIX-SUM-oror-PYTHON | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
d = defaultdict(lambda:0)
d[0] = 1
s = 0
ans = 0
for i in nums:
s+=i
if s<0 : s+=k
rem = s%k
d[rem]+=1
ans+=(d[rem]-1)
return ans | subarray-sums-divisible-by-k | EASY SOLUTION || HASHMAP || PREFIX SUM || PYTHON | cheems_ds_side | 0 | 3 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,757 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2778031/Python-or-O(n)-Prefix-Sum-%2B-Dictionary | class Solution:
def subarraysDivByK(self, xs: List[int], k: int) -> int:
classes = {0:1}
prefix_sum = 0
ans = 0
for x in xs:
prefix_sum = (prefix_sum + x) % k
classes[prefix_sum] = classes.get(prefix_sum, 0) + 1
for n in classes.values():
ans += n * (n-1) // 2
return ans | subarray-sums-divisible-by-k | Python | O(n) Prefix Sum + Dictionary | on_danse_encore_on_rit_encore | 0 | 18 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,758 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2747462/Prefix-Sum-Fast-and-Easy-O(N)-Solution | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
d = {0 : 1}
psum = 0
res = 0
for i in range(len(nums)):
psum += nums[i]
if psum % k in d:
res += d[psum % k]
d[psum % k] = d.get((psum % k) , 0) + 1
return (res) | subarray-sums-divisible-by-k | Prefix Sum - Fast and Easy O(N) Solution | user6770yv | 0 | 31 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,759 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2690754/Hashmap-solution-or-O(N)-TC-O(1)-SC | class Solution(object):
def subarraysDivByK(self, nums, k):
hashmap=dict()
hashmap[0]=1
pre=0
res=0
for i in nums:
pre+=i
if pre%k in hashmap:
res+=hashmap[pre%k]
hashmap[pre%k]+=1
else:
hashmap[pre%k]=1
return res | subarray-sums-divisible-by-k | Hashmap solution | O(N) TC O(1) SC | sundram_somnath | 0 | 21 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,760 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2664335/Python3-Solution-oror-O(N)-Time-and-Space-Complexity | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
prefixSum=0
count=0
dic={}
for i in range(len(nums)):
prefixSum+=nums[i]
rem=prefixSum%k
if rem not in dic:
dic[rem]=0
if rem==0:
count+=1
if rem in dic:
count+=dic[rem]
dic[rem]+=1
return count | subarray-sums-divisible-by-k | Python3 Solution || O(N) Time & Space Complexity | akshatkhanna37 | 0 | 25 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,761 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/2092212/Python-prefix-sum-easy-to-understand-O(n) | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
prefix_sum = []
dic = defaultdict(int)
dic[0] = 1
curr = 0
res = 0
for i in range(len(nums)):
curr += nums[i]
div = curr % k
res += dic[div]
dic[div] += 1
return res | subarray-sums-divisible-by-k | Python prefix sum easy to understand O(n) | Kennyyhhu | 0 | 154 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,762 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/982286/Python3-prefix-and-frequency-table | class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
freq = defaultdict(int, {0: 1})
ans = prefix = 0
for x in A:
prefix = (prefix + x) % K
ans += freq[prefix]
freq[prefix] += 1
return ans | subarray-sums-divisible-by-k | [Python3] prefix & frequency table | ye15 | 0 | 157 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,763 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/710842/Python3-prefix-sum-remainder-counter-Subarray-Sums-Divisible-by-K | class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
presum = [0]
for a in A:
presum.append(presum[-1] + a)
ans = 0
for v in Counter(p % K for p in presum).values():
ans += v * (v -1) // 2
return ans | subarray-sums-divisible-by-k | Python3 prefix sum remainder counter - Subarray Sums Divisible by K | r0bertz | 0 | 308 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,764 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/563142/Python3-Prefix-Sum | class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
prefix = defaultdict(int)
prefix[0] = 1
summary, current = 0, 0
for v in A:
current = (current + v % K + K) % K
summary += prefix[current]
prefix[current] += 1
return summary | subarray-sums-divisible-by-k | Python3 Prefix Sum | tjucoder | 0 | 154 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,765 |
https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/388799/Solution-in-Python-3-(beats-~95)-(six-lines)-(two-pass) | class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
D, s = {0:1}, 0
for a in A:
s = (s + a) % K
if s in D: D[s] += 1
else: D[s] = 1
return sum(i*(i-1)//2 for i in D.values())
- Junaid Mansuri
(LeetCode ID)@hotmail.com | subarray-sums-divisible-by-k | Solution in Python 3 (beats ~95%) (six lines) (two pass) | junaidmansuri | -1 | 595 | subarray sums divisible by k | 974 | 0.536 | Medium | 15,766 |
https://leetcode.com/problems/odd-even-jump/discuss/1293059/Python-O(nlogn)-bottom-up-DP-easy-to-understand-260ms | class Solution:
def oddEvenJumps(self, A: List[int]) -> int:
# find next index of current index that is the least larger/smaller
def getNextIndex(sortedIdx):
stack = []
result = [None] * len(sortedIdx)
for i in sortedIdx:
while stack and i > stack[-1]:
result[stack.pop()] = i
stack.append(i)
return result
sortedIdx = sorted(range(len(A)), key= lambda x: A[x])
oddIndexes = getNextIndex(sortedIdx)
sortedIdx.sort(key=lambda x: -A[x])
evenIndexes = getNextIndex(sortedIdx)
# [odd, even], the 0th jump is even
dp = [[0,1] for _ in range(len(A))]
for i in range(len(A)):
if oddIndexes[i] is not None:
dp[oddIndexes[i]][0] += dp[i][1]
if evenIndexes[i] is not None:
dp[evenIndexes[i]][1] += dp[i][0]
return dp[-1][0] + dp[-1][1] | odd-even-jump | Python O(nlogn) bottom-up DP easy to understand 260ms | ScoutBoi | 9 | 966 | odd even jump | 975 | 0.389 | Hard | 15,767 |
https://leetcode.com/problems/odd-even-jump/discuss/1369141/Python3-dp | class Solution:
def oddEvenJumps(self, arr: List[int]) -> int:
large = [-1] * len(arr)
small = [-1] * len(arr)
stack = []
for i, x in sorted(enumerate(arr), key=lambda x: (x[1], x[0])):
while stack and stack[-1] < i: large[stack.pop()] = i
stack.append(i)
stack = []
for i, x in sorted(enumerate(arr), key=lambda x: (-x[1], x[0])):
while stack and stack[-1] < i: small[stack.pop()] = i
stack.append(i)
odd = [0] * len(arr)
even = [0] * len(arr)
odd[-1] = even[-1] = 1
for i in reversed(range(len(arr))):
if 0 <= large[i]: odd[i] = even[large[i]]
if 0 <= small[i]: even[i] = odd[small[i]]
return sum(odd) | odd-even-jump | [Python3] dp | ye15 | 4 | 325 | odd even jump | 975 | 0.389 | Hard | 15,768 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/915905/Python-3-98-better-explained-with-simple-logic | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
A.sort(reverse = True)
for i in range(3,len(A)+1):
if(A[i-3] < A[i-2] + A[i-1]):
return sum(A[i-3:i])
return 0 | largest-perimeter-triangle | Python 3, 98% better, explained with simple logic | apurva_101 | 14 | 2,300 | largest perimeter triangle | 976 | 0.544 | Easy | 15,769 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/550885/PythonJavaJSGoC%2B%2B-O(-n-log-n-)-by-sorting.-w-Visualization | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
# sort side length in descending order
A.sort( reverse = True )
# Try and test from largest side length
for i in range( len(A) - 2):
if A[i] < A[i+1] + A[i+2]:
# Early return when we find largest perimeter triangle
return A[i] + A[i+1] + A[i+2]
# Reject: impossible to make triangle
return 0 | largest-perimeter-triangle | Python/Java/JS/Go/C++ O( n log n ) by sorting. [w/ Visualization] | brianchiang_tw | 9 | 628 | largest perimeter triangle | 976 | 0.544 | Easy | 15,770 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692877/Python-Solution-with-explanation. | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
i = n-1
j = n-3
while(j>=0):
if(nums[j]+nums[j+1]>nums[i]):
return nums[j]+nums[j+1]+nums[i]
i=i-1
j=j-1
return 0 | largest-perimeter-triangle | Python Solution with explanation. | yashkumarjha | 5 | 505 | largest perimeter triangle | 976 | 0.544 | Easy | 15,771 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/390818/Two-Solutions-in-Python-3-(beats-~95) | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
L, _ = len(A), A.sort()
for i in range(L-1,1,-1):
if A[i] < A[i-1] + A[i-2]: return sum(A[i-2:i+1])
return 0 | largest-perimeter-triangle | Two Solutions in Python 3 (beats ~95%) | junaidmansuri | 4 | 929 | largest perimeter triangle | 976 | 0.544 | Easy | 15,772 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/390818/Two-Solutions-in-Python-3-(beats-~95) | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
L, _ = len(A), A.sort()
for i in range(L-1,1,-1):
a = A[i]
for j in range(i-1,0,-1):
b, m, c = A[j], a - A[j] + 1, A[j-1]
if m > b: break
if c >= m: return a + b + c
return 0
- Junaid Mansuri
(LeetCode ID)@hotmail.com | largest-perimeter-triangle | Two Solutions in Python 3 (beats ~95%) | junaidmansuri | 4 | 929 | largest perimeter triangle | 976 | 0.544 | Easy | 15,773 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2220814/Python3-simple-naive-approach | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
A.sort(reverse=True)
for i in range(len(A) - 2):
if A[i] < A[i+1] + A[i+2]:
return A[i] + A[i+1] + A[i+2]
return 0 | largest-perimeter-triangle | 📌 Python3 simple naive approach | Dark_wolf_jss | 3 | 119 | largest perimeter triangle | 976 | 0.544 | Easy | 15,774 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2136139/Python-Easy-and-Simple-Solution | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
#sum of two side should always be greater than third side
nums.sort()
nums.reverse()
for i in range(len(nums)-2):
base,side1,side2 = nums[i],nums[i+1],nums[i+2]
if side1+side2>base:
return side1+side2+base
return 0 | largest-perimeter-triangle | Python Easy and Simple Solution | pruthashouche | 3 | 264 | largest perimeter triangle | 976 | 0.544 | Easy | 15,775 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2000126/Python-Clean-and-Simple! | class Solution:
def largestPerimeter(self, nums):
nums.sort(reverse=True)
for i in range(len(nums)-2):
base, side1, side2 = nums[i], nums[i+1], nums[i+2]
if side1 + side2 > base:
return base + side1 + side2
return 0 | largest-perimeter-triangle | Python - Clean and Simple! | domthedeveloper | 3 | 260 | largest perimeter triangle | 976 | 0.544 | Easy | 15,776 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2695058/Python-Simple | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort(reverse=1)
for i in range(len(nums)-2):
if nums[i] < nums[i+1] + nums[i+2]:
return sum(nums[i:i+3])
return 0 | largest-perimeter-triangle | Python - Simple | lokeshsenthilkumar | 1 | 17 | largest perimeter triangle | 976 | 0.544 | Easy | 15,777 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2693372/93.3-in-runtime-and-91.6-in-space-for-begginers | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
#sort the array iin decreasing order
#TRIANGLE RULE
#sum of two arre greater than third side
nums.sort(reverse=True)
for i in range(3,len(nums)+1):
if nums[i-3]<nums[i-2]+nums[i-1]:
return sum(nums[i-3:i])
return 0 | largest-perimeter-triangle | 93.3 % in runtime and 91.6 in space for begginers | V_Bhavani_Prasad | 1 | 27 | largest perimeter triangle | 976 | 0.544 | Easy | 15,778 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2172763/Python-Simple-Python-Solution-Using-Sorting | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums = sorted(nums)
i = len(nums)-3
while i>-1:
if nums[i]+nums[i+1] > nums[i+2]:
return nums[i]+nums[i+1]+nums[i+2]
i = i - 1
return 0 | largest-perimeter-triangle | [ Python ] ✅✅ Simple Python Solution Using Sorting 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 1 | 183 | largest perimeter triangle | 976 | 0.544 | Easy | 15,779 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2131532/Python3-Solution-with-Clear-Explanation | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort(reverse=True)
for i in range(0, len(nums)-2):
if nums[i]<(nums[i+1]+nums[i+2]):
return nums[i]+nums[i+1]+nums[i+2]
return 0 | largest-perimeter-triangle | Python3 - Solution with Clear Explanation | Akashraj-srinivasan | 1 | 151 | largest perimeter triangle | 976 | 0.544 | Easy | 15,780 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2814366/Python-solution-beats-99.84-solution's-time-complexity | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums=sorted(nums)
l=len(nums)-1
while l>=2:
if nums[l]<nums[l-1]+nums[l-2]:
return nums[l]+nums[l-1]+nums[l-2]
l-=1
return 0 | largest-perimeter-triangle | Python solution beats 99.84 solution's time complexity | thunder34 | 0 | 6 | largest perimeter triangle | 976 | 0.544 | Easy | 15,781 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2794498/Beats-97.33-solution | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums = sorted(nums, reverse = True)
for i in range(0,len(nums)-2):
window = nums[i:i+3]
if (window[0] < window[1] + window[2]) and 0 not in window: return sum(window)
return 0 | largest-perimeter-triangle | Beats 97.33% solution | ishitakumardps | 0 | 5 | largest perimeter triangle | 976 | 0.544 | Easy | 15,782 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2759179/Simple-Python3-Solution | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort(reverse=True)
for i in range(0, len(nums)-2):
if (nums[i] + nums[i+1] > nums[i+2] ) and (nums[i+1] + nums[i+2] > nums[i] ) and (nums[i] + nums[i+2] > nums[i+1] ):
return nums[i] + nums[i+1]+ nums[i+2]
return 0 | largest-perimeter-triangle | Simple Python3 Solution | vivekrajyaguru | 0 | 4 | largest perimeter triangle | 976 | 0.544 | Easy | 15,783 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2710396/python-easy-solution-with-reversed-sort | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums = sorted(nums, reverse = True)
i = 0
while i <= len(nums)-3:
if nums[i] < nums[i+1] + nums[i+2]:
return nums[i] + nums[i+1] + nums[i+2]
i += 1
return 0 | largest-perimeter-triangle | python easy solution with reversed sort | shangyueqi | 0 | 7 | largest perimeter triangle | 976 | 0.544 | Easy | 15,784 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2695789/Python3-Solution-O(n) | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
# rule of triangles length of sizes
nums = sorted(nums, reverse=True)
print(nums)
i = 0
while i < len(nums) - 2:
if nums[i] + nums[i+1] > nums[i+2] and nums[i] + nums[i+2] > nums[i+1] and nums[i+1] + nums[i+2] > nums[i]:
return sum(nums[i:i+3])
i += 1
return 0 | largest-perimeter-triangle | Python3 Solution - O(n) | sipi09 | 0 | 8 | largest perimeter triangle | 976 | 0.544 | Easy | 15,785 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2695707/Python-clean-code-or-Sorting-looping-sol. | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
# Sort the array first in case to find out the largest peri.
nums.sort()
for i in range(len(nums)-1, -1, -1):
if i > 1 and (nums[i-1]+nums[i-2]) > nums[i]:
return nums[i]+nums[i-1]+nums[i-2]
return 0 | largest-perimeter-triangle | Python clean code | Sorting / looping sol. | Aamina | 0 | 8 | largest perimeter triangle | 976 | 0.544 | Easy | 15,786 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2695677/Python-oror-O(N-Log-N)-oror-With-Explanation-and-time-complexity | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort(reverse=True)
for i in range(len(nums)-2):
if nums[i]<nums[i+1]+nums[i+2]:
return nums[i]+nums[i+1]+nums[i+2]
return 0 | largest-perimeter-triangle | Python || O(N Log N) || With Explanation and time complexity | _sagargoel_ | 0 | 4 | largest perimeter triangle | 976 | 0.544 | Easy | 15,787 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694918/Python3-For-loop-after-sort | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort(reverse=True)
for idx in range(len(nums) - 2):
sub_sum = nums[idx + 1] + nums[idx + 2]
if nums[idx] < sub_sum:
return nums[idx] + sub_sum
return 0 | largest-perimeter-triangle | Python3 For loop after sort | lambrosopos | 0 | 6 | largest perimeter triangle | 976 | 0.544 | Easy | 15,788 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694872/Python3-Greedy | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort()
while len(nums) >= 3:
a, b, c = nums[-3:]
if a + b > c:
return a+b+c
nums.pop()
return 0 | largest-perimeter-triangle | [Python3] Greedy | ruosengao | 0 | 5 | largest perimeter triangle | 976 | 0.544 | Easy | 15,789 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694818/Python3!-As-short-as-it-gets!-Timegreater96. | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums = sorted(nums)
for i in range(len(nums)-3, -1, -1):
if nums[i+2] < nums[i] + nums[i+1]:
return nums[i] + nums[i+1] + nums[i+2]
return 0 | largest-perimeter-triangle | 😎Python3! As short as it gets! Time>96%. | aminjun | 0 | 9 | largest perimeter triangle | 976 | 0.544 | Easy | 15,790 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694697/PYTHON-EASIEST-solution | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
A.sort(reverse = True)
for i in range(len(A) - 2):
if A[i + 1] + A[i + 2] > A[i]:
return A[i] + A[i + 1] + A[i + 2]
return 0 | largest-perimeter-triangle | PYTHON EASIEST solution | Abhishekh21 | 0 | 4 | largest perimeter triangle | 976 | 0.544 | Easy | 15,791 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694506/Python-easy-solution | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort()
i = len(nums)-1
while i>=2:
if nums[i-1]+nums[i-2]>nums[i]:
if nums[i-1]-nums[i-2]<nums[i]:
return nums[i-1]+nums[i-2]+nums[i]
i-=1
return 0 | largest-perimeter-triangle | Python easy solution | kanchan63637 | 0 | 3 | largest perimeter triangle | 976 | 0.544 | Easy | 15,792 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694420/py3 | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
A.sort()
for i in range(len(A)-3,-1,-1):
if(A[i] + A[i+1] > A[i+2]):
return A[i] + A[i+1] + A[i+2]
return 0 | largest-perimeter-triangle | py3 | user8296YR | 0 | 3 | largest perimeter triangle | 976 | 0.544 | Easy | 15,793 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694299/Python3-solution | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
# Sort the array
A.sort()
# start with 3 less than len(A), keep going until you get to just before -1, by steps of -1.
for i in range(len(A)-3,-1,-1):
# Sum of 2 sides of a triangle is > than the 3rd side
if(A[i] + A[i+1] > A[i+2]):
# largest perimeter
return A[i] + A[i+1] + A[i+2]
# If it is impossible to form any triangle of non-zero area, return 0
return 0 | largest-perimeter-triangle | Python3 solution | rupamkarmakarcr7 | 0 | 2 | largest perimeter triangle | 976 | 0.544 | Easy | 15,794 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694232/python-Faster-than-97.4-O(n)-time-complexity | class Solution(object):
def largestPerimeter(self,nums):
"""
:type nums: List[int]
:rtype: int
"""
i=len(nums)-1
nums.sort()
if len(nums)<3:
return 0
while (i>=2):
if nums[i-2]+nums[i-1]>nums[i]:
return nums[i-2]+nums[i-1]+nums[i]
i-=1
return 0 | largest-perimeter-triangle | [python] Faster than 97.4% , O(n) time complexity | paras1915 | 0 | 14 | largest perimeter triangle | 976 | 0.544 | Easy | 15,795 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694101/Python-Solution | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
if len(nums) <3:
return 0
nums.sort()
i=len(nums)-1
while i>=2:
if nums[i-2] + nums[i-1] > nums[i]:
return nums[i-2]+nums[i-1]+nums[i]
i-=1
return 0 | largest-perimeter-triangle | Python Solution | Sheeza | 0 | 3 | largest perimeter triangle | 976 | 0.544 | Easy | 15,796 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2694088/Python-oror-O(nlogn)-oror-Short-Crisp-and-Simple-to-Understand-oror-Top-92-Time | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
sides = sorted(nums, reverse=True)
for i in range(len(sides)-2):
if sides[i] < sides[i+1] + sides[i+2]:
return sides[i] + sides[i+1] + sides[i+2]
return 0 | largest-perimeter-triangle | Python || O(nlogn) || Short, Crisp and Simple to Understand || Top 92% Time | Aayush65 | 0 | 5 | largest perimeter triangle | 976 | 0.544 | Easy | 15,797 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2693943/Easy-Python-Solution | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort(reverse=True)
for i in range(len(nums)-2):
if nums[i]+nums[i+1]>nums[i+2] and nums[i]+nums[i+2]>nums[i+1] and nums[i+1]+nums[i+2]>nums[i]:
return nums[i]+nums[i+1]+nums[i+2]
return 0 | largest-perimeter-triangle | Easy Python Solution | souravrrp | 0 | 2 | largest perimeter triangle | 976 | 0.544 | Easy | 15,798 |
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2693787/Python-(Faster-than-93)-O(N)-Greedy-solution-with-explaination-or-Sliding-window | class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort(reverse=True)
perimeter = 0
for i in range(len(nums) - 2):
if (nums[i + 1] + nums[i + 2]) > nums[i]:
return nums[i + 1] + nums[i + 2] + nums[i]
return 0 | largest-perimeter-triangle | Python (Faster than 93%) O(N) Greedy solution with explaination | Sliding window | KevinJM17 | 0 | 5 | largest perimeter triangle | 976 | 0.544 | Easy | 15,799 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.