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/valid-palindrome/discuss/1714544/Two-pointer-Python-solution-O(1)-space-with-comments
class Solution: def isPalindrome(self, s: str) -> bool: # Define two pointers starting at the end and beginning of the string left = 0 right = len(s) - 1 # Iterate and increment the pointers towards the middle. # Stop when left == right (odd len(s)) or left > right (even len(s)). while left < right: left_val = s[left].lower() l_is_alnum = left_val.isalnum() right_val = s[right].lower() r_is_alnum = right_val.isalnum() if l_is_alnum and r_is_alnum: if left_val != right_val: return False left += 1 right -= 1 continue # if both aren't alnums, increment the pointer only if it's not alnum if not l_is_alnum: left += 1 if not r_is_alnum: right -= 1 return True
valid-palindrome
Two pointer Python solution, O(1) space with comments
nat_5t34
1
147
valid palindrome
125
0.437
Easy
1,400
https://leetcode.com/problems/valid-palindrome/discuss/1585786/Python-Easy-Solution-or-O(n)-Approach
class Solution: def isPalindrome(self, s: str) -> bool: start = 0 s = s.lower() end = len(s)-1 while start < end: if not s[start].isalnum(): start += 1 continue if not s[end].isalnum(): end -= 1 continue if s[start] != s[end]: return False start += 1 end -= 1 return True
valid-palindrome
Python Easy Solution | O(n) Approach
leet_satyam
1
186
valid palindrome
125
0.437
Easy
1,401
https://leetcode.com/problems/valid-palindrome/discuss/1256371/Python3-simple-solution-by-two-approaches
class Solution: def isPalindrome(self, s: str) -> bool: x = '' for i in s: i = i.lower() if i.isalnum(): x += i return x == x[::-1]
valid-palindrome
Python3 simple solution by two approaches
EklavyaJoshi
1
96
valid palindrome
125
0.437
Easy
1,402
https://leetcode.com/problems/valid-palindrome/discuss/1256371/Python3-simple-solution-by-two-approaches
class Solution: def isPalindrome(self, s: str) -> bool: i = 0 j = len(s)-1 x = '' y = '' while i<=j: if x == '': if s[i].lower().isalnum(): x = s[i].lower() else: i += 1 if y == '': if s[j].lower().isalnum(): y = s[j].lower() else: j -= 1 if x != '' and y != '': if x != y: return False x = '' y = '' i += 1 j -= 1 return True
valid-palindrome
Python3 simple solution by two approaches
EklavyaJoshi
1
96
valid palindrome
125
0.437
Easy
1,403
https://leetcode.com/problems/valid-palindrome/discuss/1245962/Python3-95-time-with-list-comprehension-explained
class Solution: def isPalindrome(self, s: str) -> bool: s = [c for c in s.lower() if c.isalnum()] return s == s[::-1]
valid-palindrome
Python3 95% time, with list comprehension, explained
albezx0
1
151
valid palindrome
125
0.437
Easy
1,404
https://leetcode.com/problems/valid-palindrome/discuss/1074210/Simplest-Solution
class Solution: def isPalindrome(self, s: str) -> bool: y=''.join(c for c in s if c.isalnum()) y=y.lower() if(y==y[::-1]): return True else: return False
valid-palindrome
Simplest Solution
parasgarg395
1
129
valid palindrome
125
0.437
Easy
1,405
https://leetcode.com/problems/valid-palindrome/discuss/958812/Python-2-liner-easy-solution-with-list-comprehension!
class Solution: def isPalindrome(self, s: str) -> bool: if s == '': return True new = ''.join([x.lower() for x in s if x.isalnum()]) return new == new[::-1]
valid-palindrome
Python 2-liner, easy solution with list comprehension!
yahoo123pl
1
157
valid palindrome
125
0.437
Easy
1,406
https://leetcode.com/problems/valid-palindrome/discuss/902617/Python3-solution(Both-O(n)-space-complexity-and-O(1)-space-complexity)
class Solution: def isPalindrome(self, s: str) -> bool: if not s: return True new_s=[i for i in s.lower() if i.isalnum()] reverse=new_s[::-1] return reverse==new_s #O(1) solution class Solution: def isPalindrome(self, s: str) -> bool: if not s: return True left, right = 0, len(s)-1 while left<right: if not s[left].isalnum(): left+=1 continue if not s[right].isalnum(): right-=1 continue if s[left].lower() != s[right].lower(): return False left+=1 right-=1 return True
valid-palindrome
Python3 solution(Both O(n) space complexity and O(1) space complexity)
iammyashh
1
140
valid palindrome
125
0.437
Easy
1,407
https://leetcode.com/problems/valid-palindrome/discuss/770390/Python-or-Easy-Solution-for-beginners-with-comments
class Solution(object): def isPalindrome(self, s): s = s.lower() #Converts string to lower x = '' for i in s: if i.isalnum(): # Checks if string is alphanumeric x+=(i) return x==x[::-1]
valid-palindrome
Python | Easy Solution for beginners with comments
rachitsxn292
1
189
valid palindrome
125
0.437
Easy
1,408
https://leetcode.com/problems/valid-palindrome/discuss/695623/Python3-two-approaches
class Solution: def isPalindrome(self, s: str) -> bool: lo, hi = 0, len(s)-1 while lo < hi: if not s[lo].isalnum(): lo += 1 elif not s[hi].isalnum(): hi -= 1 elif s[lo].lower() != s[hi].lower(): return False else: lo, hi = lo+1, hi-1 return True
valid-palindrome
[Python3] two approaches
ye15
1
123
valid palindrome
125
0.437
Easy
1,409
https://leetcode.com/problems/valid-palindrome/discuss/695623/Python3-two-approaches
class Solution: def isPalindrome(self, s: str) -> bool: s = "".join(c for c in s.lower() if c.isalnum()) return s == s[::-1]
valid-palindrome
[Python3] two approaches
ye15
1
123
valid palindrome
125
0.437
Easy
1,410
https://leetcode.com/problems/valid-palindrome/discuss/695623/Python3-two-approaches
class Solution: def isPalindrome(self, s: str) -> bool: return (lambda x: x == x[::-1])([c for c in s.lower() if c.isalnum()])
valid-palindrome
[Python3] two approaches
ye15
1
123
valid palindrome
125
0.437
Easy
1,411
https://leetcode.com/problems/valid-palindrome/discuss/585988/Easy-Python-Solution
class Solution: def isPalindrome(self, s: str) -> bool: if len(s)==1: return True k="" for i in range(len(s)): if s[i].isalnum(): k+=s[i].lower() print(k) if k=="": return True if k==k[::-1]: return True if len(k)==1: return False return False
valid-palindrome
Easy Python Solution
Ayu-99
1
82
valid palindrome
125
0.437
Easy
1,412
https://leetcode.com/problems/valid-palindrome/discuss/2844950/Easy-understand-but-use-more-space
class Solution: def isPalindrome(self, s: str) -> bool: # Format the string temp = [letter.lower() for letter in s if letter.isalnum()] # Tow pointer to check left = 0 right = len(temp) - 1 while left <= right: if temp[left] != temp[right]: return False left += 1 right -= 1 return True
valid-palindrome
Easy understand but use more space
JennyLu
0
3
valid palindrome
125
0.437
Easy
1,413
https://leetcode.com/problems/valid-palindrome/discuss/2843588/Easy-Solution-Using-Alnum-Python
class Solution: def isPalindrome(self, s: str) -> bool: lowerS = s.lower() old = [" ".join(i for i in lowerS if i.isalnum())] if "".join(old) == "".join(old[0][::-1]): return True else: return False
valid-palindrome
Easy Solution - Using Alnum - Python
bharatvishwa
0
1
valid palindrome
125
0.437
Easy
1,414
https://leetcode.com/problems/valid-palindrome/discuss/2841854/Python-or-Two-pointer-solution.
class Solution: def isPalindrome(self, s: str) -> bool: l,r = 0, len(s)-1 while l<r: while s[l].isalnum() == False and l<r: l +=1 while s[r].isalnum() == False and l<r: r -=1 if s[l].lower() != s[r].lower(): return False l +=1 r -=1 return True
valid-palindrome
Python | Two pointer solution.
float_boat
0
1
valid palindrome
125
0.437
Easy
1,415
https://leetcode.com/problems/valid-palindrome/discuss/2841821/Python-or-Two-pointer-solution
class Solution: def isPalindrome(self, s: str) -> bool: Snew = "" for char in s: if char.isalnum(): Snew += char.lower() l,r = 0, len(Snew)-1 while l<r: if Snew[l] != Snew[r]: return False l +=1 r -=1 return True
valid-palindrome
Python | Two pointer solution
float_boat
0
1
valid palindrome
125
0.437
Easy
1,416
https://leetcode.com/problems/valid-palindrome/discuss/2841801/Python-solution-or-Reverse-the-string
class Solution: def isPalindrome(self, s: str) -> bool: Snew = "" for char in s: if char.isalnum(): Snew += char.lower() return Snew == Snew[::-1]
valid-palindrome
Python solution | Reverse the string
float_boat
0
1
valid palindrome
125
0.437
Easy
1,417
https://leetcode.com/problems/word-ladder-ii/discuss/2422401/46ms-Python-97-Faster-Working-Multiple-solutions-95-memory-efficient-solution
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: d = defaultdict(list) for word in wordList: for i in range(len(word)): d[word[:i]+"*"+word[i+1:]].append(word) if endWord not in wordList: return [] visited1 = defaultdict(list) q1 = deque([beginWord]) visited1[beginWord] = [] visited2 = defaultdict(list) q2 = deque([endWord]) visited2[endWord] = [] ans = [] def dfs(v, visited, path, paths): path.append(v) if not visited[v]: if visited is visited1: paths.append(path[::-1]) else: paths.append(path[:]) for u in visited[v]: dfs(u, visited, path, paths) path.pop() def bfs(q, visited1, visited2, frombegin): level_visited = defaultdict(list) for _ in range(len(q)): u = q.popleft() for i in range(len(u)): for v in d[u[:i]+"*"+u[i+1:]]: if v in visited2: paths1 = [] paths2 = [] dfs(u, visited1, [], paths1) dfs(v, visited2, [], paths2) if not frombegin: paths1, paths2 = paths2, paths1 for a in paths1: for b in paths2: ans.append(a+b) elif v not in visited1: if v not in level_visited: q.append(v) level_visited[v].append(u) visited1.update(level_visited) while q1 and q2 and not ans: if len(q1) <= len(q2): bfs(q1, visited1, visited2, True) else: bfs(q2, visited2, visited1, False) return ans
word-ladder-ii
46ms Python 97 Faster Working Multiple solutions 95% memory efficient solution
anuvabtest
35
2,800
word ladder ii
126
0.276
Hard
1,418
https://leetcode.com/problems/word-ladder-ii/discuss/2422401/46ms-Python-97-Faster-Working-Multiple-solutions-95-memory-efficient-solution
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: res = [] edge = collections.defaultdict(set) wordList = set(wordList) for word in wordList: for i in range(len(word)): edge[word[:i] +'*'+word[i+1:]].add(word) bfsedge = {} def bfs(): minl = 0 queue = set() queue.add(beginWord) while queue: next_queue = set() for word in queue: if word in wordList: wordList.remove(word) bfsedge[minl] = collections.defaultdict(set) for word in queue: if word == endWord: return minl for i in range(len(word)): for w in edge[word[:i]+'*'+word[i+1:]]: if w in wordList: next_queue.add(w) bfsedge[minl][w].add(word) queue = next_queue minl += 1 return minl def dfs(seq, endWord): if seq[-1] == endWord: res.append(seq.copy()) return for nextWord in bfsedge[minl-len(seq)][seq[-1]]: if nextWord not in seq: dfs(seq+[nextWord], endWord) minl = bfs() dfs([endWord], beginWord) # reverse the sequence for sq in res: sq.reverse() return res
word-ladder-ii
46ms Python 97 Faster Working Multiple solutions 95% memory efficient solution
anuvabtest
35
2,800
word ladder ii
126
0.276
Hard
1,419
https://leetcode.com/problems/word-ladder-ii/discuss/1890299/Python-BFS%2BDFS-beats100
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: prefix_d = defaultdict(list) for word in wordList: for i in range(0,len(word)): prefix_d[word[0:i]+"*"+word[i+1:]].append(word) order = {beginWord: []} queue = deque([beginWord]) temp_q = deque() go_on = True end_list = [] while queue and go_on: # There is no node even added to temp_q temp_d = {} while queue: # Pop every node on this level cur = queue.popleft() for i in range(0, len(cur)): for j in prefix_d[cur[0:i]+"*"+cur[i+1:]]: if j == endWord: end_list.append(j) go_on = False if j not in order: if j not in temp_d: temp_d[j] = [cur] temp_q.append(j) else: temp_d[j].append(cur) queue = temp_q temp_q = deque() order.update(temp_d) ret = [] # DFS to restore the paths def dfs(path, node): path = path + [node] # add the node(Deepcopy) if order[node] == []: ret.append(list(path[::-1])) return for i in order[node]: dfs(path, i) if endWord in order: dfs([], endWord) else: return [] return ret
word-ladder-ii
Python BFS+DFS beats100%
juehuil
4
335
word ladder ii
126
0.276
Hard
1,420
https://leetcode.com/problems/word-ladder-ii/discuss/2262529/python3-bidirectional-BFS-or-does-not-TLE-in-July-2022
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: list[str]) -> list[list[str]]: if endWord not in wordList: return [] lw = len(beginWord) # build variants list/graph variants: dict[str, list[str]] = defaultdict(list) for word in wordList: for i in range(lw): key = word[:i] + '*' + word[i + 1:] variants[key].append(word) # bi-bfs to build the graph of paths q1: deque[str] = deque([beginWord]) # queue starting from beginWord q2: deque[str] = deque([endWord]) # queue from the back with endWord v1: set[str] = {beginWord} # visited nodes starting from beginWord v2: set[str] = {endWord} # visited nodes starting from endWord found: bool = False graph: dict[str, set[str]] = defaultdict(set) def edge(src: str, dest: str, forward: bool) -> None: if forward: graph[src].add(dest) else: graph[dest].add(src) def bfs(q: deque[str], seen: set[str], opposing: set[str], forward: bool) -> None: nonlocal found lq = len(q) frontier: set[str] = set() for _ in range(lq): curr = q.popleft() for i in range(lw): key = curr[:i] + '*' + curr[i + 1:] for neigh in variants[key]: if neigh in opposing: edge(curr, neigh, forward) found = True elif neigh not in seen or neigh in frontier: q.append(neigh) edge(curr, neigh, forward) seen.add(neigh) frontier.add(neigh) while q1 and q2 and not found: if len(q1) <= len(q2): bfs(q1, v1, v2, forward=True) else: bfs(q2, v2, v1, forward=False) # traverse paths with backtracking all_paths: list[list[str]] = [] path: list[str] = [beginWord] def find_paths(curr: str) -> None: if curr == endWord: all_paths.append(path.copy()) return for neigh in graph[curr]: path.append(neigh) find_paths(neigh) path.pop() find_paths(beginWord) return all_paths
word-ladder-ii
[python3] bidirectional BFS | does not TLE in July 2022
parmenio
3
532
word ladder ii
126
0.276
Hard
1,421
https://leetcode.com/problems/word-ladder-ii/discuss/1996030/Python-BFS-code-with-explanation
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: # check if endword is in wordlist if endWord not in wordList: return [] # insert a new value for the first time, the default value is an empty list nei = collections.defaultdict(list) wordList.append(beginWord) # build an adjacent list for word in wordList: # iterate each word for j in range(len(word)): # find patterns of each word pattern = word[:j] + "*" + word[j+1:] # replace the char in j position with * nei[pattern].append(word) # add the word in the dict # bfs visited = set([beginWord]) # don't visit the same word again q = deque() q.append((beginWord,[beginWord])) res = [] wordList = set(wordList) while q: # iterate layer for i in range(len(q)): word, seq = q.popleft() if word == endWord: res.append(seq) # go with it's neighbors for j in range(len(word)): pattern = word[:j] + "*" + word[j+1:] # check the neighbors for neiWord in nei[pattern]: # we don't check the word itself if neiWord in wordList: visited.add(neiWord) q.append((neiWord, seq+[neiWord])) wordList -= visited return res
word-ladder-ii
Python BFS code with explanation
JinlingXING
3
391
word ladder ii
126
0.276
Hard
1,422
https://leetcode.com/problems/word-ladder-ii/discuss/2422963/BFS-%2B-DFS-%2B-Memo
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: word_set = set(wordList) if endWord not in word_set: return [] # bfs build graph + dfs memo graph = defaultdict(set) queue = Deque([beginWord]) step = 0 min_step = -1 visited = set() while len(queue): size = len(queue) step += 1 for _ in range(size): cur = queue.popleft() if cur in visited: continue visited.add(cur) for i in range(len(cur)): c = cur[i] for j in range(26): n_c = chr(ord('a') + j) if n_c == c: continue n_s = cur[0:i] + n_c + cur[i+1:] if n_s in word_set: graph[n_s].add(cur) graph[cur].add(n_s) queue.append(n_s) if n_s == endWord and min_step == -1: min_step = step @lru_cache(None) def dfs(cur, step): nonlocal graph if step > min_step: return [] if cur == endWord: return [[endWord]] res = [] for nxt in graph[cur]: tmp = dfs(nxt,step+1) res += [[cur] + x for x in tmp] # print(res) return res return dfs(beginWord, 0)
word-ladder-ii
BFS + DFS + Memo
Yan_Yichun
2
204
word ladder ii
126
0.276
Hard
1,423
https://leetcode.com/problems/word-ladder-ii/discuss/2207679/14.2MB260mspython3
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList): def similiar(l1,l2): counter = 0 for i in range(len(l1)): if l1[i] != l2[i]: counter += 1 if counter > 1: break if counter == 1: return True if beginWord not in wordList: wordList.append(beginWord) if endWord not in wordList: return [] else: wordList.remove(endWord) # 首先逐级分层: possible = [endWord] layer = [possible] rest = wordList newpossible = [1] while newpossible != []: newpossible = [] newrest = rest.copy() for i in possible: for j in newrest: if similiar(i,j): if j not in newpossible: newpossible.append(j) rest.remove(j) possible = newpossible layer.append(newpossible) print(layer) # 定位 counter = 0 for i in layer: if beginWord not in i: counter += 1 else: break # 分层筛查 def recursion(layer,n,temp,result,beginWord): for i in layer[n - 1]: if similiar(i,temp[-1]): newtemp = temp + [i] if newtemp[-1] == endWord: result.append(newtemp) else: recursion(layer,n - 1,newtemp,result,beginWord) result = [] recursion(layer,counter,[beginWord],result,beginWord) return result
word-ladder-ii
14.2MB,260ms,python3
Bin123
2
124
word ladder ii
126
0.276
Hard
1,424
https://leetcode.com/problems/word-ladder-ii/discuss/1360434/Python-Easy-BFS-solution
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: "Edge Case checking" if endWord not in wordList: return [] size = len(beginWord) "create llokup got all the possible wordpatters" lookup = defaultdict(list) for word in wordList: for i in range(size): lookup[word[:i] + "*" + word[i+1:]].append(word) cur_len = 9999 ans = [] "enter the first element in the queue" queue = collections.deque([[beginWord, 1,[beginWord]]]) visited = {beginWord: True} while(queue): currWord, pathLength,words_till_now = queue.popleft() """ instead of marking an elemnt vistied , when we insert it in the queue, we mark it as visited only when we pop and element this way , same word can be used by other curWords <ex :> "red" "tax" ["ted","tex","red","tax","tad","den","rex","pee"] and we make sure that element can not be used again """ visited[currWord] = True """ run a for loop for all values for all the possible patterns for the popped word """ for i in range(size): possibleWordPattern = currWord[:i] + "*" + currWord[i+1:] for word in lookup[possibleWordPattern]: if(currWord == word): continue """ if the word for the possibleWordPattern key matches with the end word we add it to the ans list """ if(word == endWord): if cur_len == pathLength + 1: ans.append(words_till_now+[word]) elif cur_len > pathLength + 1: ans = [words_till_now+[word]] cur_len = pathLength + 1 if(word not in visited): queue.append([word, pathLength + 1,words_till_now+[word]]) return ans
word-ladder-ii
Python , Easy BFS solution
shankha117
2
150
word ladder ii
126
0.276
Hard
1,425
https://leetcode.com/problems/word-ladder-ii/discuss/991528/Python-BFS-%2B-DFS
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: def build_graph() -> dict: graph = defaultdict(list) for word in wordList: for i in range(N): w = word[:i] + "*" + word[i+1:] graph[w].append(word) return graph def neighbors(word: str) -> str: for i in range(N): for w in graph[word[:i] + "*" + word[i+1:]]: yield w def bfs(start: str) -> int: queue = deque() queue.append(start) distances[start] = 0 while queue: level = len(queue) for _ in range(level): word= queue.popleft() pathlen = distances[word] if word == endWord: return pathlen for neighbor in neighbors(word): if neighbor not in distances: distances[neighbor] = pathlen + 1 queue.append(neighbor) return 0 def dfs(start: str, path: List[str]) -> None: if start == endWord: ans.append(list(path) + [endWord]) return path.append(start) for neighbor in neighbors(start): if distances[neighbor] == distances[start] + 1: dfs(neighbor, path) path.pop() ans = list() N = len(beginWord) graph = build_graph() distances = defaultdict(int) min_path_len = bfs(beginWord) if min_path_len == 0: return ans dfs(beginWord, list()) return ans
word-ladder-ii
Python BFS + DFS
alexvlis_d
2
348
word ladder ii
126
0.276
Hard
1,426
https://leetcode.com/problems/word-ladder-ii/discuss/704422/Python3-simple-and-two-end-bfs-(98.6)
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: graph = dict() for word in wordList: for i in range(len(word)): graph.setdefault(word[:i] + "*" + word[i+1:], []).append(word) ans = [] queue = {beginWord: [[beginWord]]} seen = {beginWord} while queue and not ans: temp = dict() for word, seq in queue.items(): for i in range(len(word)): for node in graph.get(word[:i] + "*" + word[i+1:], []): if node == endWord: ans.extend([x + [node] for x in seq]) if node in seen: continue for x in seq: temp.setdefault(node, []).append(x + [node]) seen |= set(temp.keys()) #has to be updated level-by-level queue = temp return ans
word-ladder-ii
[Python3] simple & two-end bfs (98.6%)
ye15
2
393
word ladder ii
126
0.276
Hard
1,427
https://leetcode.com/problems/word-ladder-ii/discuss/704422/Python3-simple-and-two-end-bfs-(98.6)
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: if endWord not in wordList: return [] graph = dict() for word in wordList: for i in range(len(word)): graph.setdefault(word[:i] + "*" + word[i+1:], []).append(word) ans = [] front0, front1 = {beginWord: [[beginWord]]}, {endWord:[[endWord]]} #word &amp; sequences ending in word seen = {beginWord, endWord} reverse = False while front0 and front1 and not ans: if len(front0) > len(front1): front0, front1, reverse = front1, front0, not reverse temp = dict() for word, seq in front0.items(): for i in range(len(word)): for node in graph.get(word[:i] + "*" + word[i+1:], []): if node in front1: ans.extend([y + x[::-1] if reverse else x + y[::-1] for x in seq for y in front1[node]]) if node in seen: continue for x in seq: temp.setdefault(node, []).append(x + [node]) seen |= set(temp.keys()) #has to be updated level-by-level front0 = temp return ans
word-ladder-ii
[Python3] simple & two-end bfs (98.6%)
ye15
2
393
word ladder ii
126
0.276
Hard
1,428
https://leetcode.com/problems/word-ladder-ii/discuss/704422/Python3-simple-and-two-end-bfs-(98.6)
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: if endWord not in wordList: return [] # edge case graph = {} for word in wordList: for i in range(len(word)): key = word[:i] + "*" + word[i+1:] graph.setdefault(key, []).append(word) queue = [beginWord] prev = {beginWord: set()} while queue: qq = [] pp = {} for w in queue: for i in range(len(w)): key = w[:i] + "*" + w[i+1:] for ww in graph.get(key, []): if ww not in prev: qq.append(ww) pp.setdefault(ww, set()).add(w) queue = qq prev.update(pp) if endWord in prev: break if endWord not in prev: return [] ans = [[endWord]] while prev[ans[0][-1]]: newq = [] for seq in ans: w = seq[-1] for i, ww in enumerate(prev[w]): newq.append(seq + [ww]) ans = newq return [x[::-1] for x in ans]
word-ladder-ii
[Python3] simple & two-end bfs (98.6%)
ye15
2
393
word ladder ii
126
0.276
Hard
1,429
https://leetcode.com/problems/word-ladder-ii/discuss/1200831/Python-bfs-%2B-dfs-faster-than-85%2B
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: # bfs with memory wordDict = set(wordList) if endWord not in wordDict: return [] l, s, used, flag, parent = len(beginWord), {beginWord}, set(), True, defaultdict(list) while s and flag: tmp = set() used = used.union(s) for w in s: new_word = [w[:i] + x + w[i+1:] for x in string.ascii_lowercase for i in range(l)] for x in new_word: if x == endWord: flag = False if x in wordDict and x not in used: tmp.add(x) parent[w].append(x) if not tmp: return [] s = tmp # dfs ans = [] def dfs(cur, pos): if pos == endWord: ans.append(cur.copy()) return for p in parent[pos]: cur.append(p) dfs(cur, p) cur.pop() dfs([beginWord], beginWord) return ans
word-ladder-ii
Python bfs + dfs, faster than 85+%
dustlihy
1
394
word ladder ii
126
0.276
Hard
1,430
https://leetcode.com/problems/word-ladder-ii/discuss/2706979/One-small-change-to-word-ladder-1
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: letters = "abcdefghijklmnopqrstuvwxyz" wordList = set(wordList) queue = deque() queue.append([beginWord]) if beginWord in wordList: wordList.remove(beginWord) res = [] while queue: qlen = len(queue) new_words = set() for _ in range(qlen): word_chain = queue.popleft() current_word = word_chain[-1] if current_word == endWord: res.append(word_chain) continue for i,ch in enumerate(current_word): for new_ch in letters: if new_ch == ch: continue new_word = current_word[:i] + new_ch + current_word[i+1:] if new_word in wordList: new_words.add(new_word) word_chain.append(new_word) queue.append(word_chain[:]) word_chain.pop() for new_word in new_words: wordList.remove(new_word) return res
word-ladder-ii
One small change to word ladder 1
shriyansnaik
0
22
word ladder ii
126
0.276
Hard
1,431
https://leetcode.com/problems/word-ladder-ii/discuss/2640330/Solution-only-work-for-3236-cases
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: if endWord not in wordList: return [] n, l = len(wordList), len(beginWord) # construct adj adj = collections.defaultdict(list) for w in wordList: for i in range(l): key = w[:i] + '*' + w[i + 1:] adj[key].append(w) # BFS que = collections.deque([beginWord]) parents = collections.defaultdict(set) visited = set() while que: ll = len(que) tovisit = set() for _ in range(ll): s= que.popleft() for i in range(l): key = s[: i] + "*" + s[i + 1:] for w in adj[key]: if w not in visited: tovisit.add(w) que.append(w) parents[w].add(s) if w == endWord: parents[w].add(s) visited.update(tovisit) if endWord in visited: break def construct_path(word, path): if word == beginWord: ans.append(path[::-1]) return for p in parents[word]: construct_path(p, path + [p]) ans = [] construct_path(endWord, [endWord]) return ans
word-ladder-ii
Solution only work for 32/36 cases
YYYami
0
26
word ladder ii
126
0.276
Hard
1,432
https://leetcode.com/problems/word-ladder-ii/discuss/2423508/O(n)-with-bfs-%2B-building-tries-%2B-back-track-same-level-nodes
class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: """ cog + log + + dog """ def ppath(p): if d.get(p): path.append(p) if d[p][1]==-1: print(path[::-1]) ans.append([v for v in path[::-1]]) else: for v in d: if d[v][0]+1==d[p][0] and sum([1 for i in range(k) if v[i]!=p[i]])<=1: ppath(v) path.pop(-1) pass n, k = len(wordList), len(wordList[0]) # build tries tries = {} for i in range(n): for j in range(k): w = wordList[i][:j] + "?" + wordList[i][j+1:] tries[w] = tries.get(w, []) tries[w].append(wordList[i]) pass print(beginWord, endWord) print("[build] tries: ", tries) # bfs (only closing node after 1-level) q = [beginWord] d = {q[0]: (0, -1)} flag = False while len(q)>0: u = q.pop(0) for j in range(k): w = u[:j] + "?" + u[j+1:] for v in tries.get(w, []): # for all v adjacent u if not d.get(v): d[v] = (d[u][0]+1, u) q.append(v) if v==endWord: break if d.get(endWord): break if d.get(endWord): break print("\n[bfs] d: ", d) print("\npath: ") path = [] ans = [] ppath(endWord) print("=" * 20) return ans print = lambda *a,**aa: ()
word-ladder-ii
O(n) with bfs + building tries + back-track same-level nodes
dntai
0
89
word ladder ii
126
0.276
Hard
1,433
https://leetcode.com/problems/word-ladder/discuss/1332551/Elegant-Python-Iterative-BFS
class Solution(object): def ladderLength(self, beginWord, endWord, wordList): graph = defaultdict(list) for word in wordList: for index in range(len(beginWord)): graph[word[:index] + "_" + word[index+1:]].append(word) queue = deque() queue.append((beginWord, 1)) visited = set() while queue: current_node, current_level = queue.popleft() if current_node == endWord: return current_level for index in range(len(beginWord)): node = current_node[:index] + "_" + current_node[index+1:] for neighbour in graph[node]: if neighbour not in visited: queue.append((neighbour, current_level + 1)) visited.add(neighbour) graph[node] = [] return 0
word-ladder
Elegant Python Iterative BFS
soma28
4
366
word ladder
127
0.368
Hard
1,434
https://leetcode.com/problems/word-ladder/discuss/2506114/python-solution-or-BFS-or-faster-than-94-solutions
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 nei = collections.defaultdict(list) wordList.append(beginWord) for word in wordList: for j in range(len(word)): pattern = word[:j] + "*" + word[j + 1:] nei[pattern].append(word) visit = set([beginWord]) q = deque([beginWord]) res = 1 while q: for i in range(len(q)): word = q.popleft() if word == endWord: return res for j in range(len(word)): pattern = word[:j] + "*" + word[j + 1:] for neiWord in nei[pattern]: if neiWord not in visit: visit.add(neiWord) q.append(neiWord) res += 1 return 0
word-ladder
python solution | BFS | faster than 94% solutions
nikhitamore
2
225
word ladder
127
0.368
Hard
1,435
https://leetcode.com/problems/word-ladder/discuss/1604369/Python-Simple-BFS
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 q = [(beginWord, 1)] wordList = set(wordList) # TLE if you don't convert into a set seen = set([beginWord]) while q: currWord, level = q.pop(0) for i in range(len(currWord)): for j in range(97,123): newWord = currWord[:i] + chr(j) + currWord[i+1:] if newWord == endWord: return level + 1 if newWord in wordList and newWord not in seen: seen.add(newWord) q.append((newWord, level+1)) return 0 ```
word-ladder
Python Simple BFS
ranasaani
2
282
word ladder
127
0.368
Hard
1,436
https://leetcode.com/problems/word-ladder/discuss/1200737/Python-BFS-with-pruning-faster-than-95%2B
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: # bfs wordList = set(wordList) if endWord not in wordList: return 0 l = len(beginWord) begin_queue, end_queue = deque([beginWord]), deque([endWord]) level = 0 begin_used, end_used = set(), set() while begin_queue and end_queue: level += 1 for _ in range(len(begin_queue)): # level order begin_word = begin_queue.popleft() begin_used.add(begin_word) for i in range(l): for c in string.ascii_lowercase[:26]: w = begin_word[:i] + c + begin_word[i+1:] if w in end_queue: return level * 2 if w in wordList and w not in begin_used: begin_queue.append(w) for _ in range(len(end_queue)): end_word = end_queue.popleft() end_used.add(end_word) for i in range(l): for c in string.ascii_lowercase[:26]: w = end_word[:i] + c + end_word[i+1:] if w in begin_queue: return level * 2 + 1 if w in wordList and w not in end_used: end_queue.append(w) return 0
word-ladder
Python BFS with pruning, faster than 95+%
dustlihy
2
367
word ladder
127
0.368
Hard
1,437
https://leetcode.com/problems/word-ladder/discuss/1200737/Python-BFS-with-pruning-faster-than-95%2B
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: # bfs wordList = set(wordList) if endWord not in wordList: return 0 l = len(beginWord) begin_queue, end_queue = deque([beginWord]), deque([endWord]) level = 0 while begin_queue and end_queue: level += 1 for _ in range(len(begin_queue)): # level order begin_word = begin_queue.popleft() for i in range(l): for c in string.ascii_lowercase[:26]: w = begin_word[:i] + c + begin_word[i+1:] if w in end_queue: return level * 2 if w in wordList: begin_queue.append(w) wordList.remove(w) for _ in range(len(end_queue)): end_word = end_queue.popleft() for i in range(l): for c in string.ascii_lowercase[:26]: w = end_word[:i] + c + end_word[i+1:] if w in begin_queue: return level * 2 + 1 if w in wordList: end_queue.append(w) wordList.remove(w) return 0
word-ladder
Python BFS with pruning, faster than 95+%
dustlihy
2
367
word ladder
127
0.368
Hard
1,438
https://leetcode.com/problems/word-ladder/discuss/1200737/Python-BFS-with-pruning-faster-than-95%2B
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: # bfs wordList = set(wordList) if endWord not in wordList: return 0 l = len(beginWord) begin_queue, end_queue = deque([beginWord]), deque([endWord]) level = 0 while begin_queue and end_queue: level += 1 if len(begin_queue) > len(end_queue): begin_queue, end_queue = end_queue, begin_queue for _ in range(len(begin_queue)): # level order begin_word = begin_queue.popleft() for i in range(l): for c in string.ascii_lowercase[:26]: w = begin_word[:i] + c + begin_word[i+1:] if w in end_queue: return level * 2 if w in wordList: begin_queue.append(w) wordList.remove(w) if len(begin_queue) < len(end_queue): begin_queue, end_queue = end_queue, begin_queue for _ in range(len(end_queue)): end_word = end_queue.popleft() for i in range(l): for c in string.ascii_lowercase[:26]: w = end_word[:i] + c + end_word[i+1:] if w in begin_queue: return level * 2 + 1 if w in wordList: end_queue.append(w) wordList.remove(w) return 0
word-ladder
Python BFS with pruning, faster than 95+%
dustlihy
2
367
word ladder
127
0.368
Hard
1,439
https://leetcode.com/problems/word-ladder/discuss/1200737/Python-BFS-with-pruning-faster-than-95%2B
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: # bfs wordList = set(wordList) if endWord not in wordList: return 0 l, s1, s2 = len(beginWord), {beginWord}, {endWord} wordList.remove(endWord) level = 0 while s1 and s2: level += 1 s = set() if len(s1) > len(s2): s1, s2 = s2, s1 for w1 in s1: # level order new_words = [w1[:i] + t + w1[i+1:] for t in string.ascii_lowercase for i in range(l)] for w in new_words: if w in s2: return level * 2 if w not in wordList: continue s.add(w) wordList.remove(w) s1, s = s, set() if len(s2) > len(s1): s1, s2 = s2, s1 for w2 in s2: new_words = [w2[:i] + t + w2[i+1:] for t in string.ascii_lowercase for i in range(l)] for w in new_words: if w in s1: return level * 2 + 1 if w not in wordList: continue s.add(w) wordList.remove(w) s2 = s return 0
word-ladder
Python BFS with pruning, faster than 95+%
dustlihy
2
367
word ladder
127
0.368
Hard
1,440
https://leetcode.com/problems/word-ladder/discuss/1200737/Python-BFS-with-pruning-faster-than-95%2B
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: # bfs wordList = set(wordList) if endWord not in wordList: return 0 l, s1, s2 = len(beginWord), {beginWord}, {endWord} wordList.remove(endWord) level = 0 while s1 and s2: level += 1 s = set() if len(s1) > len(s2): s1, s2 = s2, s1 for w1 in s1: # level order new_words = [w1[:i] + t + w1[i+1:] for t in string.ascii_lowercase for i in range(l)] for w in new_words: if w in s2: return level + 1 if w not in wordList: continue s.add(w) wordList.remove(w) s1 = s return 0
word-ladder
Python BFS with pruning, faster than 95+%
dustlihy
2
367
word ladder
127
0.368
Hard
1,441
https://leetcode.com/problems/word-ladder/discuss/2755577/PYTHON-SOLUTION-USING-BFS-ALGORITHM
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: s=set(wordList) l=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t', 'u','v','w','x','y','z'] queue=deque([]) queue.append([beginWord,0]) while queue: a,b=queue.popleft() if a==endWord: return b+1 for j in range(len(a)): for i in l: if (a[:j]+i+a[j+1:]) in s and (a[:j]+i+a[j+1:])!=beginWord: s.remove(a[:j]+i+a[j+1:]) queue.append([a[:j]+i+a[j+1:],b+1]) return 0
word-ladder
PYTHON SOLUTION USING BFS ALGORITHM
shashank_2000
1
393
word ladder
127
0.368
Hard
1,442
https://leetcode.com/problems/word-ladder/discuss/2456833/Intuitive-solution-without-the-wildcard-logic-only-9-faster-though
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: """ approach: 1. make the adjacency list 2. run bfs """ wordList.insert(0, beginWord) wordList = set(wordList) visitedDic = {} if endWord not in wordList: return 0 for i in wordList: visitedDic[i]=0 dic = defaultdict(list) for i in (wordList): diff = self.helper(i,wordList) dic[i]=diff # now we need to do the BFS q = collections.deque() # POP(0) is O(N) is normal list, in deque it is O(1) q.append(beginWord) ans = 0 while q: size = len(q) ans += 1 for i in range(size): curr = q.popleft() visitedDic[curr] = 1 if curr == endWord: return ans for j in dic[curr]: if visitedDic[j]==0: q.append(j) return 0 def helper(self, s, wordList): diff = 0 l = set() for i in range(len(s)): for j in 'abcdefghijklmnopqrstuvwxyz': temp = s[0:i]+j+s[i+1:] # temp[i] = j # word = ''.join(temp) if temp!=s and temp in wordList: l.add(temp) return l
word-ladder
Intuitive solution without the wildcard logic, only 9% faster though
abhineetsingh192
1
47
word ladder
127
0.368
Hard
1,443
https://leetcode.com/problems/word-ladder/discuss/704077/Python3-two-end-bfs-(99.49)
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 #shortcut graph = dict() for word in wordList: for i in range(len(word)): graph.setdefault(word[:i] + "*" + word[i+1:], []).append(word) #two-end bfs front0, front1 = {beginWord}, {endWord} seen = {beginWord, endWord} ans = 1 while front0 and front1: ans += 1 if len(front0) > len(front1): front0, front1 = front1, front0 #move forward frontier temp = set() for word in front0: for i in range(len(word)): for node in graph.get(word[:i] + "*" + word[i+1:], []): if node in front1: return ans if node not in seen: temp.add(node) seen.add(node) front0 = temp return 0
word-ladder
[Python3] two-end bfs (99.49%)
ye15
1
130
word ladder
127
0.368
Hard
1,444
https://leetcode.com/problems/word-ladder/discuss/704077/Python3-two-end-bfs-(99.49)
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 #shortcut graph = dict() for word in wordList: for i in range(len(word)): graph.setdefault(word[:i] + "*" + word[i+1:], []).append(word) #two-end bfs front0, seen0 = {beginWord}, set() front1, seen1 = {endWord}, set() ans = 0 while front0 and front1: ans += 1 if front0 &amp; front1: return ans if len(front0) > len(front1): front0, front1 = front1, front0 seen0, seen1 = seen1, seen0 #move forward frontier temp = set() for word in front0: for i in range(len(word)): temp |= {node for node in graph.get(word[:i] + "*" + word[i+1:], []) if node not in seen0} seen0 |= temp front0 = temp return 0
word-ladder
[Python3] two-end bfs (99.49%)
ye15
1
130
word ladder
127
0.368
Hard
1,445
https://leetcode.com/problems/word-ladder/discuss/704077/Python3-two-end-bfs-(99.49)
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 # edge case mp = {} for word in wordList: for i in range(len(word)): key = word[:i] + "*" + word[i+1:] mp.setdefault(key, []).append(word) queue = [beginWord] seen = {beginWord} ans = 1 while queue: newq = [] for word in queue: if word == endWord: return ans for i in range(len(word)): key = word[:i] + "*" + word[i+1:] for ww in mp.get(key, []): if ww not in seen: newq.append(ww) seen.add(ww) queue = newq ans += 1 return 0 # impossible
word-ladder
[Python3] two-end bfs (99.49%)
ye15
1
130
word ladder
127
0.368
Hard
1,446
https://leetcode.com/problems/word-ladder/discuss/2842662/Graph-Shortest-Path-BFS
class Node: def __init__(self, val): self.val = val self.lvl = 1 class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 d = set(wordList) wordCombo = defaultdict(set) for word in wordList + [beginWord]: for i in range(len(word)): for x in string.ascii_lowercase: tmp = word[:i] + x + word[i+1:] if tmp != word and tmp in d: wordCombo[word].add(tmp) # print(wordCombo) q = deque([Node(beginWord)]) seen = set() while q: curr = q.popleft() if curr.val == endWord: return curr.lvl for v in wordCombo[curr.val]: if v in seen: continue seen.add(v) tmp = Node(v) tmp.lvl = curr.lvl + 1 q.append(tmp) return 0
word-ladder
Graph Shortest Path BFS
Adeyinka
0
2
word ladder
127
0.368
Hard
1,447
https://leetcode.com/problems/word-ladder/discuss/2705779/Simplest-BFS-solution
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: letters = "abcdefghijklmnopqrstuvwxyz" wordList = set(wordList) queue = deque() queue.append((beginWord,1)) if beginWord in wordList: wordList.remove(beginWord) while queue: current_word,chain_length = queue.popleft() if current_word == endWord: return chain_length for i,ch in enumerate(current_word): for new_letter in letters: if new_letter == ch: continue new_word = current_word[:i] + new_letter + current_word[i+1:] if new_word in wordList: queue.append((new_word,chain_length+1)) wordList.remove(new_word) return 0
word-ladder
Simplest BFS solution
shriyansnaik
0
7
word ladder
127
0.368
Hard
1,448
https://leetcode.com/problems/word-ladder/discuss/2668790/BFS-python-with-explanation
class Solution: def ladderLength(self, begin: str, end: str, word_list: List[str]) -> int: words = set(word_list) # make a set because existence query is O(1) vs O(N) for list queue = deque([begin]) distance = 1 while len(queue) > 0: n = len(queue) distance += 1 for _ in range(n): word = queue.popleft() for i in range(len(word)): for c in ascii_letters: next_word = word[:i] + c + word[i + 1:] if next_word not in words: continue if next_word == end: return distance queue.append(next_word) words.remove(next_word) # removing from the set is equivalent as marking the word visited return 0
word-ladder
BFS - python with explanation
user3734a
0
3
word ladder
127
0.368
Hard
1,449
https://leetcode.com/problems/word-ladder/discuss/2454761/help-me-optimize-this-code-getting-TLE
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: """ approach: 1. make the adjacency list 2. run bfs """ wordList.insert(0, beginWord) visitedDic = {} if endWord not in wordList: return 0 for i in range(len(wordList)): visitedDic[wordList[i]]=0 dic = defaultdict(list) for i in range(len(wordList)): diff = self.helper(wordList[i],wordList) dic[wordList[i]]=diff # now we need to do the BFS q = [] q.append(beginWord) ans = 0 while q: size = len(q) ans += 1 for i in range(size): curr = q.pop(0) visitedDic[curr] = 1 if curr == endWord: return ans for j in dic[curr]: if visitedDic[j]==0: q.append(j) return 0 def helper(self, s, wordList): diff = 0 l = set() for i in range(len(s)): for j in 'abcdefghijklmnopqrstuvwxyz': temp = list(s) temp[i] = j if ''.join(temp)!=s and ''.join(temp) in wordList: l.add(''.join(temp)) return list(l)
word-ladder
help me optimize this code, getting TLE
abhineetsingh192
0
29
word ladder
127
0.368
Hard
1,450
https://leetcode.com/problems/word-ladder/discuss/2428100/Faster-Than-98-Bidirectional-BFS
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 n = len(beginWord) h = collections.defaultdict(list) for word in wordList: for i in range(n): h[word[:i] + "*" + word[i + 1:]].append(word) #source queue sq = collections.deque() sq.append((beginWord, 1)) #destination queue dq = collections.deque() dq.append((endWord, 1)) #visited from source sv = {} sv[beginWord] = 1 #visited from destination dv = {} dv[endWord] = 1 while sq and dq: for _ in range(len(sq)): node, level = sq.popleft() for x in range(n): for word in h[node[:x] + "*" + node[x + 1:]]: if word in dv: print(word, sv, dv) return level + dv[word] if word not in sv: sv[word] = level + 1 sq.append((word, level + 1)) for _ in range(len(dq)): node, level = dq.popleft() for x in range(n): for word in h[node[:x] + "*" + node[x + 1:]]: if word in sv: return level + sv[word] if word not in dv: dv[word] = level + 1 dq.append((word, level + 1)) return 0
word-ladder
Faster Than 98 %, Bidirectional BFS
saurabh0225
0
62
word ladder
127
0.368
Hard
1,451
https://leetcode.com/problems/word-ladder/discuss/2424207/Clean-divided-into-easy-to-follow-parts-python3-solution()
class Solution: # O(n * m^2) time, n --> len(wordList), m --> len(wordList[i]) # O(n*m) space, # Approach: BFS, hashtable, string def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: vstd = set() pattern_map = {} def buildPattern() -> None: addWordPattern(beginWord) for word in wordList: addWordPattern(word) def addWordPattern(word: str) -> None: patterns = getPatterns(word) for pattern in patterns: if pattern not in pattern_map.keys(): pattern_map[pattern] = [] pattern_map[pattern].append(word) def getPatterns(word: str) -> List[str]: patterns = [] for i in range(len(word)): pattern = word[:i] + '#' + word[i+1:] patterns.append(pattern) return patterns def getNeighbours(root_word: str) -> List[str]: neighbours = [] patterns = getPatterns(root_word) for pattern in patterns: words = pattern_map[pattern] for word in words: if word != root_word: neighbours.append(word) return neighbours def bfs(root_word:str) -> int: qu = deque() qu.append(root_word) depth = 0 while qu: n = len(qu) depth +=1 for i in range(n): root_word = qu.popleft() if root_word in vstd: continue if root_word == endWord: return depth vstd.add(root_word) neighbours = getNeighbours(root_word) for nb in neighbours: qu.append(nb) return 0 buildPattern() ans = bfs(beginWord) return ans
word-ladder
Clean, divided into easy to follow parts, python3 solution()
destifo
0
6
word ladder
127
0.368
Hard
1,452
https://leetcode.com/problems/word-ladder/discuss/2423650/Python3-or-Easy-to-Understand-or-Efficient-or-Faster-than-99.28
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 # create adjacency list wordList.append(beginWord) neighbors = collections.defaultdict(list) for word in wordList: for j in range(len(word)): pattern = word[:j] + '*' + word[j+1:] neighbors[pattern].append(word) # print(neighbors) # do BFS to find the shortest sequence visited = set([beginWord]) q = deque([beginWord]) STS = 1 while q: for _ in range(len(q)): word = q.popleft() if word == endWord: return STS for j in range(len(word)): pattern = word[:j] + '*' + word[j+1:] for nWord in neighbors[pattern]: if nWord not in visited: visited.add(nWord) q.append(nWord) STS += 1 return 0
word-ladder
✅Python3 | Easy to Understand | Efficient | Faster than 99.28%
thesauravs
0
15
word ladder
127
0.368
Hard
1,453
https://leetcode.com/problems/word-ladder/discuss/2351613/Python-BFS-Chinese
class Solution: def ladderLength(self, b: str, e: str, lists: List[str]) -> int: if e not in lists: return 0 ls = string.ascii_lowercase # 所有lowercase字母 q = collections.deque([b]) lists = set(lists) res = 1 while q: size = len(q) for _ in range(size): word = q.popleft() if word == e: #如果找到, 直接输出, 因为bfs所以是最小值 return res for i in range(len(word)): # time: O(26nm) m是单词长度 for c in ls: if word[i] != c: newWord = word[:i] + c + word[i+1:] #这里换26-1次字母, 组成新单词 if newWord in lists: # 如果新单词在list里面, 证明已经找到 lists.remove(newWord) # 移除, 防止重复访问 q.append(newWord) res += 1 return 0
word-ladder
Python BFS Chinese 中文
scr112
0
60
word ladder
127
0.368
Hard
1,454
https://leetcode.com/problems/word-ladder/discuss/2086062/Python-BFS-Solution
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: d = {} wordList.append(beginWord) ans = 1 visited = set({}) for word in wordList: for j in range(len(word)): pattern = word[:j] + '*' + word[j+1:] if pattern in d: d[pattern].append(word) else: d[pattern] = [word] q = [] q.append(beginWord) q.append('N') visited.add(beginWord) while q: curr = q.pop(0) if curr == 'N': ans += 1 if len(q) != 0: q.append('N') else: for i in range(len(curr)): pattern = curr[:i] + '*' + curr[i+1:] for w2 in d[pattern]: if w2 == endWord: return ans + 1 if w2 not in visited: visited.add(w2) q.append(w2) return 0
word-ladder
Python BFS Solution
DietCoke777
0
102
word ladder
127
0.368
Hard
1,455
https://leetcode.com/problems/word-ladder/discuss/1249010/Python-O(beginWord.length*26*n)-solution-using-BFS
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord in wordList == False: return 0 n, ans = len(wordList), 0 mp, chars, queue = Counter(wordList), list(string.ascii_lowercase), deque() queue.append(beginWord) l_q = len(queue) while l_q: ans += 1 while l_q: word = queue.popleft() if word == endWord: return ans n, word = len(word), [ch for ch in word] for i in range(n): ch = word[i] for k in chars: word[i] = k aux = ''.join(word) if mp[aux] > 0: queue.append(aux) del mp[aux] word[i] = ch l_q -= 1 l_q = len(queue) return 0
word-ladder
Python O(beginWord.length*26*n) solution using BFS
m0biu5
0
88
word ladder
127
0.368
Hard
1,456
https://leetcode.com/problems/word-ladder/discuss/503648/Python3-BFS-solution-too-slow-even-after-all-optimizations-from-other-threads.-Help
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 visited = {} helper = {} for word in wordList: helper[word] = [word[:i]+'*'+word[i+1:] for i in range(len(word))] queue = [] queue.append((endWord,1)) catchment = {beginWord[:i]+'*'+beginWord[i+1:]:0 for i in range(len(beginWord))} while queue: word,depth = queue.pop(0) if any([True if token in catchment else False for token in helper[word]]): return depth+1 # +1 coz n words, not n transitions visited[word] = 1 for other in wordList: if other not in visited: if any([True if token in helper[word] else False for token in helper[other]]): queue.append((other,depth+1)) return 0
word-ladder
[Python3] BFS solution too slow even after all optimizations from other threads. Help?
elstersen
0
122
word ladder
127
0.368
Hard
1,457
https://leetcode.com/problems/word-ladder/discuss/238033/Python3-BFS-set
class Solution: def ladderLength(self, beginWord: 'str', endWord: 'str', wordList: 'List[str]') -> 'int': wordSet = set(wordList) if endWord not in wordSet: return 0 wordDict = {1:[beginWord]} output = 1 while True: words = wordDict[output] wordDict[output + 1] = [] for word in words: for i in range(len(word)): for j in string.ascii_lowercase: wordChange = word[:i] + j + word[i+1:] if wordChange == endWord: return output + 1 if wordChange in wordSet: wordDict[output+1].append(wordChange) wordSet.remove(wordChange) if wordDict[output+1] == []: break output += 1 return 0
word-ladder
Python3 BFS set
xiangyupeng1994
0
145
word ladder
127
0.368
Hard
1,458
https://leetcode.com/problems/longest-consecutive-sequence/discuss/1109808/Python-Clean-Union-Find-with-explanation
class Node: def __init__(self, val): self.val = val self.parent = self self.size = 1 class UnionFind: def find(self, node): if node.parent != node: node.parent = self.find(node.parent) return node.parent def union(self, node1, node2): parent_1 = self.find(node1) parent_2 = self.find(node2) if parent_1 != parent_2: parent_2.parent = parent_1 parent_1.size += parent_2.size return parent_1.size class Solution: def longestConsecutive(self, nums: List[int]) -> int: uf = UnionFind() nodes = {} max_size = 0 for num in nums: if num not in nodes: node = Node(num) nodes[num] = node size = 1 if num + 1 in nodes: size = uf.union(node, nodes[num+1]) if num - 1 in nodes: size = uf.union(node, nodes[num-1]) max_size = max(max_size, size) return max_size ```
longest-consecutive-sequence
[Python] Clean Union Find with explanation
l3arner
21
1,800
longest consecutive sequence
128
0.489
Medium
1,459
https://leetcode.com/problems/longest-consecutive-sequence/discuss/773690/Simple-O(n)-Python-Solution-with-Explanation
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not nums: return 0 num_set = set(nums) longest = 0 for n in nums: if n-1 not in num_set: length = 0 while n in num_set: length += 1 n += 1 longest = max(longest, length) return longest
longest-consecutive-sequence
Simple O(n) Python Solution with Explanation
user1469X
4
700
longest consecutive sequence
128
0.489
Medium
1,460
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2546572/Python-solution-keeping-track-of-current-max-and-current-count
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums = sorted(set(nums)) cur_max = 0 cur_count = 0 prev = None for i in nums: if prev is not None: if prev+1 == i: cur_count += 1 else: cur_max = max(cur_max, cur_count) cur_count = 1 else: cur_count += 1 prev = i return max(cur_max, cur_count)
longest-consecutive-sequence
📌 Python solution keeping track of current max and current count
croatoan
3
113
longest consecutive sequence
128
0.489
Medium
1,461
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2265067/Python-O(n)-Solution-using-Set
class Solution: def longestConsecutive(self, nums: List[int]) -> int: seen = set(nums) longest = 0 for n in seen: if (n-1) not in seen: length = 1 while (n+length) in seen: length += 1 longest = max(length, longest) return longest
longest-consecutive-sequence
Python O(n) Solution using Set
deucesevenallin
3
204
longest consecutive sequence
128
0.489
Medium
1,462
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2239243/Python-oror-O(n)-oror-set-oror-explanation
class Solution: def longestConsecutive(self, nums: List[int]) -> int: maxLength = 0 s = set(nums) ans=0 n=len(nums) for i in range(len(nums)): # current element is starting point if (nums[i]-1) not in s: # Then check for next elements in the sequence j = nums[i] while(j in s): j += 1 maxLength = max(maxLength, j-nums[i]) return maxLength
longest-consecutive-sequence
Python || O(n) || set || explanation
palashbajpai214
3
176
longest consecutive sequence
128
0.489
Medium
1,463
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2686938/Python-Traversing-every-path-at-most-once
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums_set = set(nums) longest = 0 for num in nums: # If the number before current number not in set # then this path has yet to be traversed if num-1 not in nums_set: # Initialize length to account for current number length = 1 # Continue incrementing while every +1 number exists in set while (num + length) in nums_set: length += 1 # Once done traversing, update max longest with max longest longest = max(longest, length) # Return this return longest
longest-consecutive-sequence
[Python] Traversing every path at most once
graceiscoding
2
251
longest consecutive sequence
128
0.489
Medium
1,464
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2326350/Python-O(n)-Time-Space-with-full-working-explanation
class Solution: def longestConsecutive(self, nums: List[int]) -> int: # Time: O(n) and Space: O(n) numSet = set(nums) # will contain all the numbers from the list only once longest = 0 for n in nums: # we will take each element one at a time and check if n-1 not in numSet: # if smaller consecutive number is present in the set or not, if it is means the LCS should not start from n length = 0 # when it's not set length to 0 to start counting the len of LCS while n+length in numSet: # while the larger consecutive number is present in the set the LCS len will keep on increasing length += 1 longest = max(length, longest) # checking if the current length of LCS is the longest or the previous one is return longest
longest-consecutive-sequence
Python O(n) Time Space with full working explanation
DanishKhanbx
2
103
longest consecutive sequence
128
0.489
Medium
1,465
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2242925/Python-or-Java-Shortest-Code-or-O(N)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: s, maxi = set(nums), 0 for i in s: if i + 1 in s: continue count = 1 while i - count in s: count += 1 maxi = max(maxi, count) return maxi
longest-consecutive-sequence
✅ Python | Java Shortest Code | O(N)
dhananjay79
2
115
longest consecutive sequence
128
0.489
Medium
1,466
https://leetcode.com/problems/longest-consecutive-sequence/discuss/1513221/Easy-Python-3-Solution
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums_set = set(nums) length =0 #longest sequence for i in nums: if i-1 not in nums_set: #check if 1 less num present in set currentNum = i currentLen = 1 while (currentNum+1) in nums_set: #find all nums of a consecutive sequence currentLen+=1 currentNum+=1 length = max(length, currentLen) return length ```
longest-consecutive-sequence
Easy Python 3 Solution
miss_sunshine
2
190
longest consecutive sequence
128
0.489
Medium
1,467
https://leetcode.com/problems/longest-consecutive-sequence/discuss/1339712/GolangPython3-Solution-with-using-hashset
class Solution: def longestConsecutive(self, nums: List[int]) -> int: s = set(nums) d = {} max_seq_len = 0 for num in nums: cur_seq_len = 0 num_cp = num while num_cp in s: cur_seq_len += 1 s.remove(num_cp) num_cp -= 1 if num_cp in d: cur_seq_len += d[num_cp] d[num] = cur_seq_len max_seq_len = max(max_seq_len, cur_seq_len) return max_seq_len
longest-consecutive-sequence
[Golang/Python3] Solution with using hashset
maosipov11
2
116
longest consecutive sequence
128
0.489
Medium
1,468
https://leetcode.com/problems/longest-consecutive-sequence/discuss/1339712/GolangPython3-Solution-with-using-hashset
class Solution: def longestConsecutive(self, nums: List[int]) -> int: s = set(nums) max_seq_len = 0 for num in nums: if num - 1 in s: continue cur_seq_len = 0 while num in s: cur_seq_len += 1 num += 1 max_seq_len = max(max_seq_len, cur_seq_len) return max_seq_len
longest-consecutive-sequence
[Golang/Python3] Solution with using hashset
maosipov11
2
116
longest consecutive sequence
128
0.489
Medium
1,469
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2243002/Python-oror-O(n)-oror-Optimal-solution-oror-Removing-from-set
class Solution: def longestConsecutive(self, nums: List[int]) -> int: numset = set(nums) ans = 0 while not len(numset) == 0: # pick 'random' element from set el = numset.pop() numberOfConsecutiveElements = 1 # find neighbors bigger than element 'el' i = 1 neighbor = el + i while neighbor in numset: # remove neighbor from set to avoid looking it up in next iterations # this gives us O(n) numset.remove(neighbor) i += 1 neighbor = el + i numberOfConsecutiveElements += i - 1 # find neighbors smaller than element 'el' i = 1 neighbor = el - i while neighbor in numset: # remove neighbor from set to avoid looking it up in next iterations # this gives us O(n) numset.remove(neighbor) i += 1 neighbor = el - i numberOfConsecutiveElements += i - 1 ans = max(ans, numberOfConsecutiveElements) return ans
longest-consecutive-sequence
Python || O(n) || Optimal solution || Removing from set
xfiderek
1
30
longest consecutive sequence
128
0.489
Medium
1,470
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2242014/python3-or-easy-to-understand-or-clear-explanation-or-O(n)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: ans = 0 # dictionary declaration dictionary = {} # adding nums in dictionary to check as they are visited or not for num in nums: dictionary[num]=1 # to keep track of max length max_length = 1 # loop through the set for num in set(nums): # to check if the num is smallest or not and if it is smallest then num-1 will not be there # in dictionary and dictionary.get(num-1, 0) will return 0 if dictionary.get(num-1, 0) == 0: # now we are looking for the next number (num+1) present in dictionary or not next_num = num + 1 # if next number is in the list then we add +1 to max_length and increment the next_num while dictionary.get(next_num, 0): max_length += 1 next_num += 1 # comparing and storing the max_length in ans and initialises max_length ans = max(ans, max_length) max_length = 1 return ans
longest-consecutive-sequence
python3 | easy to understand | clear explanation | O(n)
H-R-S
1
25
longest consecutive sequence
128
0.489
Medium
1,471
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2238773/Python-using-set.-Time%3A-O(N).-Space%3A-O(N)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums = set(nums) result = 0 while nums: n = nums.pop() count = 1 m = n while m + 1 in nums: nums.remove(m + 1) count += 1 m = m + 1 while n - 1 in nums: nums.remove(n - 1) count += 1 n = n - 1 result = max(result, count) return result
longest-consecutive-sequence
Python, using set. Time: O(N). Space: O(N)
blue_sky5
1
45
longest consecutive sequence
128
0.489
Medium
1,472
https://leetcode.com/problems/longest-consecutive-sequence/discuss/1932044/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not nums: return 0 count = 0 res = 0 a = sorted(set(nums)) for i in range(0,len(a)-1): if a[i]+1 == a[i+1]: count+=1 print(count) res = max(count, res) else: count = 0 return res+1
longest-consecutive-sequence
Python (Simple Approach and Beginner-Friendly)
vishvavariya
1
83
longest consecutive sequence
128
0.489
Medium
1,473
https://leetcode.com/problems/longest-consecutive-sequence/discuss/1637476/Easy-Python-Solution(99.98)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums=list(set(nums)) nums.sort() c=1 a=[0] for i in range(len(nums)-1): if nums[i]+1==nums[i+1]: c+=1 else: a.append(c) c=1 return max(max(a),c) if nums else 0
longest-consecutive-sequence
Easy Python Solution(99.98%)
Sneh17029
1
412
longest consecutive sequence
128
0.489
Medium
1,474
https://leetcode.com/problems/longest-consecutive-sequence/discuss/1401188/Python-oror-O(2n)-or-easy-or-SR
class Solution: def longestConsecutive(self, nums: List[int]) -> int: """ main idea is to start from lowest number O(2n) """ #we first preprocess such that no duplicate elements are present HashSet = set(nums) max_streak = 0 for number in list(HashSet): if number-1 not in HashSet: #this is the lowest number possible for starting a new Streak cnt = 0 tmp = number while tmp in HashSet: cnt+=1 tmp+=1 max_streak = max(max_streak, cnt) return max_streak
longest-consecutive-sequence
Python || O(2n) | easy | SR
sathwickreddy
1
218
longest consecutive sequence
128
0.489
Medium
1,475
https://leetcode.com/problems/longest-consecutive-sequence/discuss/705694/Python3-two-O(N)-approaches
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums = set(nums) ans = 0 for x in nums: if x-1 not in nums: xx = x + 1 while xx in nums: xx += 1 ans = max(ans, xx-x) return ans
longest-consecutive-sequence
[Python3] two O(N) approaches
ye15
1
176
longest consecutive sequence
128
0.489
Medium
1,476
https://leetcode.com/problems/longest-consecutive-sequence/discuss/705694/Python3-two-O(N)-approaches
class Solution: def longestConsecutive(self, nums: List[int]) -> int: lcs = dict() for x in nums: if x not in lcs: lcs[x] = lcs[x + lcs.get(x+1, 0)] = lcs[x-lcs.get(x-1, 0)] = 1 + lcs.get(x+1, 0) + lcs.get(x-1, 0) return max(lcs.values(), default=0)
longest-consecutive-sequence
[Python3] two O(N) approaches
ye15
1
176
longest consecutive sequence
128
0.489
Medium
1,477
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2843560/Python-Easy-Solution-90
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if len(nums) == 0: return 0 l = list(set(nums)) s = sorted(l) count = 1 res = [] for i in range(len(s)-1): if (s[i] + 1) == s[i+1]: count +=1 else: res.append(count) count = 1 res.append(count) return max(res)
longest-consecutive-sequence
Python Easy Solution 90%
Jashan6
0
3
longest consecutive sequence
128
0.489
Medium
1,478
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2842614/Simple-python-solution-with-O(n)-TC%3A-80.17
class Solution: def longestConsecutive(self, nums: List[int]) -> int: set_a = set(nums) res = 0 for i in set_a: if i-1 in set_a: continue temp = 0 while i in set_a: temp += 1 i += 1 if temp > res: res = temp return res
longest-consecutive-sequence
😎 Simple python solution with O(n) TC: 80.17%
Pragadeeshwaran_Pasupathi
0
4
longest consecutive sequence
128
0.489
Medium
1,479
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2840547/Python-or-Number-LineIntuitionSet-or-Comments
class Solution: def longestConsecutive(self, nums: List[int]) -> int: longest = 0 nums = set(nums) # convert to have a faster lookup time for num in nums: if num - 1 not in nums: # if left number not in nums, it's a min value current = 0 while num in nums: # while there is a next value/element, keep on incrementing the size current += 1 num += 1 # the next value/element longest = max(current, longest) # which is the longer number line? return longest
longest-consecutive-sequence
🎉Python | Number Line/Intuition/Set | Comments
Arellano-Jann
0
4
longest consecutive sequence
128
0.489
Medium
1,480
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2834546/Another-approach-using-set.-O(n)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums_set = set(nums) longest = 0 while True: if len(nums_set) == 0: break num = nums_set.pop() temp_longest = 1 prev = num - 1 while prev in nums_set: nums_set.remove(prev) prev -= 1 temp_longest += 1 next = num + 1 while next in nums_set: nums_set.remove(next) next += 1 temp_longest += 1 longest = max(longest, temp_longest) return longest
longest-consecutive-sequence
Another approach using set. O(n)
monkecoder
0
5
longest consecutive sequence
128
0.489
Medium
1,481
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2822805/Intuitive-solution-using-Linked-Lists
class LinkedList: def __init__(self, v) -> None: self.val = v self.prev = None self.next = None class Solution: def longestConsecutive(self, nums: List[int]) -> int: # we can just sort in nlogn then it is trivial. note order here does not matter. # we can make a linked list node of each element, then build the chains nodes = {} # num: linked list node for n in nums: # ignore duplicates since they can't help if n in nodes: continue node = LinkedList(n) nodes[n] = node # check if we can link it to another node if n-1 in nodes: nodes[n-1].next = node node.prev = nodes[n-1] if n+1 in nodes: nodes[n+1].prev = node node.next = nodes[n+1] # find starting points (ones without a prev) starters = {n:node for n, node in nodes.items() if not node.prev} # get longest one res = 0 for n,node in starters.items(): head = node count = 0 while head: head = head.next count += 1 res = max(res,count) return res
longest-consecutive-sequence
Intuitive solution using Linked Lists
johnsmith999
0
2
longest consecutive sequence
128
0.489
Medium
1,482
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2805853/Python-easy-to-understand-long-solution-broken-down
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums.sort() if len(nums)>=1: count = 1 else: return 0 count, count1 = 1,1 print((nums)) for i in range(0,len(nums)-1): if (nums[i+1]-nums[i])==1: count = count+1 elif (nums[i]==nums[i+1]): count=count else: if count>count1: count1 = count count = 1 print(count) return max(count,count1)
longest-consecutive-sequence
Python easy to understand long solution broken down
mikeyone
0
4
longest consecutive sequence
128
0.489
Medium
1,483
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2803642/Easy-Solution
class Solution: def longestConsecutive(self, nums: List[int]) -> int: numSet = set(nums) longest = 0 for n in nums: #check if its the start of a sequence if (n - 1) not in numSet: length = 0 while (n + length) in numSet: length += 1 longest = max(length, longest) return longest
longest-consecutive-sequence
Easy Solution
swaruptech
0
6
longest consecutive sequence
128
0.489
Medium
1,484
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2772710/Simple-Python3-implementation.
class Solution: def longestConsecutive(self, nums: List[int]) -> int: max_depth = 0 queue = set(nums) # set is a hash table, looking is O(1) while len(queue) > 0: depth = self.dfs(queue, queue.pop()) if depth > max_depth: max_depth = depth return max_depth def dfs(self, queue, number): """ visit each element """ num_above, num_below = 0, 0 if number == None: return 0 number_above = number+1 number_below = number-1 # check number below if number_below in queue: # O(1) queue.remove(number_below) num_above = self.dfs(queue, number_below) # check number above if number_above in queue: # O(1) queue.remove(number_above) num_below = self.dfs(queue, number_above) return num_above + num_below + 1 # add one to consider this element as well
longest-consecutive-sequence
Simple Python3 implementation.
dreyceyalbin
0
3
longest consecutive sequence
128
0.489
Medium
1,485
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2750869/Time-complexity-of-%22checking-if-element-in-set%22-is-Average%3A-O(1)-Worst%3A-O(n).
class Solution: def longestConsecutive(self, nums: List[int]) -> int: """TC: O(n), SC: O(n)""" nums = set(nums) # make it faster in following processes longest = 0 for elem in nums: if elem-1 not in nums: # try to find smaller one start_at = elem end_at = start_at while end_at+1 in nums: end_at += 1 longest = max(longest, abs(end_at - start_at) + 1) return longest
longest-consecutive-sequence
Time complexity of "checking if element in set" is Average: O(1), Worst: O(n).
woora3
0
4
longest consecutive sequence
128
0.489
Medium
1,486
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2747500/Python-fast-straightforward-solution
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums.sort() mx = 0 c = 0 for i in range(len(nums)-1): if nums[i]+1 == nums[i+1]: c += 1 print(c) if nums[i] == nums[i+1]: continue if nums[i+1] > nums[i]+1: mx = max(c, mx) c = 0 mx = max(c, mx) return mx+1 if len(nums) > 0 else 0
longest-consecutive-sequence
Python fast straightforward solution
asamarka
0
5
longest consecutive sequence
128
0.489
Medium
1,487
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2746643/Easy-and-simple-Set-solution-or-Python-or-Beats-90-in-speed
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if len(nums)==0:return 0; x=list(set(nums)) ans=1;fans=0 x.sort() for i in range(1,len(x)): if x[i]-x[i-1]==1:ans+=1 else:fans=max(ans,fans);ans=1 ans=max(ans,fans) return ans;
longest-consecutive-sequence
Easy and simple Set solution | Python | Beats 90% in speed
kamtendra
0
2
longest consecutive sequence
128
0.489
Medium
1,488
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2744497/Beat-97.-2-solutions.-O(n)-and-O(nlogn)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not nums: return 0 nums.sort() longestStreak = 1 currentStreak = 1 for i in range(1, len(nums)): if nums[i] != nums[i-1]: if nums[i] == nums[i-1] + 1: currentStreak += 1 else: longestStreak = max(longestStreak, currentStreak) currentStreak = 1 return max(currentStreak, longestStreak) return longestStreak
longest-consecutive-sequence
Beat 97%. 2 solutions. O(n) & O(nlogn)
mdfaisalabdullah
0
5
longest consecutive sequence
128
0.489
Medium
1,489
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2744497/Beat-97.-2-solutions.-O(n)-and-O(nlogn)
class Solution: def longestConsecutive(self, nums: List[int]) -> int: longest_streak = 0 num_set = set(nums) for num in num_set: if num - 1 not in num_set: current_num = num current_streak = 1 while current_num + 1 in num_set: current_num += 1 current_streak += 1 longest_streak = max(longest_streak, current_streak) return longest_streak
longest-consecutive-sequence
Beat 97%. 2 solutions. O(n) & O(nlogn)
mdfaisalabdullah
0
5
longest consecutive sequence
128
0.489
Medium
1,490
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2740718/Simple-Passing-Solution-using-a-sorted-set
class Solution: def longestConsecutive(self, nums: List[int]) -> int: elems = sorted(list(set(nums))) seq = 1 left = 0 right = 1 max_seq = seq N = len(elems) if N <= 1: return N while right < N: if elems[left] == elems[right] - 1: seq += 1 else: max_seq = max(max_seq, seq) seq = 1 left += 1 right += 1 max_seq = max(max_seq, seq) return max_seq
longest-consecutive-sequence
Simple Passing Solution using a sorted set
koff82
0
1
longest consecutive sequence
128
0.489
Medium
1,491
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2738781/Python-easy-understanding-solution
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not nums: return 0 holder = {} nums = list(set(nums)) for i in nums: left = right = 0 if holder.get(i-1): left = holder[i-1] if holder.get(i+1): right = holder[i+1] new_value = right+left+1 holder[i-left] = new_value holder[i+right] = new_value return max(i for i in holder.values())
longest-consecutive-sequence
Python easy understanding solution
shotgunner
0
4
longest consecutive sequence
128
0.489
Medium
1,492
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2730621/Python3-Weighted-Quick-Union-with-Path-Compression
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not nums: return 0 uf = {x:x for x in nums} counts = {x:1 for x in nums} def find(id): while id != uf[id]: uf[id] = uf[uf[id]] id = uf[id] return id def union(p,q): id_p = find(p) id_q = find(q) if id_p == id_q: return else: if counts[id_p] < counts[id_q]: uf[id_p] = uf[id_q] counts[id_q] += counts[id_p] else: uf[id_q] = uf[id_p] counts[id_p] += counts[id_q] nums_set = set(nums) for num in nums_set: if num+1 in nums_set: union(num+1, num) if num-1 in nums_set: union(num-1, num) return max(counts.values())
longest-consecutive-sequence
Python3 Weighted Quick Union with Path Compression
Mbarberry
0
6
longest consecutive sequence
128
0.489
Medium
1,493
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2723036/Python3-code-or-Simple-Solution-or-95-memory-space-and-55-faster
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not(nums): return 0 if len(nums)==1: return 1 maxCount=1 cnt=1 nums.sort() for x in range(len(nums)-1): if nums[x+1]==(nums[x]+1): cnt+=1 maxCount=max(cnt,maxCount) elif nums[x+1]==nums[x]: continue else: cnt=1 continue return maxCount ```
longest-consecutive-sequence
Python3 code | Simple Solution | 95% memory space and 55% faster
raviacts035
0
1
longest consecutive sequence
128
0.489
Medium
1,494
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2720453/python-easy-solution-faster
class Solution: def longestConsecutive(self, nums: List[int]) -> int: numset=set(nums) lseq=0 for i in nums: if(i-1 not in numset): longest=0 while(i+longest in numset): longest+=1 lseq=max(longest,lseq) return lseq
longest-consecutive-sequence
python easy solution faster
Raghunath_Reddy
0
7
longest consecutive sequence
128
0.489
Medium
1,495
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2702002/A-naive-solution
class Solution: def longestConsecutive(self, nums: List[int]) -> int: cnt, max = 0,0 arr = sorted(set(nums)) res = [0] if len(arr): for i in range(len(arr)-1): if arr[i+1]-arr[i] == 1: cnt+=1 if cnt>max: max=cnt else: cnt=0 max+=1 return max
longest-consecutive-sequence
A naive solution
AliAlthiab
0
2
longest consecutive sequence
128
0.489
Medium
1,496
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2694954/O(n)-time-easy-solution
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums = set(nums) longest = 0 for n in nums: if n-1 not in nums: length = 0 while n + length in nums: length += 1 longest = max(longest, length) return longest
longest-consecutive-sequence
O(n) time easy solution
zananpech9
0
4
longest consecutive sequence
128
0.489
Medium
1,497
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2671769/Python-faster-than-98
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums_set = set(nums) seen = set() longest = 0 for num in nums: if num in seen: continue target = num+1 cur_len = 1 while target in nums_set: seen.add(target) target += 1 cur_len += 1 target = num-1 while target in nums_set: seen.add(target) target -= 1 cur_len += 1 longest = max(longest, cur_len) return longest
longest-consecutive-sequence
Python faster than 98%
cprachaseree
0
2
longest consecutive sequence
128
0.489
Medium
1,498
https://leetcode.com/problems/longest-consecutive-sequence/discuss/2626274/Python3-very-simple-solution-using-python-dictionary
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if 0 <= len(nums) < 2: return len(nums) longest = 0 d = {} for num in nums: if num not in d: left = d.get(num - 1, 0) right = d.get(num + 1, 0) current_longest = left + right + 1 longest = max(longest, current_longest) d[num] = d[num-left] = d[num + right] = current_longest return longest
longest-consecutive-sequence
Python3 very simple solution using python dictionary
miko_ab
0
33
longest consecutive sequence
128
0.489
Medium
1,499