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]: node.children[ascii] = TrieNode(ch) node = node.children[ascii] node.eow = True def Trie_search(word,Trieroot): node = Trieroot for ch in word: ascii = ord(ch) - ord('a') if not node.children[ascii]: return False node = node.children[ascii] if node.eow: return True return False class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: ln = len(s) dp = [True] + [False]*ln Trieroot = TrieNode() for word in wordDict: Trie_add(word, Trieroot) for end in range(1,ln + 1): for st in range(end): this_word = s[st: end] if dp[st] and Trie_search(this_word, Trieroot): dp[end] =True break return dp[-1]
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 substrings and check if the strings in the dictionary are present in the substring. 2. This will not work, why? Because strings in the mother set may have been used already to create another string SOLUTION -------------------------- 1. Go through the dictionary of words and find the string which is the potential begining of the string 2. segment the length of that string from the string. 3. Check if the remaining string can also be segmented in words from the dictionary. 4. if there are no more strings to segment then we can return True. 5. This is a recurrence problem and can be solved with the recurrence solution. 6. The recurrence function should go through the word dictionary and the one which qualifies will now segment the rest of the string and check for the rest of the segment of the string. FOR THE RECURRENCE RELATION 1. With every word in the dictionary, get the length of the word. 2. Check if a segment of the string is equal to that word. 3. if True, call the function of the rest of the segment of the string. Base Case: 1. If all strings are segmented, which means we have the empty ("") string so we can then return True 2. Else we return False """ """ RECURRENCE SOLUTION """ def sectionBreak(string): if len(string) == 0: return True for word in wordDict: prefix = string[:len(word)] if prefix == word and sectionBreak(string[len(word):]): return True return False return sectionBreak(s) """ MOMOIZATION """ def sectionBreak(string, memo): if len(string) == 0: return True elif string in memo: return memo[string] for word in wordDict: prefix = string[:len(word)] if prefix == word and sectionBreak(string[len(word):], memo): memo[string] = True return True memo[string] = False return False return sectionBreak(s, {}) """ The dynammic programming approach 1. The empty substring can be segmented to any of the words in the dictionary. 2. Let the index of the words represents the sufix of words in the dictionary. 3. If suffix of a word is in the dictionary then and the suffix of the previous word is also in the dictionary, then it stands to prove that, the substring of the string up to the current suffix can also be segmented """ # Initialize a dp table with the length of the string + 1 # Plus 1 is to compensate for the empty string # You can either iterate from the back if you want to use the prefix instead of suffix pointers. wordSet = set(wordDict) # put words in a hashSet to optimize lookup to O(1) dp = [False for _ in range(len(s)+1)] dp[0] = True for i in range(1, len(s)+1): for j in range(i-1, -1, -1): if dp[j] and s[j:i] in wordSet: dp[i] = True break # break from the loop if a segment is found return dp[-1]
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 range(n): lw=len(wordDict[j]) if s[i:i+lw] in ss: if rec(i+lw): return True return False # return False # break # else: # return False # break return rec(0)
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[j] == True): word = s[j: i] if word in dict: dp[i] = True break return dp[-1]
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 return dp[-1]
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[:] for i in range(len(s)): curr_str = curr_str[:-1] if curr_str in wordDict and wordbreak(s[-1-i:]): return True return False return wordbreak(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: dp[i] = dp[i + len(w)] if dp[i]: break return dp[0]
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]): continue if self.wordBreak(s[l:], wordDict): memo[s] = True return True memo[s] = False return False
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 dic: dp[i]=1 return dp[-1]
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: stack.append(i+1) break; index+=1; return (stack.pop() == len(s) )
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 = [False] * (n + 1) dp[0] = True for i in range(1, n - min_length + 2): for j in range(i - 1 + min_length, min(i + max_length, n + 1)): if dp[i - 1] and s[i - 1:j] in word_set: dp[j] = True return dp[-1]
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() cur = cur.nodes[c] cur.is_leaf = True class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: trie = Trie() for word in wordDict: trie.insert(word) parents = set([0]) children = set() while parents: for p in parents: cur = trie.root i = p while i < len(s): if s[i] in cur.nodes: if cur.nodes[s[i]].is_leaf: if i < len(s)-1: children.add(i+1) else: return True cur = cur.nodes[s[i]] i += 1 else: break parents = children children = set() return False
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 = '' for j in range(i, self.n): sub += s[j] if sub in wordDict and helper(j + 1): return True dp.add(i) return False return helper(0)
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 return t[n-1]
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): if s[i:j] in wordDict: for tail in wordsEndingIn(j): if tail != '': ans.append(s[i:j] + " " + tail) else: ans.append(s[i:j]) return ans return wordsEndingIn(0)
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: # Append the word since it is in the dictionary cur.append(word) # Recursive Step self._wordBreak(s, wordDict, i+1, cur, res) # Backtracking / Post-processing / Pop the word we appended cur.pop() def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: res = [] self._wordBreak(s, set(wordDict), 0, [], res) return res
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 = cur[char] cur[self.WORD_DELIM] = word def addWords(self, words): for word in words: self.addWord(word) def getValidSentences(self, word, res = ''): res = [] def dfs(word=word, temp=[]): cur = self.root for i,char in enumerate(word): if self.WORD_DELIM in cur: dfs(word[i:], temp + [cur[self.WORD_DELIM]]) if char not in cur: break cur = cur[char] else: if self.WORD_DELIM in cur: res.append(' '.join(temp + [cur[self.WORD_DELIM]])) dfs() return res def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: trie = self.Trie() trie.addWords(wordDict) return trie.getValidSentences(s)
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:]) continue for word in wordDict: index = i+len(word) if index <= N and s[i:index] == word: queue.append((index, sentence+' '+word)) return sentences
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) if index <= N and s[i:index] == word and i not in visited: visited.add(i) backtrack(index, sentence+' '+word) visited.remove(i) N = len(s) sentences, visited = [], set() backtrack() return sentences
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 in range(i+1, len(s)+1): if s[i:ii] in wordDict: ans.extend([s[i:ii]] + x for x in fn(ii)) return ans return [" ".join(x) for x in fn(0)]
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):i] == word: ans.extend([x + [word] for x in fn(i-len(word))]) return ans return [" ".join(x) for x in fn(len(s))]
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[:i] in wordDict: dfs(word[i:], path+[word[:i]]) dfs(s,[]) return ans
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) for words in suffix: if words == '': res.append(prefix + words) else: res.append(prefix + " " + words) return res def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: self.d = wordDict return self.solve(s, 0)
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: suffix = self.solve(s, i+1) #print(prefix, suffix) for words in suffix: if words == '': self.dp[(index)].append(prefix + words) else: self.dp[(index)].append(prefix + " " + words) return self.dp[(index)] def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: self.d = wordDict self.dp = {} return self.solve(s, 0)
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: results.append(result.strip()) return True else: flag = False S = "" for i in range(len(remainingS)): S = S + remainingS[i] if S in wordDict: flag |= helper(remainingS[i+1:], result + S + " ") if not flag: memo.add(remainingS) return flag helper(s, "") return results
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, result, results): if start == sLength: curSent = ' '.join(result) results.append(curSent) return for i in range(start, sLength): curWord = s[start:i+1] if curWord in self.wordSet: result.append(curWord) self.recursion(s, sLength, i+1, result, results) result.pop()
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] # 'catsand': dp[3], s[3: 7] = 'sand' if dp[j] and s[j: i] in word_dict: for prefix in dp[j]: dp[i].append(prefix + ' ' + s[j: i]) return dp[-1] # 0123456789 # catsanddog # dp[0]: '', [] # dp[1]: 'c', [] # dp[3]: 'cat', ['cat'] # dp[4]: 'cats', ['cats'] # dp[7]: 'catsand', ['cat sand', 'cats and'] # dp[10]: 'catsanddog', ['cat sand dog', 'cats and dog']
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) else: hm[word[0]] = [word] res = [] ''' currList is a list of words that could potentially combine to construct a sentence and be stored in res. i in the index of s that we are currently working on. ''' def dfs(currList, i): #if there are words that has first letter equal to the next letter in s if s[i] in hm.keys(): #iterate through every words of that key in map for w in hm[s[i]]: #if the word is part of s if w == s[i:i+len(w)]: #option 1: we could accept this word and add it to the list currList.append(w) #if adding this word reaches the end of s, a sentence is found, we add it to result if i + len(w) == len(s): res.append(' '.join(currList)) #else we continue searching else: dfs(currList, i+len(w)) #option 2: we reject this word and continue searching without it currList.pop() dfs([],0) return res
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): return self.children[ord(c) - ord('a')] def markEnd(self): self.isEnd = True class Solution: def insert(self, trieRoot, word): node = trieRoot for char in word: node = node.addChild(char) node.markEnd() def buildTrie(self, wordDict): root = TrieNode() for word in wordDict: self.insert(root, word) return root def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: n = len(s) root = self.buildTrie(wordDict) node = root answers = [] def visit(index, node, currSent): if index == n: if node != root and node.isEnd: answers.append(''.join(currSent)) return char = s[index] child = node.getChild(char) if child: currSent.append(char) visit(index+1, child, currSent.copy()) if child.isEnd: currSent.append(" ") visit(index+1, root, currSent.copy()) visit(0, root, []) return answers
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): for w in wordDict: if s[i-len(w):i]==w and dp[i-len(w)]: dp[i] = True #### If last word index results has some words combinations present, append current word to it if res[i-len(w)]!=[]: for oldWords in res[i-len(w)]: curr = oldWords +' '+ w res[i].append(curr) else: curr = w res[i].append(curr) return res[len(s)] ## Combinations of all words at last index
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] if word in word_set: path.append(word) helper(s[index:], path) path.pop() helper(s, []) return res
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)) before_len = len(res) for index in range(1, len(s)+1): word = s[:index] if word in word_set: path.append(word) helper(s[index:], path) if len(res)==before_len: no_res_words.add(s[index:]) path.pop() helper(s, []) return res
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.append([0, ""]) ans = [] while q: node, sent = q.popleft() if node == n: ans.append(sent[1:]) else: for w in combs[node]: newNode = node+len(w) q.append([newNode, sent + " " + w]) return ans
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) def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: s1 = set(wordDict) res = [] n =len(s) self.solve(0,"",s1,res,s,n) # res.sort() return res
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) if s[i:].startswith(word): track.append(word) backtrack(s,i + n) <!-- Here if I put track.remove(word), it can not go through the "aaaaaaa" case --> track.pop() backtrack(s, 0) return ans
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(s[len(word):], words, path+" "+ word) Check(s, wordDict, "") return(ans)
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]) backtrack(index + 1) path.pop() backtrack(0) return res
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 st = [(0, "")] while st: idx, string = st.pop() t = trie while idx < L: if s[idx] in t: t = t[s[idx]] else: break if '#' in t: if idx + 1 < L: st.append((idx+1, string + t['#'] + " ")) else: O.append(string + t['#']) idx += 1 return O
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): ans.append(" ".join(cur)) else: fsol(i) cur.pop(-1) pass # build len info h = {} for w in wordDict: h[len(w)] = h.get(len(w), set([])) h[len(w)].add(w) print("s: ", s) print("h: ", h) # build jump index sidx = [[] for _ in range(len(s))] for i in range(len(s)): for j in h: if s[i:i+j] in h[j]: sidx[i].append(i+j) print("index s: ", sidx) # find ans ans = [] cur = [] fsol(0) print("ans: ", ans) print("=" * 20) return ans print = lambda *a,**aa: ()
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 == "": output.append(candidate) return # Process demonstration of the following for loop: # candidate = "" <= 'cat'sanddog # candidate = "cat" <= 'sand'dog # candidate = "cat sand" <= dog # candidate = "cat sand dog" <= '' # candidate = "" <= 'cats'anddog # candidate = "cats" <= 'and'dog # candidate = "cats and" <= dog # candidate = "cats and dog" <= '' # In the for loop range needs to add one, otherwise you will miss one char when you use restString[:i]. # This for loop will keep checking if any prefix of restString was in dictionary. for i in range(len(restString)+1): if restString[:i] in wordDict: # This if block can avoid the extra space in the from of candidate answer. if candidate == "": backtracking(restString[i:], restString[:i]) else: backtracking(restString[i:], candidate+" "+restString[:i]) backtracking(s, "") return output """ Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"] Output: ["cats and dog","cat sand dog"] """ if __name__ == "__main__": s = "catsanddog" wordDict = ["cat","cats","and","sand","dog"] solution = Solution() print(f"s = {s}") print(f"wordDict = {wordDict}") print(f"wordBreak = {solution.wordBreak(s, wordDict)}")
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 == len(s): res.append(" ".join(path)) for i in range(idx+1, len(s)+1): if s[idx:i] in wordDict: q.append((i, path + [s[idx:i]])) return res
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 range(i, n): temp += s[j] if temp in wordDict: curr.append(temp) rec(j+1, curr) curr.pop() return wordDict = set(wordDict) rec() return res
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: n = ns[0] if len(splits): concat = splits[-1] + n check(ns[1:], splits[:-1]+[concat]) if splits[-1] in wordDict: check(ns[1:], splits+[n]) else: check(ns[1:], splits+[n]) check(s, []) return res
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): recursive(s[len(word):], current + word + ' ') recursive(s, '') return ret
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 w = '' for i in range(cur_ind, leng): w += s[i] if w in wordDict: path.append(w) bt(i+1, path) path.pop() bt(0, []) return [' '.join(x) for x in output]
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)])): for string in dp[idx+len(word)]: item = word + " " + string if string == "": item = word dp[idx].append(item) return dp[0]
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 opts: if s.startswith(opt): # prune the search space, since the length of wordDict is maximum 50. path = " ".join([path, opt]) backtrack(s[len(opt):], path) path = path[:-len(opt)-1] backtrack(s, "") return ans
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): if substring[:i] in wordDict: _dfs(path+[substring[:i]], substring[i:]) _dfs([], s) return ans
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 from behind for alternative start, unpack item = listOpened.pop() [words, tail] = item # validate if curr alternative reach end if tail == length: listClosed.append(words) # normal fetch, append word with sapce infront else: listOpened += [(words + " " + word, tail + len(word)) for word in lookup if raw[tail:].startswith(word)] return listClosed
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)) return while end <= len(str_): substr = s[start:end] if substr in wordDict: path.append(substr) split(str_, end, end + 1, path) path.pop() end += 1 split(s) return res
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(stack)) else: for word in wordDict: # O(W) currStack = copy.deepcopy(stack) index = s[n:].find(word) if index == 0: currStack.append(word) recursive(n + len(word), currStack) return recursive(0, []) # O(W^S) return ans
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)): index, spaces, word = queue.popleft() if len(word) - spaces == len(s): answer.append(word[:-1]) continue for i in range(index, len(s)+1): # T.C: O(n^2) for loop and subarray S.C: O(n) check = s[index:i] if check in wordDict: new_w = word + check + " " if new_w not in seen: queue.append((index+len(check), spaces+1, new_w)) seen.add(new_w) return answer
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 string reached, join # the stack with spaces if n == m: outputs.append(" ".join(stack)) else: # For each word for word in words: # make a copy of the current stack curr_stack = copy.deepcopy(stack) # find index of the word starting at index n index = s[n:].find(word) # If word is found if index == 0: # add the word to the stack curr_stack.append(word) # Call the recursive function with updated # index and updated stack recursive(n+len(word), curr_stack) return # ~recursive() # Call the function recursive() # return return outputs
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(len(s)): if s[:i+1] in word: ds.append(s[:i+1]) self.dfs(s[i+1:],word,ds) ds.pop() return
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 = collections.deque([]) q.append((s, '')) # We'll use word paths to avoid duplicates/track the paths we've already searched. seen = set() while q: rs, path = q.popleft() if not rs: res.append(path) continue for w in wg[rs[0]]: if rs.startswith(w): ns = rs[len(w):] np = path + ' ' + w if path else w if np not in seen: seen.add(np) q.append((ns, np)) return res
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: sub_paths = self.helper(s, wordDict, i+1, n) for sub_path in sub_paths: paths.append([cs]+sub_path) self.cache[idx] = paths return paths def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: self.cache = {} li = self.helper(s, wordDict, 0, len(s)) for i in range(len(li)): li[i] = " ".join(li[i]) return li
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] ret.append(j + 1 if pattern[j] == pattern[i] else j) return ret # KMP def search(T, P): p, j = partial(P), 0 ret = [0] * len(T) for i in range(len(T)): while j > 0 and T[i] != P[j]: j = p[j - 1] if T[i] == P[j]: j += 1 if j == len(P): ret[i-j+1] = 1 j = p[j - 1] return ret n = len(s) m = len(wordDict) rets = [] for w in wordDict: rets.append(search(s, w)) results = set() result = [] def backtrack(i): if i > n: return if i == n: results.add(" ".join(result)) return for j in range(m): if rets[j][i] == 1: result.append(wordDict[j]) backtrack(i+len(wordDict[j])) result.pop() backtrack(0) return list(results)
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: if sub_s[0] in dict_word: for word in dict_word[sub_s[0]]: if sub_s.startswith(word): new_sub_s = sub_s[len(word):] new_lst = lst + [word] if not new_sub_s: ans.append(" ".join(new_lst)) else: new_state.append([new_sub_s, new_lst]) state = new_state return ans
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: s1=s1+string+" " solve(j+1,j+1,s1) if j+1==len(s): t.append(s1[:len(s1)-1]) return else: s1=s2 solve(i,j+1,s1) else: if j+1==len(s): return else: solve(i,j+1,s1) solve(0,0,"") return t
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): prefix = s[i:j] if prefix in wordSet: combo.append(prefix) dfs(j) combo.pop() dfs(0) return res
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.defaultdict(list) for i in range(l+1): for j in range(i): if i - j < min_len: break if i - j > max_len: continue if dp[j] and s[j:i] in wordDict: dp[i] = True # we care how to arrive i, so we record j pos_dict[i].append(j) #print(dp, pos_dict, sep='\n') # the question is transfered to a graph question, use a recursion to solve it. # I am used to write recursion name as 'dfs', and the question here can indeed be regarded as dfs def dfs(pos): cur = [] for p in pos_dict[pos]: tmp = s[p:pos] cur = cur + [x + ' ' + tmp for x in dfs(p)] if p > 0 else [tmp] return cur return dfs(l) # the graph question can be solved by bfs, but I am not good at bfs # if dp[l] is False: return [] # stack = pos_dict[l] # while stack: # p = stack.pop()
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 * this is done by divider 4) create combinations of possibilities """ def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: if set(Counter(s).keys()) > set(Counter("".join(wordDict)).keys()): return [] if not s: return [] wordDict = set(wordDict) dp = [[(False,[])] * len(s) for _ in range(len(s))] for l in range(1,len(s)+1): for start in range(0,len(s)-l+1): end = start + l isTrue = False arr = [] if s[start:end] in wordDict: isTrue = True arr.append(s[start:end]) for divider in range(1,len(s[start:end])): if dp[start][divider-1][0] and dp[divider][end-1][0]: isTrue = True firstHalfArr = dp[start][divider-1][1] secondHalfArr = dp[divider][end-1][1] for first in firstHalfArr: for second in secondHalfArr: tempString = first + " " + second arr.append(tempString) dp[start][end-1] = (isTrue,arr) return list(set(dp[0][-1][1]))
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) dpDict[0] = [""] wordDict = set(wordDict) # implement Word Break I logic to see if the word break is possible at all for i in range(1, N+1): for loc in range(i): if not dpTable[loc]: continue word = s[loc:i] if word in wordDict: dpTable[i] = True if not dpTable[-1]: return [] # implement the logic for Word Break II. Here we use a defaultdict to store the broken words. for i in range(1, N+1): for loc in range(i): if not dpDict[loc]: continue # if this is False, then it means that the word until this index is not present in the wordDict. word = s[loc:i] if word in wordDict: dpDict[i].extend(curr + " " + word if curr else word for curr in dpDict[loc]) # create a sentence. return dpDict[N] # return all possible sentences.
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(s)+1): if s[:i] in wd: helper(s[i:],dic,path+[s[:i]]) else: dic.add(s[:i]) wd = set(wordDict) dic = set() helper(s,dic,[]) return self.res
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 fast_ref = fast_ref.next.next if slow_ref == fast_ref: return True return False If you get it please Upvote.
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. slowptr = slowptr.next fastptr = fastptr.next.next # If both the pointers meet at any point, then the cycle is present and return true... if slowptr == fastptr: return 1 return 0
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 step. slowptr = slowptr.next fastptr = fastptr.next.next # If both the pointers meet at any point, then the cycle is present and return true... if slowptr == fastptr: return 1 return 0
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 True return False
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: return True return False
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: nodesSeen.add(head) head = head.next # move on to next node return False
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 == new_node: return True
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 = head.next return False
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 pointer while fast and fast.next: slow = slow.next #Traversing by one node at each iteration fast = fast.next.next # Traversing by two nodes at each iteration if fast == slow: # If there's a cycle then at one point in the iteration the next pointer of the fast pointer will direct us towards the node at which the slow pointer is pointing. return True # So we'll simply return true since there's a cycle return False # If the next pointer of the fast is Null then it'll break the loop and return False
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 slow == fast: return True return False # No cycle found
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.next pre.next = addr
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 fast = fast.next.next else: return False
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 not None and id(slow) == id(fast): return True return False
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.next return False
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 linked list have less than one node, it cannot have any cycle, while head: #traverse the node if head.val == 'd': #if the node's value is 'd' that means we've already seen this node return True else: head.val = 'd' #otherwise update the node value to mark it as visited head = head.next return False else: return False
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