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 if start > len(s): return left = start right = start + 1 while right <= len(s): currWord = s[left:right] if isPalindrome(currWord): comb.append(currWord) backtrack(s,right,comb) comb.pop() right += 1 backtrack(s,0,[]) return res
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]): self.helper(ret, curr + [s[:i + 1]], s[i + 1:]) def isPalin(self, s): for i in range(len(s) // 2): if s[i] != s[len(s) - 1 - i]: return False return True
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 # Recursion with backTacking def search(i): # Store the current partioning if the string is exhausted if i == n: output.append(part.copy()) else: # Look for all the indexes starting from i for j in range(i, n): # Check if the string is plaindrome # betweem index i and j, if yes, # add it to current partition if isPalindrome(i, j): part.append(s[i:j+1]) # add search(j+1) # seach partitions starting next index part.pop() # backtack search(0) # search planindrome starting 0th index return output
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 += 1 j -= 1 return True graph = collections.defaultdict(list) for i in range(1, l+1): for j in range(0, i): if dp[j] and isPalindrome(s[j:i]): dp[i] = True graph[i].append(j) def dfs(pos): ans = [] for p in graph[pos]: tmp = s[p:pos] ans += [x + '-' + tmp for x in dfs(p)] if p > 0 else [tmp] return ans return [x.split('-') for x in dfs(l)]
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) i, j = i-1, j+1 #dp @lru_cache(None) def fn(i): """Return palindrome partitioning of s[i:]""" if i == len(s): return [[]] return [[s[i:ii+1]] + y for ii in palin[i] for y in fn(ii+1)] return fn(0)
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 += 1 ri -= 1 return True cache = {} def helper(string): if string in cache: return cache[string] res = [] for i in range(len(string)): if isPalindrome(string[:i+1]): if i == len(string)-1: res.append([string[:i+1]]) else: subs = helper(string[i+1:]) for sub in subs: res.append([string[:i+1]] + sub) cache[string] = res return res res = helper(s) return res
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 = [] def dfs(pos, slate): if pos == len(s): res.append(slate[:]) return for index in range(pos, len(s)): if is_palindrome(s, pos, index): dfs(index+1, slate+[ s[pos:index+1]]) dfs(0, []) return 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])): dfs(s[k:],temp+[s[:k]],res) def ispal(s): if(s==s[::-1]): return(True) else: return(False) res=[] dfs(s,[],res) return(res)
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,len(s)+1): if (ispal(s[:k])==True): sol(s[k:],temp+[s[:k]],res) sol(s,[],res) return res
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.helper(ans, curr + [s[:i + 1]], s[i + 1:]) def isPalindrome(self, s): for i in range(len(s) // 2): if s[i] != s[len(s) - 1 - i]: return False return True
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.append(s[i:j+1]) dfs(j+1) part.pop() dfs(0) return res
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 None for j in range(i+1,n+1): if ispal(s[i:j]): back(j, l+[''.join(s[i:j]) ]) back(0,[]) return res
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*16+e] = "".join(sl[s:e+1]) def rec(p, gr): nonlocal n nonlocal r assert 0<=p<=n if p == n: c = [] for i in gr: c.append(valid[i]) r.append(c) return s = p for e in range(s, n): if s*16+e in valid: gr2 = gr.copy() gr2.append(s*16+e) rec(e+1, gr2) rec(0, []) return r
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.append(l.copy()) return for k in range(i,n): if palindrome(s,i,k): f(k+1,n,l+[s[i:k+1]],ans) ans=[] n=len(s) f(0,n,[],ans) return ans
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: return True return False def backtracking(start, curlist, length): if length == len(s): result.append(list(curlist)) return for end in range(start+1,len(s)+1): if palindrome(start,end): curlist.append(s[start:end]) backtracking(end, curlist, length+len(s[start:end]) curlist.pop() result = [] backtracking(0, [], 0) return result
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]): self.part(s[i:], path + [s[:i]], res) def isPalindrome(self, s): return s == s[::-1]
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 + 1] == s[i:k + 1][::-1]: temp.append(s[i:k +1]) traverse(k + 1, j, temp, ans) temp.pop() ans = [] temp = [] traverse(0, n, temp, ans) del temp return ans
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 r -= 1 return True def func(st,ans): if st == len(s): ans_list.append(ans) return else: for i in range(st+1,len(s)+1): if is_peli(s[st:i]): func(i,ans+[s[st:i]]) func(0,[]) return ans_list
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 i in range(index, n): # if selected string is palindrome, add to list and proceed further if s[index:i+1] == s[index:i+1][::-1]: dfs(i+1, temp + [s[index:i+1]]) dfs(0, []) return res
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]: ans.extend([[st] + j for j in recurse(i+1)]) return ans return recurse(0)
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 == temp[::-1]: dfs(s[i + 1:], path + [temp], ans) dfs(s, [], ans) return ans
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, j): part.append(s[pos:j+1]) dfs(j + 1) part.pop() def isPalindrome(s, i, j): while i < j: if s[i] != s[j]: return False i += 1 j -= 1 return True dfs(0) return res
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 for i in range(start_index,len(s)): if palindrome(s[start_index:i+1]): backtrack(i+1,path + [s[start_index:i+1]]) backtrack(0,[]) return res
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 = [] stack = [(s, [])] while stack: string, cand = stack.pop() if string == '': res.append(cand) m = len(string) for i in range(m): if panlin(string, 0, i): stack.append((string[i+1:], cand + [string[:i+1]])) return 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(len(s)): t = s[-a - 1:] memo[t] = [] for b in palindromes_from_start_symbol(t): if len(b) == a + 1: memo[t].append([b]) else: for way in memo[t[len(b):]]: memo[t].append([b] + way) return memo[s]
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]) dfs(s, i+1, path) path.pop() ans = list() dfs(s, 0, []) return ans def isPallindrome(self, s, start, end): if s[start:end+1] == s[start:end+1][::-1]: return True else: return False
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 =[] dfs(s,[],ans) #print(ans) return 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), range(stop_idx - 1, middle - 1, -1)): if s[head] != s[tail]: return False return True for start_idx in range(len(s)): for stop_idx in range(start_idx+1, len(s)+1): if is_palindrome(s, start_idx, stop_idx): palindromes[start_idx].append(s[start_idx:stop_idx]) def build_partitions(partitions: list, curr_idx: int, stop_idx: int, palindromes: dict, result: list) -> None: if curr_idx == stop_idx: result.append(partitions[:]) return for palindrome in palindromes[curr_idx]: partitions.append(palindrome) build_partitions(partitions, curr_idx + len(palindrome), stop_idx, palindromes, result) partitions.pop() result = [] build_partitions([], 0, len(s), palindromes, result) return result
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,len(s)+1):#every possible slicing position if s[:i]==s[i-1::-1]:#if palindrome. list slicing: [start:end:reverse], will first execute the reverse then consider start and end path.append(s[:i]) dfs(s[i:],path,res) path.pop() dfs(s,[],res) return res
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:], cur_path+[cur_s[:i]]) self.ret = [] dfs(s, []) return self.ret
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 backtrack(start): if start == len(s): ret.append(current[:]) return for i in range(start, len(s)): if isP(start, i): current.append(s[start:i + 1]) backtrack(i + 1) current.pop() backtrack(0) return ret
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(string,length,j,part + [string[i:j]]) def partition(self, s: str) -> List[List[str]]: self.result = [] self.dfs(s,len(s),0,[]) return self.result
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 i in range(len(s)): sub_part(i,i) sub_part(i-1,i) # generate output res=[] def dfs(i, tmp): if i >=len(s): res.append(tmp) else: for p in part[i]: dfs(i + len(p), tmp + [p]) dfs(0, []) return res
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-1, j+1 #dp @lru_cache(None) def fn(i): """Return minimum palindrome partitioning of s[i:]""" if i == len(s): return 0 return min(1 + fn(ii+1) for ii in palin[i]) return fn(0)-1
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+1]) i, j = i-1, j+1 return ans[0]-1
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 &amp; 1) while 0 <= l and r < N and S[l] == S[r]: dp[r + 1] = min(dp[r + 1], dp[l] + 1) l -= 1 r += 1 return dp[-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) else: break j += 1 # even palindromes for i in range(n): j = 0 while i + j < n and i - j - 1 >= 0: if s[i + j] == s[i - j - 1]: p_start[i + j].append(i - j - 1) else: break j += 1 min_counts = [math.inf for _ in range(n)] for i in range(n): for j in p_start[i]: min_counts[i] = min( min_counts[i], 1 + (min_counts[j - 1] if j > 0 else 0) ) return min_counts[n - 1] - 1
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 partition in i-1th count of partition # take the ith index as mid of palindrome for both even and odd length of palindrome # and test if this makes a palindrome if indexes j and k travel both sides. capture the # minimum length comes in the process. for j,k in [[i,i+1],[i-1,i+1]]: while j>=0 and k<n and s[j]==s[k]: mp[k] = min(mp[j-1]+1,mp[k]) j-=1 k+=1 return mp[k-1]
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,len(s)): if s[ind:i+1]==s[ind:i+1][::-1]: best=min(best,1+self.helper(s,i+1)) self.dp[ind]=best return best
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 i + k < lg and s[i - k] == s[i + k]: k += 1 d1.append(k) k -= 1 if i + k > r: r = i + k l = i - k l, r = 0, -1 for i, c in enumerate(s): if i > r: k = 0 else: k = min(d2[l + r - i + 1], r - i + 1) while i - k - 1 >= 0 and i + k < lg and s[i - k - 1] == s[i + k]: k += 1 d2.append(k) k -= 1 if i + k > r: r = i + k l = i - k - 1 # "aaaab" # d1 = [1, 2, 2, 1, 1] # d2 = [0, 1, 2, 1, 0] # print(d1, d2) d = defaultdict(list) for i, dm in enumerate(d1): for j in range(dm, 0, -1): d[i + j - 1].append(i - j + 1) for i, dm in enumerate(d2): for j in range(dm, 0, -1): d[i + j - 1].append(i - j) dp = [float('inf')] * (len(s) + 1) dp[0] = 0 for i in range(len(s)): for j in d[i]: dp[i + 1] = min(dp[i + 1], dp[j] + 1) return dp[-1] - 1
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) return dp[len(s)] def minCut1(self, s: str) -> int: if len(s)<=1: return 0 self.memo=[None]*(len(s)+1) self.memo[0]=[[]] ps = self.partition(s) min_len=float("inf") for p in ps: min_len=min(min_len,len(p)) return min_len - 1 def partition(self,s): l = len(s) if self.memo[l]: return self.memo[l] result=[] for i in range(l-1,-1,-1): current=s[i:] if current==current[::-1]: prevs=self.partition(s[:i]) for prev in prevs: result+=[prev+[current]] self.memo[l]=result return result
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: if ngbr.val not in clones: clones[ngbr.val] = Node(ngbr.val, []) q.append(ngbr) cur_clone.neighbors.append(clones[ngbr.val]) return clones[node.val]
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) return node_copy def dfs(self, node): for neighbor in node.neighbors: if neighbor not in self.visited: # add the neighbor node to visited dict neighbor_copy = Node(neighbor.val, []) self.visited[neighbor] = neighbor_copy self.visited[node].neighbors.append(neighbor_copy) self.dfs(neighbor) else: # use the neighbor node in the visited dict self.visited[node].neighbors.append(self.visited[neighbor])
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] while len(self.stack) > 0: node = self.stack.pop() for neighbor in node.neighbors: if neighbor not in self.visited: # add the neighbor node to visited dict neighbor_copy = Node(neighbor.val, []) self.visited[neighbor] = neighbor_copy self.visited[node].neighbors.append(neighbor_copy) self.stack.append(neighbor) else: # use the neighbor node in the visited dict self.visited[node].neighbors.append(self.visited[neighbor]) return node_copy
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] = Node(curNode.val) for nei in curNode.neighbors: if nei and nei not in curNewDict: curNewDict[nei] = Node(nei.val) traverse(nei) # only calling if nei is not in dictionary. Here we using the curNewDict to track visited nodes also! curNewDict[curNode].neighbors.append(curNewDict[nei]) traverse(node) # return copy of the starting node return curNewDict[node]
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.val) for nei in curNode.neighbors: if nei and nei not in curNewDict: curNewDict[nei] = Node(nei.val) q.append(nei) curNewDict[curNode].neighbors.append(curNewDict[nei]) # return copy of the starting node return curNewDict[node]
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) for neigh in cur.neighbors: n.neighbors.append(clone(neigh)) return m[cur.val] m = {} return m[node.val] if clone(node) else None
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] mp = {} return node and dfs(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: memo[nn] = Node(nn.val) stack.append(nn) memo[n].neighbors.append(memo[nn]) return node and memo[node]
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() for realNeigh in real.neighbors: if realNeigh in nodeToClone: # get reference of a existing cloned node from dictionary and append to list of neighbors clone.neighbors.append(nodeToClone[realNeigh]) else: # create a clone of the real neighbor and add it to list of neighbors as well as the dictionary clonedNeigh = Node(realNeigh.val) clone.neighbors.append(clonedNeigh) nodeToClone[realNeigh] = clonedNeigh q.append((realNeigh, clonedNeigh)) return head
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.append(DFS(neighbor)) return copy_node return DFS(node)
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] = newNode if node.neighbors: newNode.neighbors = [self.cloneGraph(n) for n in node.neighbors] return newNode
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 in visited: c_n = dfs(neighbor) clone_node.neighbors.append(c_n) else: c_n = visited[neighbor.val] clone_node.neighbors.append(c_n) return clone_node return dfs(node)
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.val not in vis: copy.neighbors.append(self.dfs(v, vis)) else: copy.neighbors.append(vis[v.val]) return copy
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: copy.neighbors.append(dfs(nei)) return copy return dfs(node) if node else None
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.val not in created: created[n.val] = Node(n.val) queue.append(n) new.neighbors.append(created[n.val]) return created[1]
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 None
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.val, []) self.m[N.val] = N for neighbor in node.neighbors: N.neighbors.append(self.clone(N, neighbor)) return N def clone(self, parent, node): if node.val in self.m: return self.m[node.val] N = Node(node.val, [parent]) self.m[N.val] = N for neighbor in node.neighbors: if neighbor.val == parent.val: continue if neighbor.val in self.m: N.neighbors.append(self.m[neighbor.val]) else: N.neighbors.append(self.clone(N, neighbor)) return N
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 cur_node = nodes_to_visit.pop() copy_node = node_dict[cur_node.val] nodes_visited.add(cur_node.val) for neighbor in cur_node.neighbors: # adding nodes_to_visit if neighbor.val not in nodes_visited and neighbor.val not in node_dict: nodes_to_visit.append(neighbor) # creating new node if neighbor.val not in node_dict: node_dict[neighbor.val] = Node(val=neighbor.val, neighbors=[]) neighbor_node = node_dict[neighbor.val] # adding neighbors if neighbor.val not in nodes_visited: neighbor_node.neighbors.append(copy_node) copy_node.neighbors.append(neighbor_node) return node_dict[node.val]
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 hashmap we are storing new node value at the old node key for nei in node.neighbors: copy.neighbors.append(dfs(nei)) return copy return dfs(node) if node else None # if values exists in node then only call dfs else return []
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.neighbors: copy.neighbors.append(dfs(neighbor)) return copy return dfs(node) if node else None
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 neighbor.val not in dups: dups[neighbor.val] = Node(neighbor.val, []) q.append(neighbor) dups[current.val].neighbors.append(dups[neighbor.val]) return dups[node.val]
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.cloneGraph(n)) else: newNode.neighbors.append(self.visited[n]) return newNode
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 = Node() copy.val = cur.val visited[cur] = copy stack.extend(cur.neighbors) # assign neighbors for cur in visited: visited[cur].neighbors = [visited[nd] for nd in cur.neighbors] return visited[node]
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(dfs(nei)) return copy return None if node is None else dfs(node)
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 is the corresponding cloned node adj = {} #the adjacency list for the graph. In each k:v pair k is the val attribute #of a node and v is a list of the val attributes of its neighbors. stack = [node] #stack of nodes to be visited. Each time we visit a node, we will add #its neighbors in the stack. while stack != []: curr = stack.pop() #take a node out of the stack if curr.val not in visited: #if node was already visited we do nothing visited.append(curr.val) cloneNodes[curr.val] = Node(curr.val) #create new node with the same val and #no neighbors adj[curr.val] = [] for nd in curr.neighbors: stack.append(nd) #add neighbors in the stack adj[curr.val].append(nd.val) #save neighbors in adjacency dictionary for k, v in adj.items(): #update neighbors of cloned nodes to match the neighbors of old ones cloneNodes[k].neighbors = [cloneNodes[i] for i in v] return cloneNodes[node.val] #return clone of initial node
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 for nei in cur.neighbors: new_node.neighbors.append(helper(nei)) return new_node return helper(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.neighbors: if nde.val not in nodes: queue.append(nde) nodes[nde.val] = (Node(val = nde.val), [nd.val for nd in nde.neighbors]) for val in nodes: neighbors = [] for vl in nodes[val][1]: neighbors.append(nodes[vl][0]) nodes[val][0].neighbors = neighbors return nodes[1][0]
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 nde.val not in nodes: queue.append(nde) nodes[nde.val] = Node(val = nde.val) neighbors.append(nodes[nde.val]) nodes[curr.val].neighbors = neighbors return nodes[1]
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 dfs(node)
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() for neighbor in node.neighbors: if neighbor not in m: # to process this node later on # since we haven't processed this yet queue.append(neighbor) # create a mapping of this node # with a newly created node in m m[neighbor] = Node(neighbor.val) # add the current neighbor (the copy from the map) # to the neighbors of the parent node in the # current iteration m[node].neighbors.append(m[neighbor]) # return the root node return m[root]
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: graph.neighbors.append(dfs(neighbor, visited)) else: graph.neighbors.append(visited[neighbor.val]) return graph if node is None: return None return dfs(node)
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 dictionary return it if node in mapp: return mapp[node] # making a new node (clone) of the actual node if not in mapp and add it copy = Node(node.val) mapp[node] = copy # iterating through the actual node's neighbours list and appending their clone values to clone neighbours list for n in node.neighbors: copy.neighbors.append(dfs(n)) # return the entire new object created return copy # return the value that is finally returned cloned graph if initial node is present else return None return dfs(node) if node else None ``` Time Complexity - O(n) - n is the sum of number of nodes V and number of Edges E Space Coplexity - O(n)
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(n, i, self.processed[node.val]) return self.processed[node.val] def clone(self, node, index, prev): if node.val not in self.processed: prev.neighbors[index] = Node(node.val, node.neighbors[:]) self.processed[node.val] = prev.neighbors[index] for i, n in enumerate(prev.neighbors[index].neighbors): self.clone(n, i, prev.neighbors[index]) else: prev.neighbors[index] = self.processed[node.val]
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, dict)) return dict[node]
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] - cost[i] if gas_tank < 0: # the car has deficit of petrol start_index = i+1 # change the starting point gas_tank = 0 # make the current gas to 0, as we will be starting again from next station return start_index
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 &amp; cost idx, min_val, cur = 0, sys.maxsize, 0 # get cumulative sum and find the smallest, the place after the smallest idx will be where we start for i, v in enumerate(diff): cur += v if cur <= min_val: min_val, idx = cur, i # maintain smallest &amp; its index return (idx+1)%len(diff) if cur >= 0 else -1 # if total sum is less than 0, meaning no possible place to start
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 maxSumSubArray(self, arr): maxSum, currSum = 0, 0 maxStart, start = 0, 0 for i in range(len(arr)): currSum += arr[i] if currSum > maxSum: ### the maximum sum is obtained when we start from index start maxStart = start maxSum = currSum if currSum < 0: ### reset the starting index start = i+1 currSum = 0 return start
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: return idx + 1, 0 idx += 1 return n, cum def finalize(idx, rem): for i in range(idx): rem += diff[i] if rem < 0: return -1 return idx idx = 0 while idx < n: if diff[idx] >= 0: # It is possible to start from this index. # Check if we can complete the circuit nidx, rem = OK(idx) # this should either break or reach to end. if nidx == n: # we have completed the circuit, idx is the only possible ans. # Check is rem gas can complete the remaining trip. return finalize(idx, rem) # we should check for other possibility idx = nidx else: idx += 1 return -1
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) # SC: O(1)
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 + neg >= 0 else -1
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: start = i + 1 cur = 0 return start
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[i] - cost[i] if tank < 0: tank = 0 start = i+1 if start == n: return 0 else: return start
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 if Sum < minsum: start = (i+1) % n minsum=Sum return start
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[i] - cost[i] for i in range(len(gas))) < 0: #if the sum of the difference is less than 0, it means there is no position we can reach from start to end return -1 tank, start = 0, 0 for i in range(len(gas)): tank += gas[i] - cost[i] if tank < 0: #the start point will happend at next position tank = 0 start = i + 1 if start == len(gas): return 0 else: return start
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 wrong s=0 #store the difference for checking how much gas needed to travel index=0 #index from where circuit starts for i in range(len(gas)): s+= gas[i]-cost[i] #storing the difference if s<0: #if found negative that means we dont have the enough gas in our tank to travel s=0 #so reset to 0(initially tank value from start) index=i+1 #if the sum is nagative that means surely that index not to be #used so take next i to store in index return index #EXPLAINATION- #gas = [1,2,3,4,5], cost = [3,4,5,1,2] , difference=[-2,-2,-2,3,3] , here found positive #at index 3 and after that index no sum s gonna be negative in whole circuit(goes like #from index- 3->4->0->1->2) #as said in question "guaranteed to be unique" means #gas=[1,1,1], sum=3 #cost=[1,1,1], sum=3 #this type of arrays will never be given coz here solution cannot be unique (circuit can be start from any index)
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 first statin total_gas_remain = 0 tank_gas_remain = 0 start_idx = 0 for i in range(len(gas)): total_gas_remain += gas[i] - cost[i] tank_gas_remain += gas[i] - cost[i] if tank_gas_remain < 0: start_idx = i + 1 tank_gas_remain = 0 if total_gas_remain < 0: return -1 else: return start_idx
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 res = i+1 return res if total >= 0 else -1
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 couldn't get here, if curr_tank < 0: # Pick up the next station as the starting one. starting_station = i + 1 # Start with an empty tank. curr_tank = 0 return starting_station if total_tank >= 0 else -1
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[stop] this_cost = total_gas - cost[stop] if this_cost < 0: total_gas = 0 else: total_gas = this_cost return my_stop
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 = 0 for i, d in enumerate(diff): if curr_sub + d < 0: start = i + 1 curr_sub = max(curr_sub + d, 0) tmp = max_sub max_sub = max(curr_sub, max_sub) if curr_sub > tmp: res = start return 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] # Check if we can make it to gas Station if tank >= cost[i]: # We can reach next gas station (Ither sa pani bi pi lain ga) tank -= cost[i] jump += 1 else: # We cannot reach next gas station, so we restart the circle by empting tank and moving destination ahead tank = 0 dest += 1 + jump jump = 0 if i == dest: return i % size return -1
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): #so return - 1 return - 1 #if the gas is sufficient #we have to find from which index we should start total = 0 #res is a variable which is created to store the index from which we are going to start res = 0 #iterate of the indexes of gas for i in range(len(gas)): #add the difference of gas and cost at each station total += (gas[i] - cost[i]) #if the difference is less than 0 if total < 0: #then we have to check the positive difference #so reset total to 0 total = 0 #increse the res value to next index res = i + 1 #after finishing the for-loop #we the return the index where first positive difference is occured return res
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: start = i maximum = 0 # WE'VE REACHED A CIRCLE if i - start == n: return start maximum += (gas[i % n] - cost[i % n]) return - 1
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 curr = 0 c+=1 return index
gas-station
[Python3] || 85% Faster || Greedy || Easy to understand ||
code_Shinobi
0
52
gas station
134
0.451
Medium
1,699