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/palindrome-partitioning/discuss/1353771/Python3-backtracking-simple | class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
def isPalindrome(s):
return s == s[::-1]
def backtrack(s,start,comb):
if start == len(s):
res.append(list(comb))
return
... | palindrome-partitioning | Python3 backtracking simple | caw062 | 2 | 330 | palindrome partitioning | 131 | 0.626 | Medium | 1,600 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1233353/Python3-Short-Easy-Backtracking-Solution-(modularity!) | class Solution:
def partition(self, s: str) -> List[List[str]]:
ret = []
self.helper(ret, [], s)
return ret
def helper(self, ret, curr, s):
if s == "":
ret.append(curr)
for i in range(len(s)):
if self.isPalin(s[:i + 1]):
... | palindrome-partitioning | [Python3] Short Easy Backtracking Solution (modularity!) | LydLydLi | 2 | 281 | palindrome partitioning | 131 | 0.626 | Medium | 1,601 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1590727/Py3-Solution-using-backtracking-w-comments | class Solution:
def partition(self, s: str) -> List[List[str]]:
# Init
output = []
part = []
n = len(s)
# Helper function to check palindrome
def isPalindrome(low,high):
x = s[low:high+1]
r = x[::-1]
return x == r
... | palindrome-partitioning | [Py3] Solution using backtracking w/ comments | ssshukla26 | 1 | 132 | palindrome partitioning | 131 | 0.626 | Medium | 1,602 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1187119/python-dp-with-graph-same-as-Word-Break-2-exactly | class Solution:
def partition(self, s: str) -> List[List[str]]:
l = len(s)
dp = [False] * (l + 1)
dp[0] = True
def isPalindrome(s):
l = len(s)
i, j = 0, l - 1
while i <= j:
if s[i] != s[j]: return False
i +=... | palindrome-partitioning | python dp with graph, same as Word Break 2 exactly | dustlihy | 1 | 148 | palindrome partitioning | 131 | 0.626 | Medium | 1,603 |
https://leetcode.com/problems/palindrome-partitioning/discuss/713192/Python3-dp-with-pre-processing-(99.87) | class Solution:
def partition(self, s: str) -> List[List[str]]:
#pre-processing
palin = dict()
for k in range(len(s)):
for i, j in (k, k), (k, k+1):
while 0 <= i and j < len(s) and s[i] == s[j]:
palin.setdefault(i, []).append(j)
... | palindrome-partitioning | [Python3] dp with pre-processing (99.87%) | ye15 | 1 | 158 | palindrome partitioning | 131 | 0.626 | Medium | 1,604 |
https://leetcode.com/problems/palindrome-partitioning/discuss/537253/Python-3-memoization-beats-95 | class Solution:
def partition(self, s: str) -> List[List[str]]:
if len(s) == 0:
return []
def isPalindrome(string):
li, ri = 0, len(string) - 1
while li < ri:
if string[li] != string[ri]:
return False
li... | palindrome-partitioning | Python 3 memoization, beats 95% | kstanski | 1 | 487 | palindrome partitioning | 131 | 0.626 | Medium | 1,605 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2841482/Python-or-Recursion-or-DFS | class Solution:
def partition(self, s: str) -> List[List[str]]:
def is_palindrome(arr, start, end):
while start <= end:
if arr[start] != arr[end]:
return False
start += 1
end -= 1
return True
res ... | palindrome-partitioning | Python | Recursion | DFS | ajay_gc | 0 | 2 | palindrome partitioning | 131 | 0.626 | Medium | 1,606 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2813527/Palindrome-Partitioning | class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
def dfs(s,temp,res):
if not s:
res.append(temp)
return
for k in range(1,len(s)+1):
if(ispal(s[:k])):
... | palindrome-partitioning | Palindrome Partitioning | RajatGupta123 | 0 | 7 | palindrome partitioning | 131 | 0.626 | Medium | 1,607 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2813524/Palindrome-partitioning-in-python | class Solution:
def partition(self, s: str) -> List[List[str]]:
res=[]
def ispal(s):
if s==s[::-1]:
return True
else:
return False
def sol(s,temp,res):
if not s:
res.append(temp)
for k in range(1,... | palindrome-partitioning | Palindrome partitioning in python | ravishankarguptacktd | 0 | 1 | palindrome partitioning | 131 | 0.626 | Medium | 1,608 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2813122/python3-Easy-recursive-sol. | class Solution:
def partition(self, s: str) -> List[List[str]]:
ans=[]
self.helper(ans,[],s)
return ans
def helper(self, ans, curr, s):
if s == "":
ans.append(curr)
for i in range(len(s)):
if self.isPalindrome(s[:i + 1]):
self.hel... | palindrome-partitioning | python3 Easy recursive sol. | pranjalmishra334 | 0 | 2 | palindrome partitioning | 131 | 0.626 | Medium | 1,609 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2786052/python-fast-solution | class Solution:
def partition(self, s: str) -> List[List[str]]:
res=[]
part=[]
def dfs(i):
if i>=len(s):
res.append(part.copy())
return
for j in range(i,len(s)):
if s[i:j+1]==s[i:j+1][::-1]:
part.app... | palindrome-partitioning | python fast solution | gauravtiwari91 | 0 | 3 | palindrome partitioning | 131 | 0.626 | Medium | 1,610 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2786027/Python-oror-Clean-Backtracking | class Solution:
def partition(self, s: str) -> List[List[str]]:
n, s, res = len(s), list(s), []
def ispal(sub):
i,j = 0, len(sub)-1
while i <= j :
if sub[i] != sub[j]: return False
i += 1
j -= 1
return True
def back(i, l):
nonlocal res
if i >= n:
res.append(l.copy())
return ... | palindrome-partitioning | Python || Clean Backtracking | morpheusdurden | 0 | 6 | palindrome partitioning | 131 | 0.626 | Medium | 1,611 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2737846/Python3-Precomputed-Palindromes-Beats-88 | class Solution:
def partition(self, s: str) -> List[List[str]]:
r = []
sl = list(s)
valid = {}
n=len(s)
def is_pal(x):
return x == x[::-1]
for s in range(n):
for e in range(n):
if is_pal(sl[s:e+1]):
valid[s*... | palindrome-partitioning | Python3 Precomputed Palindromes Beats 88% | godshiva | 0 | 7 | palindrome partitioning | 131 | 0.626 | Medium | 1,612 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2737663/palindrome-partitioning-faster-then-96 | class Solution:
def partition(self, s: str) -> List[List[str]]:
def palindrome(s,i,j):
while i<j:
if s[i]!=s[j]:
return False
i+=1
j-=1
return True
def f(i,n,l,ans):
if i>=n:
ans.a... | palindrome-partitioning | palindrome partitioning faster then 96% | ravinuthalavamsikrishna | 0 | 6 | palindrome partitioning | 131 | 0.626 | Medium | 1,613 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2716102/Python-Backtracking | class Solution:
def partition(self, s: str) -> List[List[str]]:
def palindrome(left, right):
right -= 1
while left <= right:
if s[left] != s[right]:
break
left += 1
right -= 1
if left > right... | palindrome-partitioning | Python Backtracking | Bettita | 0 | 8 | palindrome partitioning | 131 | 0.626 | Medium | 1,614 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2646281/95-Faster-Python-Easy-Solution | class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
self.part(s, [], res)
return res
def part(self, s, path, res):
if not s:
res.append(path)
return
for i in range(1, len(s) + 1):
if self.isPalindrome(s[:i]):
... | palindrome-partitioning | 95% Faster Python Easy Solution | mdfaisalabdullah | 0 | 3 | palindrome partitioning | 131 | 0.626 | Medium | 1,615 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2492041/Python3-or-Recursive-or-Space-Optimized | class Solution:
def partition(self, s: str) -> List[List[str]]:
n = len(s)
if n == 1: return [[s]]
def traverse(i,j, temp, ans):
if i == n:
ans.append(temp.copy())
for k in range(i , j):
if s[i:k + ... | palindrome-partitioning | Python3 | Recursive | Space Optimized | Garvit-IDKHTC | 0 | 26 | palindrome partitioning | 131 | 0.626 | Medium | 1,616 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2443392/Python-optimized-solution-using-backtracking | class Solution:
def partition(self, s: str) -> List[List[str]]:
ans_list = []
def is_peli(str1):
l = 0
r = len(str1)-1
while l <= r:
if str1[l] != str1[r]:
return False
else:
l += 1
... | palindrome-partitioning | Python optimized solution using backtracking | AshishGohil | 0 | 26 | palindrome partitioning | 131 | 0.626 | Medium | 1,617 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2309091/Python-3-Backtracking-solution-with-recursive-visualisation-with-diagram | class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
n = len(s)
def dfs(index, temp):
if index > n:
return
if index == n:
res.append(temp)
return
for ... | palindrome-partitioning | [Python 3] Backtracking solution with recursive visualisation with diagram | Gp05 | 0 | 37 | palindrome partitioning | 131 | 0.626 | Medium | 1,618 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2104485/Pyhton3-Solution | class Solution:
def partition(self, s: str) -> List[List[str]]:
n = len(s)
@lru_cache(None)
def recurse(index):
if n == index: return [[]]
ans = []
for i in range(index,n):
st = s[index:i+1]
if st == st[::-1]:
... | palindrome-partitioning | Pyhton3 Solution | satyam2001 | 0 | 34 | palindrome partitioning | 131 | 0.626 | Medium | 1,619 |
https://leetcode.com/problems/palindrome-partitioning/discuss/2024747/Python-recursive-solution | class Solution:
def partition(self, s: str) -> List[List[str]]:
ans = []
orig = s
def dfs(s, path, ans):
if ''.join(path) == orig:
ans.append(path)
temp = ""
for i in range(len(s)):
temp += s[i]
if temp == te... | palindrome-partitioning | Python recursive solution | user6397p | 0 | 52 | palindrome partitioning | 131 | 0.626 | Medium | 1,620 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1908244/Python-Backtrack-oror-100-Fast-oror-Easy-to-Understand | class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
part = []
def dfs(pos):
if pos >= len(s):
res.append(part.copy())
return
for j in range(pos, len(s)):
if isPalindrome(s, pos... | palindrome-partitioning | Python - Backtrack || 100% Fast || Easy to Understand | dayaniravi123 | 0 | 117 | palindrome partitioning | 131 | 0.626 | Medium | 1,621 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1874129/Python-or-BackTracking-or-Recursive | class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
def palindrome(s):
return s == s[::-1]
def backtrack(start_index,path):
if start_index >= len(s):
res.append(path)
return
... | palindrome-partitioning | Python | BackTracking | Recursive | iamskd03 | 0 | 46 | palindrome partitioning | 131 | 0.626 | Medium | 1,622 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1863215/Python-easy-to-understand-backtracking-solution | class Solution:
def partition(self, s: str) -> List[List[str]]:
def panlin(x, i, j):
while i < j:
if x[i] != x[j]:
return False
i += 1
j -= 1
return True
n = len(s)
res = []... | palindrome-partitioning | Python easy-to-understand backtracking solution | byuns9334 | 0 | 105 | palindrome partitioning | 131 | 0.626 | Medium | 1,623 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1710316/low-memory(less-then-99)-no-recursion-very-clear-python-solution | class Solution:
def partition(self, s: str) -> List[List[str]]:
def palindromes_from_start_symbol(r):
res = []
for i in range(len(r)):
if r[:i+1] == r[:i+1][::-1]:
res.append(r[:i+1])
return res
memo = {}
for a in range... | palindrome-partitioning | low memory(less then 99%), no recursion, very clear python solution | futhfuec | 0 | 124 | palindrome partitioning | 131 | 0.626 | Medium | 1,624 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1706539/Straightforward-Solution-(like-official-version)-in-Python3 | class Solution:
def partition(self, s: str) -> List[List[str]]:
def dfs(s, start, path):
if start >= len(s):
ans.append(path.copy())
for i in range(start, len(s)):
if self.isPallindrome(s, start, i):
path.append(s[start: i+1])
... | palindrome-partitioning | Straightforward Solution (like official version) in Python3 | lucyyang | 0 | 27 | palindrome partitioning | 131 | 0.626 | Medium | 1,625 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1669004/Palindrome-Partitioning-Backtracking-DFS-PYTHON3-Easy-to-understand | class Solution:
def partition(self, s: str) -> List[List[str]]:
def dfs(a,b,ans):
if not a:
ans.append(b)
return
for i in range(1,len(a)+1):
if a[:i] == a[:i][::-1]:
dfs(a[i:], b+[a[:i]], ans)
ans =[]
... | palindrome-partitioning | Palindrome Partitioning Backtracking DFS PYTHON3 Easy to understand | user8744WJ | 0 | 52 | palindrome partitioning | 131 | 0.626 | Medium | 1,626 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1668596/Python3-runtime-faster-than-97.97-memory-less-than-100.00 | class Solution:
def partition(self, s: str) -> List[List[str]]:
palindromes = defaultdict(list)
def is_palindrome(s: str, start_idx: int, stop_idx: int) -> bool:
middle = (start_idx + stop_idx) // 2
for head, tail in zip(
range(start_idx, middle),
... | palindrome-partitioning | [Python3] runtime faster than 97.97%, memory less than 100.00% | geka32 | 0 | 69 | palindrome partitioning | 131 | 0.626 | Medium | 1,627 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1583422/python-dfs-quicker-90%2B | class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
def dfs(s,path,res):# s: what comes after. path:what previously experienced, res: where will we put
if not s: # ending argument
res.append(path[:])
return
for i in range(1... | palindrome-partitioning | python dfs quicker 90%+ | kevinskw | 0 | 102 | palindrome partitioning | 131 | 0.626 | Medium | 1,628 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1420306/Simple-Python-standard-dfs-beats-92 | class Solution:
def partition(self, s: str) -> List[List[str]]:
def dfs(cur_s, cur_path):
if not cur_s:
self.ret.append(cur_path)
return
for i in range(1, len(cur_s)+1):
if cur_s[:i] == cur_s[:i][::-1]:
dfs(cur_s[i:]... | palindrome-partitioning | Simple Python standard dfs beats 92% | Charlesl0129 | 0 | 296 | palindrome partitioning | 131 | 0.626 | Medium | 1,629 |
https://leetcode.com/problems/palindrome-partitioning/discuss/1292959/Staightforward-Python-Backtracking-code-determine-Palindrome-by-recursion-with-memorization | class Solution:
def partition(self, s: str) -> List[List[str]]:
@lru_cache(maxsize = None)
def isP(l, r):
if r <= l:
return True
if s[r] != s[l]:
return False
return isP(l + 1, r - 1)
ret, current = [], []
def backt... | palindrome-partitioning | Staightforward Python Backtracking code, determine Palindrome by recursion with memorization | wanghua_wharton | 0 | 146 | palindrome partitioning | 131 | 0.626 | Medium | 1,630 |
https://leetcode.com/problems/palindrome-partitioning/discuss/971962/dfs-Solution-in-Python3 | class Solution:
def palind(self,i,j,string):
return string[i:j] == string[i:j][::-1]
def dfs(self,string,length,i,part):
if i == length:
self.result.append(part)
for j in range(i+1,length+1):
if self.palind(i,j,string):
self.dfs(s... | palindrome-partitioning | dfs Solution in Python3 | swap2001 | 0 | 58 | palindrome partitioning | 131 | 0.626 | Medium | 1,631 |
https://leetcode.com/problems/palindrome-partitioning/discuss/893452/python3-soln-beats-99.52 | class Solution:
def partition(self, s: str) -> List[List[str]]:
part = [[] for _ in range(len(s))]
def sub_part(l, r):
if 0 <= l <= r < len(s) and s[l]==s[r]:
part[l].append(s[l:r+1])
sub_part(l-1, r+1)
# find all palindromes
for... | palindrome-partitioning | python3 soln beats 99.52% | amrmahmoud96 | 0 | 456 | palindrome partitioning | 131 | 0.626 | Medium | 1,632 |
https://leetcode.com/problems/palindrome-partitioning-ii/discuss/713271/Python3-dp-(top-down-and-bottom-up) | class Solution:
def minCut(self, s: str) -> int:
#pre-processing
palin = dict()
for k in range(len(s)):
for i, j in (k, k), (k, k+1):
while 0 <= i and j < len(s) and s[i] == s[j]:
palin.setdefault(i, []).append(j)
i, j = i-... | palindrome-partitioning-ii | [Python3] dp (top-down & bottom-up) | ye15 | 2 | 131 | palindrome partitioning ii | 132 | 0.337 | Hard | 1,633 |
https://leetcode.com/problems/palindrome-partitioning-ii/discuss/713271/Python3-dp-(top-down-and-bottom-up) | class Solution:
def minCut(self, s: str) -> int:
ans = [inf]*len(s) + [0] #min palindrome partition for s[i:]
for k in reversed(range(len(s))):
for i, j in (k, k), (k, k+1):
while 0 <= i and j < len(s) and s[i] == s[j]:
ans[i] = min(ans[i], 1 + ans[j... | palindrome-partitioning-ii | [Python3] dp (top-down & bottom-up) | ye15 | 2 | 131 | palindrome partitioning ii | 132 | 0.337 | Hard | 1,634 |
https://leetcode.com/problems/palindrome-partitioning-ii/discuss/2812683/Python3-Solution-or-DP-or-O(n2) | class Solution:
def minCut(self, S):
N = len(S)
dp = [-1] + [N] * N
for i in range(2 * N - 1):
l = i // 2
r = l + (i & 1)
while 0 <= l and r < N and S[l] == S[r]:
dp[r + 1] = min(dp[r + 1], dp[l] + 1)
l -= 1
... | palindrome-partitioning-ii | ✔ Python3 Solution | DP | O(n^2) | satyam2001 | 1 | 120 | palindrome partitioning ii | 132 | 0.337 | Hard | 1,635 |
https://leetcode.com/problems/palindrome-partitioning-ii/discuss/2529036/Python-oror-Faster-than-93-oror-DP | class Solution:
def minCut(self, s: str) -> int:
n = len(s)
p_start = [[] for _ in range(n)]
# odd palindromes
for i in range(n):
j = 0
while i + j < n and i - j >= 0:
if s[i + j] == s[i - j]:
p_start[i + j].append(i - j)
... | palindrome-partitioning-ii | Python || Faster than 93% ✅ || DP | wilspi | 1 | 138 | palindrome partitioning ii | 132 | 0.337 | Hard | 1,636 |
https://leetcode.com/problems/palindrome-partitioning-ii/discuss/1669092/Python-solution-faster-than-97 | class Solution:
def minCut(self, s: str) -> int:
n = len(s)
# mp denotes how many min cuts needed till ith index.
mp = {
i:i
for i in range(-1,n)
}
for i in range(n):
mp[i] = min(mp[i],1+mp[i-1]) # if not palindrome add one more... | palindrome-partitioning-ii | Python solution faster than 97 % | lalit96sh | 1 | 147 | palindrome partitioning ii | 132 | 0.337 | Hard | 1,637 |
https://leetcode.com/problems/palindrome-partitioning-ii/discuss/2147654/Python3-or-Recursive-DP | class Solution:
def minCut(self, s: str) -> int:
self.dp=[-1 for i in range(len(s))]
return self.helper(s,0)-1
def helper(self,s,ind):
if ind==len(s):
return 0
if self.dp[ind]!=-1:
return self.dp[ind]
best=float('inf')
for i in range(ind,le... | palindrome-partitioning-ii | [Python3] | Recursive DP | swapnilsingh421 | 0 | 23 | palindrome partitioning ii | 132 | 0.337 | Hard | 1,638 |
https://leetcode.com/problems/palindrome-partitioning-ii/discuss/1390609/Python-Manacher-%2B-DP-solution-beats-92 | class Solution:
def minCut(self, s: str) -> int:
lg = len(s)
d1 = []
d2 = []
d = {}
l, r = 0, -1
for i, c in enumerate(s):
if i > r:
k = 1
else:
k = min(d1[l + r - i], r - i + 1)
while i - k >= 0 and ... | palindrome-partitioning-ii | [Python] Manacher + DP solution beats 92% | kyttndr | 0 | 113 | palindrome partitioning ii | 132 | 0.337 | Hard | 1,639 |
https://leetcode.com/problems/palindrome-partitioning-ii/discuss/499380/Python3-two-different-methods | class Solution:
def minCut(self, s: str) -> int:
if len(s)<=1: return 0
dp = []
for x in range(-1,len(s)):
dp.append(x)
for i in range(len(s)):
for j in range(i,len(s)):
if s[i:j]==s[j:i:-1]:
dp[j+1]=min(dp[j+1],dp[i]+1)
... | palindrome-partitioning-ii | Python3 two different methods | jb07 | 0 | 191 | palindrome partitioning ii | 132 | 0.337 | Hard | 1,640 |
https://leetcode.com/problems/clone-graph/discuss/1792858/Python3-ITERATIVE-BFS-(beats-98)-'less()greater''-Explained | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node: return node
q, clones = deque([node]), {node.val: Node(node.val, [])}
while q:
cur = q.popleft()
cur_clone = clones[cur.val]
for ngbr in cur.neighbors:
... | clone-graph | ✔️ [Python3] ITERATIVE BFS (beats 98%) ,、’`<(❛ヮ❛✿)>,、’`’`,、, Explained | artod | 181 | 15,100 | clone graph | 133 | 0.509 | Medium | 1,641 |
https://leetcode.com/problems/clone-graph/discuss/374863/Python-up-to-date-BFSDFS-Solutions | class Solution(object):
def cloneGraph(self, node):
"""
:type node: Node
:rtype: Node
"""
if node == None:
return None
self.visited = dict()
node_copy = Node(node.val, [])
self.visited[node] = node_copy
self.dfs(node)
... | clone-graph | Python up-to-date BFS/DFS Solutions | yanshengjia | 8 | 1,000 | clone graph | 133 | 0.509 | Medium | 1,642 |
https://leetcode.com/problems/clone-graph/discuss/374863/Python-up-to-date-BFSDFS-Solutions | class Solution(object):
def cloneGraph(self, node):
"""
:type node: Node
:rtype: Node
"""
if node == None:
return None
self.visited = dict()
node_copy = Node(node.val, [])
self.visited[node] = node_copy
self.stack = [node]
... | clone-graph | Python up-to-date BFS/DFS Solutions | yanshengjia | 8 | 1,000 | clone graph | 133 | 0.509 | Medium | 1,643 |
https://leetcode.com/problems/clone-graph/discuss/2159884/Python-2-Optimal-Solutions-DFS-BFS | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node: return None
curNewDict = {} # key = curNode; value = copy of curNode
def traverse(curNode):
if not curNode: return
if curNode not in curNewDict:
curNewDict[curNode] =... | clone-graph | [Python] 2 Optimal Solutions DFS, BFS | samirpaul1 | 3 | 208 | clone graph | 133 | 0.509 | Medium | 1,644 |
https://leetcode.com/problems/clone-graph/discuss/2159884/Python-2-Optimal-Solutions-DFS-BFS | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node: return None
curNewDict = {} # key = curNode; value = copy of curNode
q = [node]
while q:
curNode = q.pop()
if curNode not in curNewDict: curNewDict[curNode] = Node(curNode.va... | clone-graph | [Python] 2 Optimal Solutions DFS, BFS | samirpaul1 | 3 | 208 | clone graph | 133 | 0.509 | Medium | 1,645 |
https://leetcode.com/problems/clone-graph/discuss/916525/Python-understandable-dfs-beats-95-speed-and-100-memory | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
def clone(cur):
if not cur:
return False
if cur.val in m:
return m[cur.val]
else:
n = m[cur.val] = Node(cur.val)
... | clone-graph | Python understandable dfs beats 95% speed and 100% memory | modusV | 3 | 114 | clone graph | 133 | 0.509 | Medium | 1,646 |
https://leetcode.com/problems/clone-graph/discuss/706507/Python3-recursive-and-iterative-dfs | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
def dfs(node):
"""Return deep-cloned graph."""
if node not in mp:
cln = mp[node] = Node(node.val)
cln.neighbors = [dfs(nn) for nn in node.neighbors]
return mp[node]
... | clone-graph | [Python3] recursive & iterative dfs | ye15 | 3 | 125 | clone graph | 133 | 0.509 | Medium | 1,647 |
https://leetcode.com/problems/clone-graph/discuss/706507/Python3-recursive-and-iterative-dfs | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if node:
memo = {node: Node(node.val)} #original -> clone mapping
stack = [node]
while stack:
n = stack.pop()
for nn in n.neighbors:
if nn not in memo:
... | clone-graph | [Python3] recursive & iterative dfs | ye15 | 3 | 125 | clone graph | 133 | 0.509 | Medium | 1,648 |
https://leetcode.com/problems/clone-graph/discuss/1808344/Python-Iterative-BFS | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
head = Node(node.val)
q = deque([(node, head)])
nodeToClone = { node : head }
while q:
real, clone = q.popleft()
... | clone-graph | Python Iterative BFS | Rush_P | 1 | 102 | clone graph | 133 | 0.509 | Medium | 1,649 |
https://leetcode.com/problems/clone-graph/discuss/1793192/Python-Simple-and-Easy-Python-Solution-Using-DFS-and-HashMap-or-Dictionary | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if node == None:
return None
GraphClone = {}
def DFS(node):
if node in GraphClone:
return GraphClone[node]
copy_node = Node(node.val)
GraphClone[node] = copy_node
for neighbor in node.neighbors:
copy_node.neighbors.app... | clone-graph | [ Python ] ✔✔ Simple and Easy Python Solution Using DFS and HashMap or Dictionary🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 1 | 67 | clone graph | 133 | 0.509 | Medium | 1,650 |
https://leetcode.com/problems/clone-graph/discuss/1735224/Python-DFS | class Solution:
def __init__(self):
self.cloned = {}
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return node
if node.val in self.cloned:
return self.cloned[node.val]
newNode = Node(node.val)
self.cloned[node.val] = newN... | clone-graph | Python, DFS | blue_sky5 | 1 | 110 | clone graph | 133 | 0.509 | Medium | 1,651 |
https://leetcode.com/problems/clone-graph/discuss/2837743/python-bfs-dfs-solutions | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
visited = {}
def dfs(node):
clone_node = Node(node.val)
visited[node.val] = clone_node
for neighbor in node.neighbors:
if neighbor.val not i... | clone-graph | python bfs dfs solutions | ron970404 | 0 | 2 | clone graph | 133 | 0.509 | Medium | 1,652 |
https://leetcode.com/problems/clone-graph/discuss/2749761/Python-Easy-DFS | class Solution(object):
def cloneGraph(self, node):
if node is None: return None
vis = dict()
return self.dfs(node, vis)
def dfs(self, u, vis):
copy = Node(u.val)
vis[u.val] = copy
for v in u.neighbors:
if v... | clone-graph | Python - Easy DFS | lokeshsenthilkumar | 0 | 11 | clone graph | 133 | 0.509 | Medium | 1,653 |
https://leetcode.com/problems/clone-graph/discuss/2737392/Clone-with-DFS | class Solution:
def cloneGraph(self, node):
oldToNew = {}
def dfs(node):
if node in oldToNew:
return oldToNew[node] # return the new copy
copy = Node(node.val)
oldToNew[node] = copy
for nei in node.neighbors:
... | clone-graph | Clone with DFS | meechos | 0 | 3 | clone graph | 133 | 0.509 | Medium | 1,654 |
https://leetcode.com/problems/clone-graph/discuss/2731083/Python3-or-BFS-or-Beats-98-TC-77-SC | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
created = {1: Node(node.val)}
queue = [node]
while queue:
node = queue.pop(0)
new = created[node.val]
for n in node.neighbors:
if n.... | clone-graph | Python3 | BFS | Beats 98% TC 77% SC | ChristianK | 0 | 7 | clone graph | 133 | 0.509 | Medium | 1,655 |
https://leetcode.com/problems/clone-graph/discuss/2501414/Recursive-Python-Solution-or-DFS-or-using-Hashmap | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
oldToNew = {}
def dfs(node):
if node in oldToNew:
return oldToNew[node]
copy = Node(node.val)
oldToNew[node] = copy
for neigh in node.neighbors:
copy.neighbors.append(dfs(neigh))
return copy
return dfs(node) if node else Non... | clone-graph | Recursive Python Solution | DFS | using Hashmap | nikhitamore | 0 | 19 | clone graph | 133 | 0.509 | Medium | 1,656 |
https://leetcode.com/problems/clone-graph/discuss/2349218/Python3-Recursion-HashMap-Checking | class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors or []
class Solution:
def __init__(self):
self.m = {}
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return node
N = Node(node.... | clone-graph | Python3 Recursion HashMap Checking | ophious | 0 | 31 | clone graph | 133 | 0.509 | Medium | 1,657 |
https://leetcode.com/problems/clone-graph/discuss/2308014/DFS-Python-Solution-Easy-to-Understand-(Beats-90) | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return node
node_dict = {node.val: Node(val=node.val, neighbors=[])}
nodes_to_visit = [node]
nodes_visited = set()
while nodes_to_visit:
# Finding the copy node of current node... | clone-graph | DFS Python Solution, Easy to Understand (Beats 90%) | mangopie152 | 0 | 78 | clone graph | 133 | 0.509 | Medium | 1,658 |
https://leetcode.com/problems/clone-graph/discuss/2299079/Python-DFS-Beats-97-with-full-working-explanation | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node': # Time: O(V + E) and Space: O(V)
oldToNew = {}
def dfs(node):
if node in oldToNew:
return oldToNew[node]
copy = Node(node.val) # copying the value/key
oldToNew[node] = copy # in the... | clone-graph | Python [DFS / Beats 97%] with full working explanation | DanishKhanbx | 0 | 53 | clone graph | 133 | 0.509 | Medium | 1,659 |
https://leetcode.com/problems/clone-graph/discuss/2226469/Python3-One-liner-ACCEPTED | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
oldToNew = {}
def dfs(node):
if node in oldToNew:
return oldToNew[node]
copy = Node(node.val)
oldToNew[node] = copy
for neighbor in node.ne... | clone-graph | ✅Python3 - One liner [ACCEPTED] | thesauravs | 0 | 24 | clone graph | 133 | 0.509 | Medium | 1,660 |
https://leetcode.com/problems/clone-graph/discuss/2226469/Python3-One-liner-ACCEPTED | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node: return node
q = deque([node])
dups = {node.val: Node(node.val, [])}
while q:
current = q.popleft()
for neighbor in current.neighbors:
if n... | clone-graph | ✅Python3 - One liner [ACCEPTED] | thesauravs | 0 | 24 | clone graph | 133 | 0.509 | Medium | 1,661 |
https://leetcode.com/problems/clone-graph/discuss/2226469/Python3-One-liner-ACCEPTED | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
return copy.deepcopy(node) | clone-graph | ✅Python3 - One liner [ACCEPTED] | thesauravs | 0 | 24 | clone graph | 133 | 0.509 | Medium | 1,662 |
https://leetcode.com/problems/clone-graph/discuss/2072568/Python-solution-90-beats | class Solution(object):
visited = {}
def cloneGraph(self, node):
if node is None:
return None
newNode = Node(node.val, [])
self.visited[node] = newNode
for n in node.neighbors:
if n not in self.visited:
newNode.neighbors.append(self.cloneGr... | clone-graph | Python solution 90% beats | Freeman1s1 | 0 | 50 | clone graph | 133 | 0.509 | Medium | 1,663 |
https://leetcode.com/problems/clone-graph/discuss/1820348/Python-Iterative-DFS-%2B-HashMap | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
# create copy nodes
stack = [node]
visited = {}
while stack:
cur = stack.pop()
if cur in visited:
continue
copy = No... | clone-graph | [Python] Iterative DFS + HashMap | haydarevren | 0 | 42 | clone graph | 133 | 0.509 | Medium | 1,664 |
https://leetcode.com/problems/clone-graph/discuss/1794490/Simple-Python3-Code | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
oldToNew={}
def dfs(node):
if node in oldToNew:
return oldToNew[node]
copy=Node(node.val)
oldToNew[node]=copy
for nei in node.neighbors:
copy.neighbors.append... | clone-graph | Simple Python3 Code | user6774u | 0 | 37 | clone graph | 133 | 0.509 | Medium | 1,665 |
https://leetcode.com/problems/clone-graph/discuss/1794234/Python3-Depth-first-search-with-explanation-in-the-code | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if node is None: return None #if we have an empty graph
visited = [] #will store all visited nodes
cloneNodes = {} #will store cloned nodes. In each k:v pair k is the val attribute of
#the old node and v i... | clone-graph | [Python3] Depth first search with explanation in the code | mhadjiantonis | 0 | 18 | clone graph | 133 | 0.509 | Medium | 1,666 |
https://leetcode.com/problems/clone-graph/discuss/1793743/Python3-Recursion-%2B-DFS-solution-or-36ms | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return
new_map = {}
def helper(cur):
if cur.val in new_map:
return new_map[cur.val]
new_node = Node(cur.val, [])
new_map[cur.val] = new_node
... | clone-graph | [Python3] Recursion + DFS solution | 36ms | nandhakiran366 | 0 | 15 | clone graph | 133 | 0.509 | Medium | 1,667 |
https://leetcode.com/problems/clone-graph/discuss/1793661/Python3-or-Memory-question%3A-99.28-vs-66.44 | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if node == None:
return None
nodes = {1: (Node(val = 1), [nde.val for nde in node.neighbors])}
queue = [node]
while queue:
curr = queue.pop()
for nde in curr.n... | clone-graph | Python3 | Memory question: 99.28% vs 66.44% | sr_vrd | 0 | 18 | clone graph | 133 | 0.509 | Medium | 1,668 |
https://leetcode.com/problems/clone-graph/discuss/1793661/Python3-or-Memory-question%3A-99.28-vs-66.44 | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if node == None:
return None
nodes = {1: Node(val = 1)}
queue = [node]
while queue:
curr = queue.pop()
neighbors = []
for nde in curr.neighbors:
if... | clone-graph | Python3 | Memory question: 99.28% vs 66.44% | sr_vrd | 0 | 18 | clone graph | 133 | 0.509 | Medium | 1,669 |
https://leetcode.com/problems/clone-graph/discuss/1734670/Python-ll-Simple-DFS | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
visited = {}
def dfs(node):
if node in visited:
return visited[node]
cop = Node(node.val, [])
visited[node] = cop
for nodes in node.neighbors:
cop.neighbors.append(dfs(nodes))
return cop
return... | clone-graph | Python ll Simple DFS | morpheusdurden | 0 | 66 | clone graph | 133 | 0.509 | Medium | 1,670 |
https://leetcode.com/problems/clone-graph/discuss/1658514/Python-Simple-iterative-BFS-explained | class Solution:
def cloneGraph(self, root: 'Node') -> 'Node':
if not root: return None
queue = deque([root])
m = {root: Node(root.val)}
while queue:
# get the first node out of
# the queue to process
node = queue.popleft()
... | clone-graph | [Python] Simple iterative BFS explained | buccatini | 0 | 174 | clone graph | 133 | 0.509 | Medium | 1,671 |
https://leetcode.com/problems/clone-graph/discuss/1514997/Python3-DFS-Solution | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
def dfs(node: 'Node', visited: dict = {}) -> 'Node':
graph = Node(node.val)
visited[node.val] = graph
for neighbor in node.neighbors:
if neighbor.val not in visited:
... | clone-graph | Python3 DFS Solution | user3694B | 0 | 165 | clone graph | 133 | 0.509 | Medium | 1,672 |
https://leetcode.com/problems/clone-graph/discuss/1273529/Simple-Python-DFS-Approach-O(n)-Solution | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
#dictionary to store old node value to new node value
mapp = {}
# function to recursive clone and map old node value to new
def dfs(node):
# if node already mapped and is present in dictio... | clone-graph | Simple - Python DFS Approach - O(n) Solution | nagashekar | 0 | 263 | clone graph | 133 | 0.509 | Medium | 1,673 |
https://leetcode.com/problems/clone-graph/discuss/535868/Python3-simple-solution | class Solution:
def __init__(self):
self.processed = {}
def cloneGraph(self, node: 'Node') -> 'Node':
if node is None:
return None
self.processed[node.val] = Node(node.val, node.neighbors[:])
for i, n in enumerate(self.processed[node.val].neighbors):
self... | clone-graph | Python3 simple solution | tjucoder | 0 | 84 | clone graph | 133 | 0.509 | Medium | 1,674 |
https://leetcode.com/problems/clone-graph/discuss/281159/Python3-DFS-Recursive | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
return clone(node, {})
def clone(node, dict):
if node not in dict:
dict[node] = Node(node.val, [])
for n in node.neighbors:
dict[node].neighbors.append(clone(n... | clone-graph | Python3 DFS Recursive | nzelei | 0 | 126 | clone graph | 133 | 0.509 | Medium | 1,675 |
https://leetcode.com/problems/gas-station/discuss/1276287/Simple-one-pass-python-solution | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
# base case
if sum(gas) - sum(cost) < 0:
return -1
gas_tank = 0 # gas available in car till now
start_index = 0 # Consider first gas station as starting point
for i in range(len(gas)):
gas_tank += gas[i] - cos... | gas-station | Simple one pass python solution | nandanabhishek | 9 | 796 | gas station | 134 | 0.451 | Medium | 1,676 |
https://leetcode.com/problems/gas-station/discuss/860310/Python-3-or-Clean-Greedy-O(N)-or-Explanation | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
diff = [g-c for g, c in zip(gas, cost)] # get difference between gas & cost
idx, min_val, cur = 0, sys.maxsize, 0 # get cumulative sum and find the smallest, the place after the smallest idx will ... | gas-station | Python 3 | Clean, Greedy O(N) | Explanation | idontknoooo | 5 | 292 | gas station | 134 | 0.451 | Medium | 1,677 |
https://leetcode.com/problems/gas-station/discuss/2773564/Python-12-line-sol.-faster-then-93.90 | class Solution(object):
def canCompleteCircuit(self, gas, cost):
if sum(gas)<sum(cost):
return -1
s=0
curr=0
for i in range(len(gas)):
curr+=gas[i]-cost[i]
if curr<0:
s=i+1
curr=0
return s | gas-station | Python 12 line sol. faster then 93.90% | pranjalmishra334 | 1 | 143 | gas station | 134 | 0.451 | Medium | 1,678 |
https://leetcode.com/problems/gas-station/discuss/1744076/Python-intuitive-explanation-O(n)-Break-down-to-maximum-sum-subarray-problem | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
if sum(gas) < sum(cost):
return -1
### find start of the maximum sum subarray
diff = [gas[i]-cost[i] for i in range(n)]
return self.maxSumSubArray(diff)
def max... | gas-station | Python intuitive explanation O(n) - Break down to maximum sum subarray problem | shubhamr022 | 1 | 193 | gas station | 134 | 0.451 | Medium | 1,679 |
https://leetcode.com/problems/gas-station/discuss/1707151/Python-Easy-and-Clean-Approach | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) < sum(cost):
return -1
fuel, strt_point = 0, 0
for i in range(len(gas)):
fuel += gas[i]-cost[i]
if fuel < 0:
strt_point = i+1
fuel = 0
return strt_point | gas-station | [Python] Easy and Clean Approach ✔ | leet_satyam | 1 | 59 | gas station | 134 | 0.451 | Medium | 1,680 |
https://leetcode.com/problems/gas-station/discuss/1706936/Python-3-or-O(N)-or-Inline-comments | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
diff = [gas[i] - cost[i] for i in range(n)]
def OK(idx):
cum = 0
while idx < n:
cum += diff[idx]
if cum < 0:
... | gas-station | [Python 3] | O(N) | Inline comments | BrijGwala | 1 | 33 | gas station | 134 | 0.451 | Medium | 1,681 |
https://leetcode.com/problems/gas-station/discuss/860589/Python-O(N)-oror-Intuitive | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(cost) > sum(gas): return -1
index = tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0: index, tank = i+1, 0
return index
# TC: O(N)
... | gas-station | Python O(N) || Intuitive | airksh | 1 | 49 | gas station | 134 | 0.451 | Medium | 1,682 |
https://leetcode.com/problems/gas-station/discuss/705747/Python3-prefix-sum | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
ans = prefix = 0
lowest = inf
for n, (g, c) in enumerate(zip(gas, cost), 1):
prefix += g-c
if prefix < lowest: ans, lowest = n, prefix
return ans%n if prefix >= 0 else -1 | gas-station | [Python3] prefix sum | ye15 | 1 | 160 | gas station | 134 | 0.451 | Medium | 1,683 |
https://leetcode.com/problems/gas-station/discuss/705747/Python3-prefix-sum | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
prefix = list(accumulate(g-c for g, c in zip(gas, cost)))
return (prefix.index(min(prefix))+1)%len(prefix) if prefix[-1] >= 0 else -1 | gas-station | [Python3] prefix sum | ye15 | 1 | 160 | gas station | 134 | 0.451 | Medium | 1,684 |
https://leetcode.com/problems/gas-station/discuss/705747/Python3-prefix-sum | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
ans = pos = neg = 0
for i, (g, c) in enumerate(zip(gas, cost)):
if pos < 0:
neg += pos
pos, ans = 0, i
pos += g - c
return ans%len(gas) if pos + n... | gas-station | [Python3] prefix sum | ye15 | 1 | 160 | gas station | 134 | 0.451 | Medium | 1,685 |
https://leetcode.com/problems/gas-station/discuss/2841452/Python-solution | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
cur = 0
start = 0
n = len(gas)
if sum(cost) > sum(gas):
return -1
for i in range(n):
cur += gas[i] - cost[i]
if cur < 0:
... | gas-station | Python solution | maomao1010 | 0 | 2 | gas station | 134 | 0.451 | Medium | 1,686 |
https://leetcode.com/problems/gas-station/discuss/2820025/Pythonor-Greedy | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
sum = 0
for i in range(n):
sum += gas[i] - cost[i]
if sum < 0:
return -1
tank = 0
start = 0
for i in range(n):
tank ... | gas-station | Python| Greedy | lucy_sea | 0 | 3 | gas station | 134 | 0.451 | Medium | 1,687 |
https://leetcode.com/problems/gas-station/discuss/2817732/Easy-Python-Solution | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
Sum = 0
n = len(gas)
start = -1
minsum = float('inf')
if sum(gas) < sum(cost):
return -1
for i in range(n):
temp = gas[i] - cost[i]
Sum += temp
... | gas-station | Easy Python Solution | Rui_Liu_Rachel | 0 | 4 | gas station | 134 | 0.451 | Medium | 1,688 |
https://leetcode.com/problems/gas-station/discuss/2815216/Greedy | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""
empty tank: 0,
goal: find the starting gas station's index if you cn travel aroun dthe circuit once in the clckwise dirsction.
clockwise direction: 3 4 5 0 1 2 3
"""
if sum(gas... | gas-station | Greedy | lillllllllly | 0 | 2 | gas station | 134 | 0.451 | Medium | 1,689 |
https://leetcode.com/problems/gas-station/discuss/2811761/Python-Solution-EXPLAINED-LINE-BY-LINE | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas)<sum(cost): #we should check that gas should be more so that the
#we can spend the gas(cost) to travel
return -1
#there is always a solution if above condition gets wr... | gas-station | Python Solution - EXPLAINED LINE BY LINE✔ | T1n1_B0x1 | 0 | 9 | gas station | 134 | 0.451 | Medium | 1,690 |
https://leetcode.com/problems/gas-station/discuss/2768148/Daily-LeetCode-Practice-Day-18 | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
# thoughts:
# go through each station and calculate the result
# O(n^2)
# to save time, the calc of first station can be used
# when we start from second station and circle back to ... | gas-station | Daily LeetCode Practice, Day 18 | yluo3421 | 0 | 2 | gas station | 134 | 0.451 | Medium | 1,691 |
https://leetcode.com/problems/gas-station/discuss/2736449/Python3-Simple-Greedy-Solution-O(n) | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
total = 0
cur = 0
res = 0
for i in range(len(gas)):
diff = gas[i] - cost[i]
total += diff
cur += diff
if cur < 0:
cur = 0
... | gas-station | Python3 Simple Greedy Solution O(n) | jonathanbrophy47 | 0 | 9 | gas station | 134 | 0.451 | Medium | 1,692 |
https://leetcode.com/problems/gas-station/discuss/2731496/greedy | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
total_tank, curr_tank = 0, 0
starting_station = 0
for i in range(n):
total_tank += gas[i] - cost[i]
curr_tank += gas[i] - cost[i]
# If one c... | gas-station | greedy | yhu415 | 0 | 5 | gas station | 134 | 0.451 | Medium | 1,693 |
https://leetcode.com/problems/gas-station/discuss/2674072/Python-Math | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(cost) > sum(gas):
return -1
total_gas = 0
this_cost = 0
for stop in range(len(gas)):
if total_gas == 0:
my_stop = stop
total_gas... | gas-station | Python Math | ascender | 0 | 4 | gas station | 134 | 0.451 | Medium | 1,694 |
https://leetcode.com/problems/gas-station/discuss/2666494/Python-3-one-pass-straightforward-intuition | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(cost) > sum(gas):
return -1
diff = [gas[i] - cost[i] for i in range(len(gas))] * 2
# looking for max sum subarray
curr_sub = max_sub = 0
start = 0
res = ... | gas-station | Python 3, one pass, straightforward intuition | user2595I | 0 | 5 | gas station | 134 | 0.451 | Medium | 1,695 |
https://leetcode.com/problems/gas-station/discuss/2641128/Solution-using-sliding-window-technique | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
size = len(cost)
gas = gas * 2
cost = cost * 2
tank = 0
dest = size
jump = 0
for i in range(size*2):
# Fill the tank Initially
tank += gas[i]
... | gas-station | Solution using sliding window technique | user0399P | 0 | 6 | gas station | 134 | 0.451 | Medium | 1,696 |
https://leetcode.com/problems/gas-station/discuss/2639050/Simple-python-code-with-explanation | class Solution:
#greedy algorithm
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
#if the gas at all stations is less than the cost at all stations then gas will not be sufficient to travel the circuit once
if sum(gas) < sum(cost):
... | gas-station | Simple python code with explanation | thomanani | 0 | 23 | gas station | 134 | 0.451 | Medium | 1,697 |
https://leetcode.com/problems/gas-station/discuss/1912277/Python-or-Maximum-Subarray-or-Kadane's-Algorithm-or-TImeSpace%3A-O(N)-O(1) | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
maximum = -1
start = 0
# WE WILL CYCLE THROUGH THE LIST BY USING MODULO
for i in range(n * 2):
# RESET IF GAS IS NEGATIVE
if maximum < 0:
s... | gas-station | [Python] | Maximum Subarray | Kadane's Algorithm | TIme/Space: O(N) / O(1) | spherical-cow | 0 | 68 | gas station | 134 | 0.451 | Medium | 1,698 |
https://leetcode.com/problems/gas-station/discuss/1707815/Python3-oror-85-Faster-oror-Greedy-oror-Easy-to-understand-oror | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) < sum(cost):
return -1
curr,index = 0,0
c = 0
for gs,cst in zip(gas,cost):
curr+= gs-cst
if curr < 0:
index = c+1
... | gas-station | [Python3] || 85% Faster || Greedy || Easy to understand || | code_Shinobi | 0 | 52 | gas station | 134 | 0.451 | Medium | 1,699 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.