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/word-break/discuss/2661869/Python-DP-bottom-up-%2B-Trie-data-structure | class TrieNode():
def __init__(self, val=None):
self.val = val
self.children = {idx: None for idx in range(26)}
self.eow = False
def Trie_add(word, Trieroot):
node = Trieroot
for ch in word:
ascii = ord(ch) - ord('a')
if not node.children[ascii]:
nod... | word-break | Python DP bottom-up + Trie data structure | ascender | 0 | 4 | word break | 139 | 0.455 | Medium | 1,900 |
https://leetcode.com/problems/word-break/discuss/2645443/EASY-EXPLANATION-WITH-MEMOIZATION-AND-DYNAMIC-PROGRAMMING | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
# Break words into pieces
# Empty word can be found in the dictionary
# can the whole s be also represented in the dictionary?
# BUILDING THE INTUITION HERE
"""
1. can I generate all su... | word-break | EASY EXPLANATION WITH MEMOIZATION AND DYNAMIC PROGRAMMING | leomensah | 0 | 85 | word break | 139 | 0.455 | Medium | 1,901 |
https://leetcode.com/problems/word-break/discuss/2588657/Python-Solution-using-DP | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp = [False] * (len(s) + 1)
dp[len(s)] = True
for i in range(len(s) - 1, -1, -1):
for w in wordDict:
if (i + len(w)) <= len(s) and s[i: i + len(w)] == w:
dp[i] = dp[i + len(w)]
if dp[i] == True:
break
return dp[0] | word-break | Python Solution using DP | nikhitamore | 0 | 57 | word break | 139 | 0.455 | Medium | 1,902 |
https://leetcode.com/problems/word-break/discuss/2548136/Python-or-Recursion-with-Inbuilt-Cache-Beats-99 | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n=len(wordDict)
ss=set(wordDict)
m=len(s)
@cache
def rec(i):
if i==m:
return True
if i>m:
return False
for j in ... | word-break | Python | Recursion with Inbuilt Cache - Beats 99% | Prithiviraj1927 | 0 | 111 | word break | 139 | 0.455 | Medium | 1,903 |
https://leetcode.com/problems/word-break/discuss/2426085/Word-Beak-oror-Python3-oror-DP | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dict = set()
for word in wordDict:
dict.add(word)
dp = [False] * (len(s)+1)
dp[0] = True
for i in range(1, len(dp)):
for j in range(0, i):
if(dp... | word-break | Word Beak || Python3 || DP | vanshika_2507 | 0 | 41 | word break | 139 | 0.455 | Medium | 1,904 |
https://leetcode.com/problems/word-break/discuss/2400773/Highly-memory-efficient-and-short-python-solution-beats-100. | class Solution(object):
def wordBreak(self, s, wordDict):
l=len(s)
dp=[False]*(l+1)
dp[0]=True
for i in range(l):
if dp[i]==True:
for j in wordDict:
if s[i:i+len(j)]==j and i+len(j)<=l:
dp[i+len(j)]=True
... | word-break | Highly memory efficient and short python solution beats 100%. | babashankarsn | 0 | 65 | word break | 139 | 0.455 | Medium | 1,905 |
https://leetcode.com/problems/word-break/discuss/2361560/Python-Simple-Recursive-with-memoization | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
visited = set()
def wordbreak(s):
if not s or s in wordDict:
return True
elif s in visited:
return
visited.add(s)
curr_str = s[:]
... | word-break | Python - Simple Recursive with memoization | ikn1062 | 0 | 131 | word break | 139 | 0.455 | Medium | 1,906 |
https://leetcode.com/problems/word-break/discuss/2290436/simply-python-dp | class Solution:
def wordBreak(self, s: str, words: List[str]) -> bool:
d = [False] * len(s)
for i in range(len(s)):
for w in words:
if w == s[i-len(w)+1:i+1] and (d[i-len(w)] or i-len(w) == -1):
d[i] = True
return d[-1] | word-break | simply python dp | gasohel336 | 0 | 117 | word break | 139 | 0.455 | Medium | 1,907 |
https://leetcode.com/problems/word-break/discuss/2226546/Python-solution-using-DP-or-Word-Break | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
length = len(s)
dp = [False] * (length + 1)
dp[length] = True
for i in range(length - 1, -1, -1):
for w in wordDict:
if (i + len(w)) <= length and s[i:i+len(w)] == w:
... | word-break | Python solution using DP | Word Break | nishanrahman1994 | 0 | 91 | word break | 139 | 0.455 | Medium | 1,908 |
https://leetcode.com/problems/word-break/discuss/2159927/Python-DP-bug | class Solution:
def wordBreak(self, s: str, wordDict: List[str], memo={}) -> bool:
if s in memo:
return memo[s]
if len(s) == 0:
return True
for word in wordDict:
l = len(word)
if l > len(s) or (not word == s[0:l]):
... | word-break | Python DP bug | MightyBob | 0 | 26 | word break | 139 | 0.455 | Medium | 1,909 |
https://leetcode.com/problems/word-break/discuss/2118083/Easy-to-understand-dp-solution-(python) | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dic={w for w in wordDict}
length=len(s)
dp=[0]*length
for i in range(length):
if s[:i+1] in dic:
dp[i]=1
for j in range(i+1):
if dp[j] and s[j+1:i+1] in d... | word-break | Easy to understand dp solution (python) | xsank | 0 | 74 | word break | 139 | 0.455 | Medium | 1,910 |
https://leetcode.com/problems/word-break/discuss/2063766/Python-O(n2)-faster-than-90-10-liner-stack | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
set_of_words = set(wordDict);
stack = [0];
for i,n in enumerate(s):
index = 1;
while index <= len(stack):
if s[stack[-index]: i +1 ] in set_of_words:
... | word-break | Python O(n^2) faster than 90% 10-liner stack | JohnHulio | 0 | 68 | word break | 139 | 0.455 | Medium | 1,911 |
https://leetcode.com/problems/word-break/discuss/1946852/Python-DP-Beats-95 | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
word_set = set(wordDict)
word_length = [len(x) for x in wordDict]
min_length, max_length = min(word_length), max(word_length)
if len(s) < min_length:
return False
dp = [Fa... | word-break | Python DP Beats 95 % | faygao52 | 0 | 73 | word break | 139 | 0.455 | Medium | 1,912 |
https://leetcode.com/problems/word-break/discuss/1859796/Python3-or-Trie-BFS | class TrieNode:
def __init__(self):
self.nodes = {}
self.is_leaf = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
cur = self.root
for c in word:
if c not in cur.nodes:
cur.nodes[c] = TrieNode(... | word-break | Python3 | Trie BFS | elainefaith0314 | 0 | 215 | word break | 139 | 0.455 | Medium | 1,913 |
https://leetcode.com/problems/word-break/discuss/1843624/python-3-oror-HashSet-%2B-dynamic-programming | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
wordDict = set(wordDict)
dp = set()
self.n = len(s)
def helper(i):
if i == self.n:
return True
if i in dp:
return False
sub = ''... | word-break | python 3 || HashSet + dynamic programming | dereky4 | 0 | 230 | word break | 139 | 0.455 | Medium | 1,914 |
https://leetcode.com/problems/word-break/discuss/1787163/Python-easy-to-read-and-understand-or-DP | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
t = [0 for _ in range(n)]
for i in range(n):
for j in range(i+1):
word = s[j:i+1]
if word in wordDict:
t[i] += t[j-1] if j > 0 else 1
r... | word-break | Python easy to read and understand | DP | sanial2001 | 0 | 280 | word break | 139 | 0.455 | Medium | 1,915 |
https://leetcode.com/problems/word-break-ii/discuss/744674/Diagrammatic-Python-Intuitive-Solution-with-Example | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
def wordsEndingIn(i):
if i == len(s):
return [""]
ans = []
for j in range(i+1, len(s)+1):
... | word-break-ii | Diagrammatic Python Intuitive Solution with Example | ivankatrump | 10 | 526 | word break ii | 140 | 0.446 | Hard | 1,916 |
https://leetcode.com/problems/word-break-ii/discuss/1602252/Time-beats-99.83-or-Space-beats-88.35 | class Solution:
def _wordBreak(self, s, wordDict, start, cur, res):
# Base Case
if start == len(s) and cur:
res.append(' '.join(cur))
for i in range(start, len(s)):
word = s[start: i+1]
if word in wordDict:
... | word-break-ii | Time beats 99.83 % | Space beats 88.35 % | PatrickOweijane | 5 | 415 | word break ii | 140 | 0.446 | Hard | 1,917 |
https://leetcode.com/problems/word-break-ii/discuss/1251729/Python-trie-no-DP | class Solution:
class Trie:
def __init__(self):
self.root = {}
self.WORD_DELIM = '$'
def addWord(self, word):
cur = self.root
for char in word:
if char not in cur:
cur[char] = {}
cur = cu... | word-break-ii | Python trie no DP | mxmb | 4 | 395 | word break ii | 140 | 0.446 | Hard | 1,918 |
https://leetcode.com/problems/word-break-ii/discuss/1437714/Python-Clean-Iterative-DFS-or-Backtracking | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
N = len(s)
queue, sentences = deque([(0, '')]), []
while queue:
i, sentence = queue.pop()
if i == N:
sentences.append(sentence[1:])
con... | word-break-ii | [Python] Clean Iterative DFS | Backtracking | soma28 | 3 | 201 | word break ii | 140 | 0.446 | Hard | 1,919 |
https://leetcode.com/problems/word-break-ii/discuss/1437714/Python-Clean-Iterative-DFS-or-Backtracking | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
def backtrack(i = 0, sentence = ''):
nonlocal N
if i == N:
sentences.append(sentence[1:])
return
for word in wordDict:
index = i+len(word)
... | word-break-ii | [Python] Clean Iterative DFS | Backtracking | soma28 | 3 | 201 | word break ii | 140 | 0.446 | Hard | 1,920 |
https://leetcode.com/problems/word-break-ii/discuss/706993/Python3-top-down-dp | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordDict = set(wordDict) #edit: better performance
@lru_cache(None)
def fn(i):
"""Return sentences of s[i:]"""
if i == len(s): return [[]]
ans = []
for ii ... | word-break-ii | [Python3] top-down dp | ye15 | 3 | 162 | word break ii | 140 | 0.446 | Hard | 1,921 |
https://leetcode.com/problems/word-break-ii/discuss/706993/Python3-top-down-dp | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
@lru_cache(None)
def fn(i):
"""Return sentences from s[:i]"""
if i == 0: return [[]] #boundary condition
ans = []
for word in wordDict:
if s[i-len... | word-break-ii | [Python3] top-down dp | ye15 | 3 | 162 | word break ii | 140 | 0.446 | Hard | 1,922 |
https://leetcode.com/problems/word-break-ii/discuss/2138282/python3-simple-dfs-89-time-99-space | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
ans = []
wordDict = set(wordDict)
def dfs(word, path):
if len(word) == 0:
ans.append(' '.join(path))
return
for i in range(1,len(word)+1):
if... | word-break-ii | python3, simple dfs, 89% time, 99% space | pjy953 | 1 | 32 | word break ii | 140 | 0.446 | Hard | 1,923 |
https://leetcode.com/problems/word-break-ii/discuss/1787326/Python-easy-to-read-and-understand-or-memoization | class Solution:
def solve(self, s, index):
if index == len(s):
return ['']
res = []
for i in range(index, len(s)):
prefix = s[index:i+1]
if prefix in self.d:
suffix = self.solve(s, i+1)
#print(prefix, suffix)
... | word-break-ii | Python easy to read and understand | memoization | sanial2001 | 1 | 152 | word break ii | 140 | 0.446 | Hard | 1,924 |
https://leetcode.com/problems/word-break-ii/discuss/1787326/Python-easy-to-read-and-understand-or-memoization | class Solution:
def solve(self, s, index):
if index == len(s):
return ['']
if index in self.dp:
return self.dp[(index)]
self.dp[(index)] = []
for i in range(index, len(s)):
prefix = s[index:i+1]
if prefix in self.d:
suff... | word-break-ii | Python easy to read and understand | memoization | sanial2001 | 1 | 152 | word break ii | 140 | 0.446 | Hard | 1,925 |
https://leetcode.com/problems/word-break-ii/discuss/763582/Python-Top-down-approach | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordDict = Counter(wordDict)
memo = set()
results = []
def helper(remainingS, result):
if remainingS in memo:
return False
elif len(remainingS) == 0:
... | word-break-ii | Python Top down approach | pujanm | 1 | 365 | word break ii | 140 | 0.446 | Hard | 1,926 |
https://leetcode.com/problems/word-break-ii/discuss/2846105/simple-DFS-solution-in-Python-time-beats-90.83-space-beats-81.92 | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
self.wordSet = set(wordDict)
sLength = len(s)
results = []
start = 0
self.recursion(s, sLength, start, [], results)
return results
def recursion(self, s, sLength, start, resul... | word-break-ii | simple DFS solution in Python, time beats 90.83%, space beats 81.92% | jennycomeon | 0 | 3 | word break ii | 140 | 0.446 | Hard | 1,927 |
https://leetcode.com/problems/word-break-ii/discuss/2819808/Python-simple-DP-solution | class Solution:
def wordBreak(self, s: str, word_dict: List[str]) -> List[str]:
n = len(s)
dp = [[] for _ in range(n + 1)]
for i in range(1, n + 1):
if s[:i] in word_dict:
dp[i].append(s[:i])
for j in range(1, i):
# dp[j], s[j: i]... | word-break-ii | Python simple DP solution | rjdarkknight1 | 0 | 6 | word break ii | 140 | 0.446 | Hard | 1,928 |
https://leetcode.com/problems/word-break-ii/discuss/2803210/Easy-Python-Solution-(DFS-intuitive) | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
'''
Adding all the words from wordDict to hm binding to their first letter
'''
hm = {}
for word in wordDict:
if word[0] in hm.keys():
hm[word[0]].append(word)
... | word-break-ii | Easy Python Solution (DFS, intuitive) | bobbyxq | 0 | 7 | word break ii | 140 | 0.446 | Hard | 1,929 |
https://leetcode.com/problems/word-break-ii/discuss/2774164/Python-clean-solution-using-Trie | class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEnd = False
def addChild(self, c):
if not self.children[ord(c) - ord('a')]:
self.children[ord(c) - ord('a')] = TrieNode()
return self.children[ord(c) - ord('a')]
def getChild(self, c):
... | word-break-ii | Python clean solution using Trie | f0rdpr3fect | 0 | 2 | word break ii | 140 | 0.446 | Hard | 1,930 |
https://leetcode.com/problems/word-break-ii/discuss/2767357/Python-easy-to-understand-followed-up-from-Word-Break-I-97-faster | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
dp = [False]* (len(s)+1)
dp[0] = True
res = {} ## Keeps all combinations of words till index i
for i in range(len(s)+1):
res[i] = []
for i in range(1,len(s)+1):
... | word-break-ii | Python easy to understand followed up from Word Break I, 97% faster | babli_5 | 0 | 8 | word break ii | 140 | 0.446 | Hard | 1,931 |
https://leetcode.com/problems/word-break-ii/discuss/2708535/12-line-python-backtracking | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
word_set = set(wordDict)
res = []
def helper(s, path):
if not s:
res.append(" ".join(path))
for index in range(1, len(s)+1):
word = s[:index]
... | word-break-ii | 12 line python backtracking | woshilaobi22 | 0 | 4 | word break ii | 140 | 0.446 | Hard | 1,932 |
https://leetcode.com/problems/word-break-ii/discuss/2708535/12-line-python-backtracking | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
word_set = set(wordDict)
res = []
no_res_words = set()
def helper(s, path):
if s in no_res_words:
return
if not s:
res.append(" ".join(path))
... | word-break-ii | 12 line python backtracking | woshilaobi22 | 0 | 4 | word break ii | 140 | 0.446 | Hard | 1,933 |
https://leetcode.com/problems/word-break-ii/discuss/2673415/Python-or-BFS-or-Simple-Solution-with-Explanation | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
n = len(s)
combs = defaultdict(list)
for i in range(n):
for word in wordDict:
if word in s[i:i+len(word)]:
combs[i].append(word)
q = deque()
q.appen... | word-break-ii | Python | BFS | Simple Solution with Explanation | devansh_7 | 0 | 8 | word break ii | 140 | 0.446 | Hard | 1,934 |
https://leetcode.com/problems/word-break-ii/discuss/2670044/Python-Recursion | class Solution:
def solve(self,i,prefix,s1,res,s,n):
if i==n:
res.append(prefix[:len(prefix)-1])
return
cur = ""
for j in range(i,n):
cur += s[j]
if cur in s1:
self.solve(j+1, prefix + cur + " ",s1,res,s,n)
... | word-break-ii | Python Recursion | alokiksoni21 | 0 | 6 | word break ii | 140 | 0.446 | Hard | 1,935 |
https://leetcode.com/problems/word-break-ii/discuss/2657443/Backtracking | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
track = []
ans = []
def backtrack(s, i):
if i == len(s) :
ans.append(" ".join(track))
return
for word in wordDict:
n = len(word)
... | word-break-ii | Backtracking | zrbtc | 0 | 7 | word break ii | 140 | 0.446 | Hard | 1,936 |
https://leetcode.com/problems/word-break-ii/discuss/2635249/Python3-Easy-9-Line-Code | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
ans = []
def Check(s, words, path):
if(s == ''):
ans.append(path[1:])
return
for word in words:
if(s[:len(word)] == word):
Check(... | word-break-ii | Python3 Easy 9 Line Code | user2800NJ | 0 | 16 | word break ii | 140 | 0.446 | Hard | 1,937 |
https://leetcode.com/problems/word-break-ii/discuss/2564445/python-simple-backtrack | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordDict = set(wordDict)
res = []
path = []
def backtrack(i):
if i == len(s):
res.append(' '.join(path))
return
for index in range(i, len(s)):
if s[i : index + 1] in wordDict:
path.append(s[i : index + 1])
... | word-break-ii | python simple backtrack | shubhamnishad25 | 0 | 47 | word break ii | 140 | 0.446 | Hard | 1,938 |
https://leetcode.com/problems/word-break-ii/discuss/2537633/python3-Recursion-and-trie-sol-for-reference | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
trie = {}
L = len(s)
O = []
for w in wordDict:
t = trie
for c in w:
if c not in t:
t[c] = {}
t = t[c]
t['#'] = w
... | word-break-ii | [python3] Recursion and trie sol for reference | vadhri_venkat | 0 | 29 | word break ii | 140 | 0.446 | Hard | 1,939 |
https://leetcode.com/problems/word-break-ii/discuss/2439424/Back-tracking-using-word-index-at-every-position-(example-illustration-for-easy-understand) | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
"""
0 1 2 3 4 5 6 7 8 9 10
c a t s a n d d o g
3 7 7 10
4
"""
def fsol(k):
for i in sidx[k]:
cur.append(s[k:i])
if i==len(s):
... | word-break-ii | Back-tracking using word-index at every position (example illustration for easy understand) | dntai | 0 | 17 | word break ii | 140 | 0.446 | Hard | 1,940 |
https://leetcode.com/problems/word-break-ii/discuss/2309092/Backtracking-solution-with-30ms-runtime-in-Python3 | class Solution:
def wordBreak(self, s: str, wordDict):
output = []
def backtracking(restString, candidate):
# When the restString is empty, it means all substring/prefix of s are found in dictionary.
# Add candidate to output answer.
if restString == "":
... | word-break-ii | Backtracking solution with 30ms runtime in Python3 | wing781227 | 0 | 14 | word break ii | 140 | 0.446 | Hard | 1,941 |
https://leetcode.com/problems/word-break-ii/discuss/2238934/python-solution-or-easy-understanding-BFS | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
q = deque()
for i in range(len(s)+1):
if s[:i] in wordDict:
q.append((i, [s[:i]]))
res = []
while q:
idx, path = q.popleft()
if idx == ... | word-break-ii | python solution | easy understanding, BFS | hardernharder | 0 | 21 | word break ii | 140 | 0.446 | Hard | 1,942 |
https://leetcode.com/problems/word-break-ii/discuss/2177683/Backtracking-Solution-without-Trie | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
n = len(s)
res = []
def rec(i=0, curr = []):
if i>=n:
res.append(" ".join(curr))
return
temp = ""
for j in ra... | word-break-ii | Backtracking Solution without Trie | abhijeetgupto | 0 | 36 | word break ii | 140 | 0.446 | Hard | 1,943 |
https://leetcode.com/problems/word-break-ii/discuss/2102759/Backtracing-solution-beats-88-in-time-88-in-space | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
res = []
def check(ns, splits):
if not ns:
if splits[-1] in wordDict:
res.append(" ".join(splits))
else:
... | word-break-ii | Backtracing solution beats 88% in time 88% in space | zhenyulin | 0 | 20 | word break ii | 140 | 0.446 | Hard | 1,944 |
https://leetcode.com/problems/word-break-ii/discuss/1826335/Recursive-Easy-and-Explained-(Runtime%3A-faster-than-74.03-Memory%3A-less-than-90.74) | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
ret = []
def recursive(s: str, current: str):
nonlocal ret
if len(s) == 0:
ret.append(current.strip())
for word in wordDict:
if s.startswith... | word-break-ii | Recursive Easy & Explained (Runtime: faster than 74.03%, Memory: less than 90.74%) | pierluigif | 0 | 37 | word break ii | 140 | 0.446 | Hard | 1,945 |
https://leetcode.com/problems/word-break-ii/discuss/1826086/python3-92-or-BackTrack-or-Easy-Implementation | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
leng = len(s)
wordDict = set(wordDict)
output = []
def bt(cur_ind, path):
# print(path[:])
if cur_ind == leng:
output.append(path[:])
return
... | word-break-ii | python3 92% | BackTrack | Easy Implementation | doneowth | 0 | 38 | word break ii | 140 | 0.446 | Hard | 1,946 |
https://leetcode.com/problems/word-break-ii/discuss/1825293/Extending-the-WordBreak-I | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
dp = [[] for idx in range(len(s)+1)]
dp[len(s)] = [""]
for idx in range(len(s)-1,-1, -1):
for word in wordDict:
if((idx+len(word) <= len(s) and word == s[idx : idx + len(word)])):
... | word-break-ii | Extending the WordBreak I | beginne__r | 0 | 20 | word break ii | 140 | 0.446 | Hard | 1,947 |
https://leetcode.com/problems/word-break-ii/discuss/1763782/python3-backtracking-with-str.startswith()-29ms | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
opts = set(wordDict)
ans = []
def backtrack(s, path):
if not s:
if path:
ans.append(path[1:])
return
for opt in opt... | word-break-ii | python3 backtracking with str.startswith() 29ms | vandesa003 | 0 | 30 | word break ii | 140 | 0.446 | Hard | 1,948 |
https://leetcode.com/problems/word-break-ii/discuss/1652523/Python-simple-recursion-approach-28-ms-faster-than-83.49-of-Python3-online-submissions | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
ans = []
def _dfs(path, substring):
if len(substring)==0:
sentence = " ".join(path)
ans.append(sentence)
return
for i in range(len(substring)+1):
... | word-break-ii | Python simple recursion approach 28 ms, faster than 83.49% of Python3 online submissions | takahiro2 | 0 | 66 | word break ii | 140 | 0.446 | Hard | 1,949 |
https://leetcode.com/problems/word-break-ii/discuss/1576420/Beats-96.4-submissions-Easy-BFS-with-detail-comment-beginner-level-understanding | class Solution:
def wordBreak(self, raw: str, lookup: List[str]) -> List[str]:
# var reservation
listOpened, listClosed, length = [(var, len(var)) for var in lookup if raw.startswith(var)], [], len(raw)
# keep search till open structure empty
while listOpened:
# pop ... | word-break-ii | Beats 96.4% submissions, Easy BFS with detail comment, beginner level understanding | kaijCH | 0 | 100 | word break ii | 140 | 0.446 | Hard | 1,950 |
https://leetcode.com/problems/word-break-ii/discuss/1542917/Python-backtrack | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
res = []
wordDict = set(wordDict)
def split(str_, start=0, end=1, path=None):
if path is None:
path = list()
if end > len(str_):
res.append(" ".join(path))... | word-break-ii | Python backtrack | juwax | 0 | 54 | word break ii | 140 | 0.446 | Hard | 1,951 |
https://leetcode.com/problems/word-break-ii/discuss/1527061/Python3-Time%3A-O(WN) | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
# s = "catsanddog"
# wordDict = ["cat","cats","and","sand","dog"]
target = len(s)
ans = []
def recursive(n, stack):
if n == target:
ans.append(" ".join... | word-break-ii | [Python3] Time: O(W^N) | jae2021 | 0 | 56 | word break ii | 140 | 0.446 | Hard | 1,952 |
https://leetcode.com/problems/word-break-ii/discuss/1467573/Python-BFS-and-thorough-space-and-time-complexity-analysis-explained | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordDict = set(wordDict) # T.C: O(M) S.C: O(M*L)
queue = deque([(0, 0, "")])
seen = set()
answer = []
while len(queue) != 0:
for _ in range(len(queue)):
... | word-break-ii | [Python] BFS and thorough space and time complexity analysis explained | asbefu | 0 | 229 | word break ii | 140 | 0.446 | Hard | 1,953 |
https://leetcode.com/problems/word-break-ii/discuss/1462067/PyPy3-Simple-recursive-solution-w-comments | class Solution:
def wordBreak(self, s: str, words: List[str]) -> List[str]:
# Init
m = len(s)
outputs = []
# Recursive solution
def recursive(n=0, stack=[]):
nonlocal outputs # global variable
# If end of str... | word-break-ii | [Py/Py3] Simple recursive solution w/ comments | ssshukla26 | 0 | 88 | word break ii | 140 | 0.446 | Hard | 1,954 |
https://leetcode.com/problems/word-break-ii/discuss/1452215/Python3-or-Backtracking | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
self.ans=[]
word=set(wordDict)
self.dfs(s,word,[])
return self.ans
def dfs(self,s,word,ds):
if s=="":
self.ans.append(" ".join(ds[:]))
return True
for i in range... | word-break-ii | [Python3] | Backtracking | swapnilsingh421 | 0 | 66 | word break ii | 140 | 0.446 | Hard | 1,955 |
https://leetcode.com/problems/word-break-ii/discuss/1415947/Very-Simple-%2B-Clean-Python-BFS-beats-95 | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
# Create a hash map for starting letter:words
wg = collections.defaultdict(set)
for i in wordDict:
wg[i[0]].add(i)
res = []
# Standard BFS using a Q.
q = c... | word-break-ii | Very Simple + Clean Python BFS beats 95% | Pythagoras_the_3rd | 0 | 120 | word break ii | 140 | 0.446 | Hard | 1,956 |
https://leetcode.com/problems/word-break-ii/discuss/1405067/Python-24ms-or-Easy-to-understand-Code | class Solution:
def helper(self, s, wordDict, idx, n):
if idx == n:
return [[]]
if idx in self.cache:
return self.cache[idx]
paths = []
cs = ""
for i in range(idx, n):
cs += s[i]
if cs in wordDict:
... | word-break-ii | Python 24ms | Easy to understand Code | sathwickreddy | 0 | 149 | word break ii | 140 | 0.446 | Hard | 1,957 |
https://leetcode.com/problems/word-break-ii/discuss/1387435/Python3-KMP-and-backtrack-20ms-beat-99 | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
def partial(pattern):
ret = [0]
for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and pattern[j] != pattern[i]:
j = ret[j - 1]
... | word-break-ii | [Python3] KMP and backtrack, 20ms beat 99% | hieuvpm | 0 | 59 | word break ii | 140 | 0.446 | Hard | 1,958 |
https://leetcode.com/problems/word-break-ii/discuss/1386171/String-startswith()-95-speed | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
dict_word = defaultdict(list)
for w in wordDict:
dict_word[w[0]].append(w)
state = [[s, []]]
ans = []
while state:
new_state = []
for sub_s, lst in state:
... | word-break-ii | String startswith(), 95% speed | EvgenySH | 0 | 49 | word break ii | 140 | 0.446 | Hard | 1,959 |
https://leetcode.com/problems/word-break-ii/discuss/1323628/Python-backtracking-(beats-99) | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
t=[]
@lru_cache(None)
def solve(i,j,s1):
if j==len(s):
return
if i>j:
return
s2=s1
string=s[i:j+1]
if string in wordDict:... | word-break-ii | Python backtracking (beats 99%) | ketan_raut | 0 | 79 | word break ii | 140 | 0.446 | Hard | 1,960 |
https://leetcode.com/problems/word-break-ii/discuss/1292759/Python-Top-Down-Super-Simple-Solution | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordSet = set(wordDict)
res = []
combo = []
def dfs(i):
if i == len(s):
res.append(" ".join(combo))
return
for j in range(i, len(s) + 1... | word-break-ii | [Python] Top-Down Super Simple Solution | genefever | 0 | 64 | word break ii | 140 | 0.446 | Hard | 1,961 |
https://leetcode.com/problems/word-break-ii/discuss/1184853/python-with-explaining-and-comments-easy-to-unsterstand-faster-than-80-(28ms) | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
l = len(s)
dp = [False] * (l + 1)
dp[0] = True
len_word = [len(x) for x in wordDict]
min_len = min(len_word)
max_len = max(len_word)
pos_dict = collections.default... | word-break-ii | python with explaining and comments, easy to unsterstand, faster than 80% (28ms) | dustlihy | 0 | 117 | word break ii | 140 | 0.446 | Hard | 1,962 |
https://leetcode.com/problems/word-break-ii/discuss/777030/Python-Bottom-Up-Approach-using-DP | class Solution:
"""
Similar to wordbreak dp solution
1) Will iterate through different lengths up to total length
2) inner loop will iterate number of ways to distribute length
3) in dp table will note witheer its possible or not + keep and array of different ways to create the solution
... | word-break-ii | Python - Bottom Up Approach using DP | dpark068 | 0 | 273 | word break ii | 140 | 0.446 | Hard | 1,963 |
https://leetcode.com/problems/word-break-ii/discuss/744852/My-commented-and-efficient-python-iterative-solution. | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
N = len(s) # calculate the length of the string
# Initialize a dpTable, dpDict, create a set of wordDict for dater lookup
dpTable = [True] + [False]*N
dpDict = collections.defaultdict(list)
... | word-break-ii | My commented and efficient python iterative solution. | darshan_22 | 0 | 190 | word break ii | 140 | 0.446 | Hard | 1,964 |
https://leetcode.com/problems/word-break-ii/discuss/399931/Help!-Why-can't-my-code-pass-the-%22pineapplepenapple%22-case | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
self.res = []
def helper(s,dic,path):
if not s:
self.res.append(' '.join(path))
return
if s in dic:
return
for i in range(1,len(... | word-break-ii | Help! Why can't my code pass the "pineapplepenapple" case? | roguerui6 | 0 | 104 | word break ii | 140 | 0.446 | Hard | 1,965 |
https://leetcode.com/problems/linked-list-cycle/discuss/1047819/Easy-in-Pythonor-O(1)-or-Beats-91 | class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None return False
slow_ref = head
fast_ref = head
while fast_ref and fast_ref.next:
slow_ref = slow_ref.next
f... | linked-list-cycle | Easy in Python| O(1) | Beats 91% | vsahoo | 13 | 948 | linked list cycle | 141 | 0.47 | Easy | 1,966 |
https://leetcode.com/problems/linked-list-cycle/discuss/2439002/Very-Easy-oror-0-ms-oror100oror-Fully-Explained-(Java-C%2B%2B-Python-JS-C-Python3) | class Solution(object):
def hasCycle(self, head):
# Initialize two node slow and fast point to the hesd node...
fastptr = head
slowptr = head
while fastptr is not None and fastptr.next is not None:
# Move slow pointer by 1 node and fast at 2 at each step.
slow... | linked-list-cycle | Very Easy || 0 ms ||100%|| Fully Explained (Java, C++, Python, JS, C, Python3) | PratikSen07 | 12 | 944 | linked list cycle | 141 | 0.47 | Easy | 1,967 |
https://leetcode.com/problems/linked-list-cycle/discuss/2439002/Very-Easy-oror-0-ms-oror100oror-Fully-Explained-(Java-C%2B%2B-Python-JS-C-Python3) | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
# Initialize two node slow and fast point to the hesd node...
fastptr = head
slowptr = head
while fastptr is not None and fastptr.next is not None:
# Move slow pointer by 1 node and fast at 2 at each st... | linked-list-cycle | Very Easy || 0 ms ||100%|| Fully Explained (Java, C++, Python, JS, C, Python3) | PratikSen07 | 12 | 944 | linked list cycle | 141 | 0.47 | Easy | 1,968 |
https://leetcode.com/problems/linked-list-cycle/discuss/1857668/2-Python-Solutions | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow=fast=head
while fast and fast.next:
fast=fast.next.next
slow=slow.next
if slow==fast: return True
return False | linked-list-cycle | 2 Python Solutions | Taha-C | 7 | 227 | linked list cycle | 141 | 0.47 | Easy | 1,969 |
https://leetcode.com/problems/linked-list-cycle/discuss/1857668/2-Python-Solutions | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
D={}
while head:
if head in D: return True
D[head]=True
head=head.next
return False | linked-list-cycle | 2 Python Solutions | Taha-C | 7 | 227 | linked list cycle | 141 | 0.47 | Easy | 1,970 |
https://leetcode.com/problems/linked-list-cycle/discuss/1857668/2-Python-Solutions | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
S=set()
while head:
if head in S: return True
S.add(head)
head=head.next
return False | linked-list-cycle | 2 Python Solutions | Taha-C | 7 | 227 | linked list cycle | 141 | 0.47 | Easy | 1,971 |
https://leetcode.com/problems/linked-list-cycle/discuss/366752/Python-two-pointers | class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return Tru... | linked-list-cycle | Python two pointers | amchoukir | 5 | 602 | linked list cycle | 141 | 0.47 | Easy | 1,972 |
https://leetcode.com/problems/linked-list-cycle/discuss/2158864/Python3-using-fast-and-slow-pointers | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False | linked-list-cycle | 📌 Python3 using fast & slow pointers | Dark_wolf_jss | 4 | 96 | linked list cycle | 141 | 0.47 | Easy | 1,973 |
https://leetcode.com/problems/linked-list-cycle/discuss/1757200/Python-O(1)-Space-Solution-or-Faster-or-Tortoise-and-Hare-Approach | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if head is None:
return False
slow=fast=head
while (fast.next is not None) and (fast.next.next is not None):
slow=slow.next
fast=fast.next.next
if slow==fast: ret... | linked-list-cycle | Python O(1) Space Solution | Faster | Tortoise and Hare Approach | Anilchouhan181 | 4 | 207 | linked list cycle | 141 | 0.47 | Easy | 1,974 |
https://leetcode.com/problems/linked-list-cycle/discuss/1342078/Runtime%3A-40-ms-faster-than-99.75-of-Python3-online-submissions-for-Linked-List-Cycle. | class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast, slow = head, head
while fast != None and fast.next != None and slow != None:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False | linked-list-cycle | Runtime: 40 ms, faster than 99.75% of Python3 online submissions for Linked List Cycle. | samirpaul1 | 4 | 252 | linked list cycle | 141 | 0.47 | Easy | 1,975 |
https://leetcode.com/problems/linked-list-cycle/discuss/1956399/Python3-oror-Beats-96.96-oror-2-Approach(Tortoise-hare-algo-and-Trick) | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow,fast = head,head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False | linked-list-cycle | ✅Python3 || Beats 96.96% || 2 Approach(Tortoise - hare algo and Trick) | Dev_Kesarwani | 3 | 194 | linked list cycle | 141 | 0.47 | Easy | 1,976 |
https://leetcode.com/problems/linked-list-cycle/discuss/1956399/Python3-oror-Beats-96.96-oror-2-Approach(Tortoise-hare-algo-and-Trick) | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
while head:
if head.val == None:
return True
head.val = None
head = head.next
return False | linked-list-cycle | ✅Python3 || Beats 96.96% || 2 Approach(Tortoise - hare algo and Trick) | Dev_Kesarwani | 3 | 194 | linked list cycle | 141 | 0.47 | Easy | 1,977 |
https://leetcode.com/problems/linked-list-cycle/discuss/1795901/Python-Simple-Python-Solution-By-Slow-and-Fast-Pointer-Approach | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False | linked-list-cycle | [ Python ] ✔✔ Simple Python Solution By Slow and Fast Pointer Approach 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 3 | 196 | linked list cycle | 141 | 0.47 | Easy | 1,978 |
https://leetcode.com/problems/linked-list-cycle/discuss/1794185/Python-O(1)-memory-5-lines-simple-solution | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
while head:
if head.val == -10**7:return True
head.val = -10**7
head = head.next
return False | linked-list-cycle | [Python] O(1) memory 5 lines simple solution | Sol-cito | 3 | 136 | linked list cycle | 141 | 0.47 | Easy | 1,979 |
https://leetcode.com/problems/linked-list-cycle/discuss/255055/Python-40ms-~-simple-~-beats-99 | class Solution(object):
def hasCycle(self, head):
nodesSeen = set() # a set is a data type that does not accept duplicates
while head is not None: # when head is None, you've reached end of linkedlist
if head in nodesSeen:
return True
else:
nod... | linked-list-cycle | Python 40ms ~ simple ~ beats 99% | nicolime | 3 | 607 | linked list cycle | 141 | 0.47 | Easy | 1,980 |
https://leetcode.com/problems/linked-list-cycle/discuss/2365073/python-or-Faster-than-90!!! | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next: return False
fast=slow=head
while fast and fast.next:
fast=fast.next.next
slow=slow.next
if fast==slow:
return True
return False | linked-list-cycle | python | Faster than 90%!!! | solityde | 2 | 112 | linked list cycle | 141 | 0.47 | Easy | 1,981 |
https://leetcode.com/problems/linked-list-cycle/discuss/1830095/Python-very-easy-solution-or-Explained | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
s = set()
while head:
if head in s: return True
s.add(head)
head = head.next
return False | linked-list-cycle | ✅ Python very easy solution | Explained | dhananjay79 | 2 | 161 | linked list cycle | 141 | 0.47 | Easy | 1,982 |
https://leetcode.com/problems/linked-list-cycle/discuss/1830095/Python-very-easy-solution-or-Explained | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast: return True
return False | linked-list-cycle | ✅ Python very easy solution | Explained | dhananjay79 | 2 | 161 | linked list cycle | 141 | 0.47 | Easy | 1,983 |
https://leetcode.com/problems/linked-list-cycle/discuss/1731248/PYTHON-3-or-EASY-SOLUTION-or | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
node = head
while node :
if node.val == False :
return True
else :
node.val = False
node = node.next
return False | linked-list-cycle | PYTHON 3 | EASY SOLUTION | | rohitkhairnar | 2 | 249 | linked list cycle | 141 | 0.47 | Easy | 1,984 |
https://leetcode.com/problems/linked-list-cycle/discuss/1731248/PYTHON-3-or-EASY-SOLUTION-or | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False | linked-list-cycle | PYTHON 3 | EASY SOLUTION | | rohitkhairnar | 2 | 249 | linked list cycle | 141 | 0.47 | Easy | 1,985 |
https://leetcode.com/problems/linked-list-cycle/discuss/1705384/Short-and-simple-O(n)-solution-in-python3 | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
new_node = ListNode(0)
while head and head.next != new_node:
next_node = head.next
head.next = new_node
head = next_node
if head == None:
return False
elif head.next ... | linked-list-cycle | Short and simple O(n) solution in python3 | harshig | 2 | 138 | linked list cycle | 141 | 0.47 | Easy | 1,986 |
https://leetcode.com/problems/linked-list-cycle/discuss/1596801/Python3-one-pointer | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
while head and head.next:
if str(head.val) == "visited": #if visited
return True
head.val = "visited" #mark visited
head = head.next
return False | linked-list-cycle | Python3 one pointer | Mandyzmr | 2 | 109 | linked list cycle | 141 | 0.47 | Easy | 1,987 |
https://leetcode.com/problems/linked-list-cycle/discuss/1357354/Ez-to-understand-python-solution | class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
while head:
if head.val == 'somerandomshit1234!@!@':
return True
else:
head.val = 'somerandomshit1234!@!@'
head = he... | linked-list-cycle | Ez to understand python solution | xcg1234 | 2 | 152 | linked list cycle | 141 | 0.47 | Easy | 1,988 |
https://leetcode.com/problems/linked-list-cycle/discuss/2321064/Python-solution-with-comments-on-line-of-code-with-easy-explanation | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
# Using slow and fast pointers A.K.A. Hare and Tortoise Algorithm or Floyd's Cycle Detection Algorithm
slow, fast = head, head
# If there's a node and the node is connected to other node using next pointe... | linked-list-cycle | Python solution with comments on line of code with easy explanation | pawelborkar | 1 | 79 | linked list cycle | 141 | 0.47 | Easy | 1,989 |
https://leetcode.com/problems/linked-list-cycle/discuss/2240379/Python-Floyd's-Tortoise-and-Hare-Algorithm-Time-O(N)-or-Space-O(1)-Explained | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head
while fast and fast.next:
slow = slow.next # Move 1 node ahead
fast = fast.next.next # Move 2 nodes ahead
# We found a cycle
if ... | linked-list-cycle | [Python] Floyd's Tortoise & Hare Algorithm - Time O(N) | Space O(1) Explained | Symbolistic | 1 | 53 | linked list cycle | 141 | 0.47 | Easy | 1,990 |
https://leetcode.com/problems/linked-list-cycle/discuss/2143594/99.49-memory-86.73-time(-O(1)-memory-) | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:return False
addr, pre, cur = 1, head, head.next
while True:
if not cur:return False
else:
if cur == addr:return True
pre, cur = cur, cur... | linked-list-cycle | 99.49% memory 86.73 time( O(1) memory ) | TUL | 1 | 210 | linked list cycle | 141 | 0.47 | Easy | 1,991 |
https://leetcode.com/problems/linked-list-cycle/discuss/2107115/Python-Simple-readable-easy-to-understand-dictionary-solution-(beats-96) | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
visited = {}
while head:
if head.next in visited:
return True
visited[head] = True
head = head.next
return False | linked-list-cycle | [Python] Simple, readable, easy to understand dictionary solution (beats 96%) | FedMartinez | 1 | 149 | linked list cycle | 141 | 0.47 | Easy | 1,992 |
https://leetcode.com/problems/linked-list-cycle/discuss/2104698/Simple-Most-memory-efficient-solution-Python | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
while head:
if not head.val:
return True
head.val = None
head = head.next
return False | linked-list-cycle | Simple, Most memory efficient solution - Python | JuanRodriguez | 1 | 44 | linked list cycle | 141 | 0.47 | Easy | 1,993 |
https://leetcode.com/problems/linked-list-cycle/discuss/1830315/Easy-Python-Solution-or-Slow-and-Fast-Pointer-Approach | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False
slow = head.next
fast = head.next.next
while fast and fast.next:
if slow==fast:
return True
slow = slow.next
... | linked-list-cycle | Easy Python Solution | Slow and Fast Pointer Approach | sharmakaushal | 1 | 25 | linked list cycle | 141 | 0.47 | Easy | 1,994 |
https://leetcode.com/problems/linked-list-cycle/discuss/1709488/O(n)-time-O(1)-space-or-Python-3-or-Easy-to-read | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow, fast = head, head
while fast is not None:
slow = slow.next
fast = fast.next
if fast is not None:
fast = fast.next
if slow is ... | linked-list-cycle | O(n) time, O(1) space | Python 3 | Easy to read | fourcommas | 1 | 96 | linked list cycle | 141 | 0.47 | Easy | 1,995 |
https://leetcode.com/problems/linked-list-cycle/discuss/1709460/O(n)-time-and-space-or-Python-3-or-Easy-to-read | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
seen_ids = set()
while head is not None:
node_id = id(head)
if node_id in seen_ids:
return True
seen_ids.add(node_id)
head = head.n... | linked-list-cycle | O(n) time and space | Python 3 | Easy to read | fourcommas | 1 | 32 | linked list cycle | 141 | 0.47 | Easy | 1,996 |
https://leetcode.com/problems/linked-list-cycle/discuss/1557185/Python-or-runtime%3A-95-and-memory%3A-98-or-simple-commented-solution | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
'''traverse the linked list and update each node values to 'visited'.
if during the traversal, you encounter a node with value 'visited' then there's a
cycle
'''
if head and head.next: #if the lin... | linked-list-cycle | Python | runtime: 95% and memory: 98% | simple commented solution | He11oWor1d | 1 | 177 | linked list cycle | 141 | 0.47 | Easy | 1,997 |
https://leetcode.com/problems/linked-list-cycle/discuss/1526509/Python-6-lines-98.85-Time-80.79-Space | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False | linked-list-cycle | [Python] 6 lines 98.85% Time, 80.79% Space | JosephJia | 1 | 358 | linked list cycle | 141 | 0.47 | Easy | 1,998 |
https://leetcode.com/problems/linked-list-cycle/discuss/1457013/Python3C%2B%2B-Several-Solutions-and-O(1)-space | class Solution:
def hasCycle(self, head: ListNode) -> bool:
s = set()
cur = head
while cur:
if cur in s:
return True
s.add(cur)
cur = cur.next
return False | linked-list-cycle | [Python3/C++] Several Solutions and O(1) space | light_1 | 1 | 142 | linked list cycle | 141 | 0.47 | Easy | 1,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.