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/number-of-matching-subsequences/discuss/932263/Python3-two-approaches
class Solution: def numMatchingSubseq(self, S: str, words: List[str]) -> int: def fn(word): """Return True if word is subsequence of S.""" k = 0 for ch in word: k = S.find(ch, k) + 1 if not k: return False return True return sum(fn(word) for word in words)
number-of-matching-subsequences
[Python3] two approaches
ye15
1
198
number of matching subsequences
792
0.519
Medium
12,900
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2612921/Simple-Python-solution-with-Hashmap-and-pointers
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: index = dict() for i in range(len(s)): if (s[i] not in index): index[s[i]] = [] index[s[i]].append(i) res = 0 for word in words: # pointer on word i = 0 # pointer on s j = 0 while i < len(word): if (word[i] not in index): break pos = self.leftBound(index[word[i]], j) if (pos == -1): break j = index[word[i]][pos] + 1 i += 1 if (i == len(word)): res += 1 return res def leftBound(self, arr, target): left, right = 0, len(arr) while (left < right): mid = left + (right - left) // 2 if (arr[mid] < target): left = mid + 1 else: right = mid if (left == len(arr)): return -1 return left
number-of-matching-subsequences
Simple Python solution with Hashmap and pointers
leqinancy
0
8
number of matching subsequences
792
0.519
Medium
12,901
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2605158/Python-or-Binary-Search-or-O(mlogn)
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: res = 0 pos = defaultdict(list) for i, c in enumerate(s): pos[c].append(i) for word in words: i, j = 0, 0 for w in word: indexes = pos[w] if not indexes: break # no such char cur = self.left_bound(indexes, j) # indexes' index if cur == -1: break # no more char left j = indexes[cur] + 1 # j moves to the next index i += 1 if i == len(word): res += 1 return res def left_bound(self, arr, target): l, r = 0, len(arr) while l < r: m = l + (r - l) // 2 if arr[m] < target: l = m + 1 else: r = m if l == len(arr): l = -1 return l
number-of-matching-subsequences
Python | Binary Search | O(mlogn)
Kiyomi_
0
21
number of matching subsequences
792
0.519
Medium
12,902
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2333683/Easy-Python-Solution-from-IsSubsequence-Problem-Enhancement
class Solution: def isSubsequence(self, s: str, t: str) -> bool: i = 0 j = 0 while i < len(s) and j < len(t): if s[i] == t[j]: i+=1 j+=1 return 1 if i == len(s) else 0 def numMatchingSubseq(self, s: str, words: List[str]) -> int: count = 0 checkMap = {} for w in words: if w in checkMap: if checkMap[w] == 1: count+=1 continue res = self.isSubsequence(w, s) checkMap[w] = res if res: count+=1 return count ```
number-of-matching-subsequences
Easy Python Solution from IsSubsequence Problem Enhancement
shubhamnagota
0
64
number of matching subsequences
792
0.519
Medium
12,903
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2315451/Python3-For-Loops-90-Run-Time
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: rt = 0 for word in words: # to go through each word and check if it matches prev = -1 # to record index of last letter, -1 for the 1st letter m = len(word) for ii in range(m): # to go through each letter of the word c = word[ii] temp = s.find(c, prev+1) # search the letter in str from previous index to end if temp <= prev: break # if the index of the letter is not found or less than previous one, not match, quit this for loop else: prev = temp # otherwise update previous index for next letter if m-1 == ii: rt += 1 # after the last letter and still in the loop, add 1 the the return value return rt
number-of-matching-subsequences
Python3 For Loops, 90% Run Time
wwwhhh1988
0
9
number of matching subsequences
792
0.519
Medium
12,904
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2312309/Python-Binary-Search-2-Approach
class Solution(object): def numMatchingSubseq(self, s, words): wordMap = collections.defaultdict(list) for i,ch in enumerate(s): wordMap[ch].append(i) def is_lcs(word): start = 0 for ch in word: arr = wordMap[ch] i = 0 j = len(arr)-1 index = -1 while i<=j: mid = (i+j)//2 if arr[mid]>=start: index = mid j = mid-1 elif arr[mid]<start: i = mid+1 if index == -1: return False start = arr[index]+1 return True count = 0 for word in words: if is_lcs(word): count+=1 return count
number-of-matching-subsequences
Python Binary Search 2 Approach
Abhi_009
0
18
number of matching subsequences
792
0.519
Medium
12,905
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2312054/Python3-Easy-to-Understand-or-Faster-than-98
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: return sum((self.isSub(s, word) for word in words)) def isSub(self, s: str, word: str) -> int: ind = 0 for char in word: ind = s.find(char, ind) + 1 if ind == 0: return 0 return 1
number-of-matching-subsequences
✅Python3 Easy to Understand | Faster than 98%
thesauravs
0
3
number of matching subsequences
792
0.519
Medium
12,906
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2308085/feel-top-votes-hard-to-understand-so-I-figure-out-this-stupid-but-easy-to-understand-method
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: # count of match count = 0 #build a hash map for s index d = defaultdict(list) for i, a in enumerate(s): d[a].append(i) for sub in words: curind = -1# current index l = len(sub) # length of sub , later match 1 minus 1 # if the letter not in hashmap or # largest index is on the left of current, # then this sub doesn't match, move on for s in sub: if (s not in d) or d[s][-1]<= curind: continue #find the smallest index larger than current index and update for i in d[s]: if i>curind: curind=i break #update if we find a match l-=1 # if all match, increase count by one if l == 0: count+=1 return count
number-of-matching-subsequences
feel top votes hard to understand, so I figure out this stupid but easy to understand method
geng0021
0
13
number of matching subsequences
792
0.519
Medium
12,907
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2307869/100-C%2B%2B-Java-and-Python-Optimal-Solution
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: root = {} def insert(word: str) -> None: node = root for c in word: if c not in node: node[c] = {'count': 0} node = node[c] node['count'] += 1 for word in words: insert(word) def dfs(s: str, i: int, node: dict) -> int: ans = node['count'] if 'count' in node else 0 if i >= len(s): return ans for c in string.ascii_lowercase: if c in node: try: index = s.index(c, i) ans += dfs(s, index + 1, node[c]) except ValueError: continue return ans return dfs(s, 0, root)
number-of-matching-subsequences
✔️ 100% - C++, Java and Python Optimal Solution
Theashishgavade
0
46
number of matching subsequences
792
0.519
Medium
12,908
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2307651/Python-solutions-%3A-Trie-%2B-DFS-and-Hashmap
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: def isSubSequence(source,word): wordIndex = 0 for chrSoruce in source: if word[wordIndex] == chrSoruce: wordIndex+=1 if wordIndex == len(word): return True if wordIndex > len(word): break return False count = 0 hashmap = {} for word in words: if word not in hashmap: if isSubSequence(s,word): hashmap[word] = True count +=1 else: hashmap[word] = False else: if hashmap[word]: count+=1 return count
number-of-matching-subsequences
Python solutions : Trie + DFS and Hashmap
manojkumarmanusai
0
97
number of matching subsequences
792
0.519
Medium
12,909
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2307542/GolangPython-Solutions
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: visited = {} counter = 0 for word in words: if word in visited: if visited[word] is True: counter+=1 continue idx = 0 for letter in s: if letter == word[idx]: idx+=1 if idx == len(word): visited[word] = True counter+=1 break else: visited[word] = False return counter
number-of-matching-subsequences
Golang/Python Solutions
vtalantsev
0
27
number of matching subsequences
792
0.519
Medium
12,910
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2306766/Python-Simple-Python-Solution-Using-Dictionary-(-HashMap-)
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: d = {} for index in range(len(s)): if s[index] not in d: d[s[index]] = [index] else: d[s[index]].append(index) result = [] for word in words: check = 0 current_index = -1 for char in word: if char not in d: break else: for index in d[char]: if index > current_index: current_index = index check = check + 1 break if check == len(word): result.append(word) return len(result)
number-of-matching-subsequences
[ Python ] ✅✅ Simple Python Solution Using Dictionary ( HashMap ) 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
83
number of matching subsequences
792
0.519
Medium
12,911
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2083517/Clean-Intuitive-Python-with-Heads-Hashmap
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: heads = defaultdict(list) for word in words: heads[word[0]].append(word) ans = 0 for c in s: strs = heads[c] heads[c] = [] for part in strs: if len(part) == 1: ans += 1 else: heads[part[1]].append(part[1:]) return ans
number-of-matching-subsequences
Clean, Intuitive Python with Heads Hashmap
boris17
0
120
number of matching subsequences
792
0.519
Medium
12,912
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2027394/binary-search-and-hash-table
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: def binary_search(positions, target): l = 0 r = len(positions) - 1 while l <= r: mid = (l + r) // 2 if positions[mid] < target: l = mid + 1 elif positions[mid] == target: l = mid + 1 elif positions[mid] > target: r = mid - 1 return positions[l] if l < len(positions) and positions[l] != target else -1 s_hash = defaultdict(list) for i, c in enumerate(s): s_hash[c].append(i) res = 0 for word in words: prev_position = -1 is_subseq = 0 for c in word: if c not in s_hash: is_subseq = False break else: cur_position = binary_search(s_hash[c], prev_position) if cur_position == -1: is_subseq = False break else: is_subseq += 1 prev_position = cur_position if is_subseq == len(word): res += 1 return res
number-of-matching-subsequences
binary search and hash table
Mujojo
0
88
number of matching subsequences
792
0.519
Medium
12,913
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1848857/Python3-Simple-python-code-with-index-faster-than-97
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: def isSubsequence(s, word): prev_idx = 0 for i in range(len(word)): try: tmp = s.index(word[i], prev_idx) prev_idx = tmp + 1 except: return False return True res = 0 for word in words: if isSubsequence(s, word): res += 1 return res
number-of-matching-subsequences
[Python3] Simple python code with index - faster than 97%
user7555GI
0
262
number of matching subsequences
792
0.519
Medium
12,914
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1813350/Python-easy-to-read-and-understand-or-is-subsequence
class Solution: def isSubsequence(self, s: str, t: str): if len(s) == 0: return True i, j = 0, 0 while i < len(t): if t[i] == s[j]: j = j+1 if j == len(s): return 1 i = i+1 return 0 def numMatchingSubseq(self, s: str, words: List[str]) -> int: ans, d = 0, {} for word in words: if word not in d: d[word] = self.isSubsequence(word, s) ans += d[word] return ans
number-of-matching-subsequences
Python easy to read and understand | is-subsequence
sanial2001
0
173
number of matching subsequences
792
0.519
Medium
12,915
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1496822/Building-Intuition-Step-by-Step-greater-Brute-Force-to-Accepted-Solution
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: #A brute force thinking - Generate all the subsequences of s and store them in an array #find how many of them occurs in the given array "words", count them and return them #But as we know, for a string of length n, we will have 2^n subsequences, #so the Time Complexity will definitely throw TLE #Lets try to think another way now #We can try to map the concept used in the problem Is Subsequence (Problem 392) here #Checking it out before this problem can be really useful as in this problem, we were given two separate strings #and we were supposed to check if one is a subsequence of other or not #Below Approach clears 41 / 52 test cases and then throws TLE count = 0 for k in words: i = 0 #to keep a check across k where k is an element of given array "words" j = 0 #to keep a check across s while j < len(s) and i < len(k): if k[i] == s[j]: #if words are similar, move through both the strings i += 1 j += 1 else: #if they are not, just move through characters of s j += 1 if i == len(k): #if i covers all elements of k, it means it is a subsequence count += 1 return count #Let us think of another way now -- (Taken help from discussion) #We will use find method of Python #string.find() method - Syntax -- string.find(substring, start, end) #start and end specifies the range you are searching your element in #if the character is not found, return -1 def is_subsequence(word): index = -1 for ch in word: index = s.find(ch , index+1) #search begins from 0th character #if index remains -1, it means we did not find the element if index == -1: return 0 #implies it is not a subsequence return 1 #implies it is a subsequence count = 0 for word in words: if is_subsequence(word): count += 1 return count
number-of-matching-subsequences
Building Intuition Step by Step --> Brute Force to Accepted Solution
aarushsharmaa
0
147
number of matching subsequences
792
0.519
Medium
12,916
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1290408/python3-Binary-search-and-index-hopping-sol-for-reference.
class Solution: def numMatchingSubseq(self, s: str, words) -> int: cnt = 0 for w in words: iter = 0 for c in w: next_idx = s[iter:].find(c) if next_idx < 0: iter = -1 break iter += next_idx + 1 if iter >= 0: cnt +=1 return cnt
number-of-matching-subsequences
[python3] Binary search & index hopping sol for reference.
vadhri_venkat
0
74
number of matching subsequences
792
0.519
Medium
12,917
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1290408/python3-Binary-search-and-index-hopping-sol-for-reference.
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: def isSubSeq(s1, s2): iter = 0 for index, val in enumerate(s1): if val == s2[iter]: iter += 1 if iter == len(s2): break return iter == len(s2) return sum([1 if isSubSeq(s, w) else 0 for w in words])
number-of-matching-subsequences
[python3] Binary search & index hopping sol for reference.
vadhri_venkat
0
74
number of matching subsequences
792
0.519
Medium
12,918
https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/discuss/1306028/Python3-binary-search
class Solution: def preimageSizeFZF(self, k: int) -> int: lo, hi = 0, 1 << 32 while lo <= hi: mid = lo + hi >> 1 x, y = mid, 0 while x: x //= 5 y += x if y < k: lo = mid + 1 elif y > k: hi = mid - 1 else: return 5 return 0
preimage-size-of-factorial-zeroes-function
[Python3] binary search
ye15
1
69
preimage size of factorial zeroes function
793
0.428
Hard
12,919
https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/discuss/1713153/PYTHON-FASTEST-SOLUTION-TILL-NOW-Faster-than-100-of-Python-Submissions
class Solution: def findzeroes(self,num): # This part takes log(n) time tmp=0 val=5 while val<=num: tmp+=num//val val*=5 return tmp def preimageSizeFZF(self, k: int) -> int: if k==0:return 5 high=5 while True: tmp=self.findzeroes(high) if tmp==k:return 5 if tmp>k:break high*=5 low=high//5 while low<=high: mid=(low+high)//2 tmp=self.findzeroes(mid) if tmp==k:return 5 if tmp<k:low=mid+1 else:high=mid-1 return 0
preimage-size-of-factorial-zeroes-function
PYTHON FASTEST SOLUTION TILL NOW Faster than 100% of Python Submissions
reaper_27
0
104
preimage size of factorial zeroes function
793
0.428
Hard
12,920
https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/discuss/1529910/Binary-search-80-speed
class Solution: def preimageSizeFZF(self, k: int) -> int: if k < 5: return 5 elif k == 5: return 0 left, right = 4, 5 * k while left < right: middle = (left + right) // 2 zeros = sum(middle // pow(5, p) for p in range(1, int(log(middle, 5)) + 1)) if zeros < k: left = middle + 1 elif zeros > k: right = middle - 1 else: return 5 return 0
preimage-size-of-factorial-zeroes-function
Binary search, 80% speed
EvgenySH
0
112
preimage size of factorial zeroes function
793
0.428
Hard
12,921
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/2269469/Python3-oror-int-array-7-lines-w-explanation-oror-TM%3A-98-49
class Solution: def validTicTacToe(self, board: List[str]) -> bool: # The two criteria for a valid board are: # 1) num of Xs - num of Os is 0 or 1 # 2) X is not a winner if the # of moves is even, and # O is not a winner if the # of moves is odd. d = {'X': 1, 'O': -1, ' ': 0} # transform the 1x3 str array to a 1x9 int array s = [d[ch] for ch in ''.join(board)] # Ex: ["XOX"," X "," "] --> [1,-1,1,0,1,0,0,0,0] sm = sum(s) if sm>>1: return False # <-- criterion 1 n = -3 if sm == 1 else 3 # <-- criterion 2. if n in {s[0]+s[1]+s[2], s[3]+s[4]+s[5], s[6]+s[7]+s[8], s[0]+s[3]+s[6], s[1]+s[4]+s[7], s[2]+s[5]+s[8], # the elements of the set are s[0]+s[4]+s[8], s[2]+s[4]+s[6]}: return False # the rows, cols, and diags return True # <-- both criteria are true
valid-tic-tac-toe-state
Python3 || int array, 7 lines, w/ explanation || T/M: 98%/ 49%
warrenruud
4
221
valid tic tac toe state
794
0.351
Medium
12,922
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/1838675/Modular-and-Extensible-Python-Solution-Beats-90
class Solution: def validTicTacToe(self, board: List[str]) -> bool: n = 3 rows = [0] * n cols = [0] * n diag = antidiag = balance = 0 def win(v): if v in rows or v in cols or v in [diag, antidiag]: return True return False for i in range(n): for j in range(n): if board[i][j] != " ": balance += 1 if board[i][j] == "X" else -1 rows[i] += 1 if board[i][j] == "X" else -1 cols[j] += 1 if board[i][j] == "X" else -1 if i == j: diag += 1 if board[i][j] == "X" else -1 if i + j == n - 1: antidiag += 1 if board[i][j] == "X" else -1 if not 0 <= balance <= 1: return False if balance == 0 and win(n): return False if balance == 1 and win(-n): return False return True
valid-tic-tac-toe-state
Modular and Extensible Python Solution - Beats 90%
totoslg
4
162
valid tic tac toe state
794
0.351
Medium
12,923
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/1119359/Straightforward-Game-Rules
class Solution: def validTicTacToe(self, board: List[str]) -> bool: row, col = len(board), len(board[0]) xCount, oCount = 0, 0 def checkStatusWinner(board): status = '' if board[0][2] == board[1][1] == board[2][0] !=' ': status = board[0][2] elif board[0][0] == board[1][1] == board[2][2] !=' ': status = board[0][0] elif board[0][0] == board[0][1] == board[0][2] !=' ': status = board[0][0] elif board[0][2] == board[1][2] == board[2][2] !=' ': status = board[0][2] elif board[2][2] == board[2][1] == board[2][0] !=' ': status = board[2][2] elif board[2][0] == board[1][0] == board[0][0] !=' ': status = board[2][0] elif board[0][1] == board[1][1] == board[2][1] !=' ': status = board[0][1] return status for i in range(row): for j in range(col): if board[i][j] == 'X': xCount += 1 elif board[i][j] == 'O': oCount += 1 if xCount < oCount or oCount+1 < xCount: return False status = checkStatusWinner(board) if status == 'X': return xCount == oCount+1 if status == 'O': return xCount == oCount return True
valid-tic-tac-toe-state
Straightforward Game Rules
anshulkapoor018
2
303
valid tic tac toe state
794
0.351
Medium
12,924
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/1927661/Python-logical-and-self-explanatory
class Solution: def validTicTacToe(self, board: List[str]) -> bool: Xs = Os = dia1 = dia2 = 0 row = [0] * 3 col = [0] * 3 for r in range(3): for c in range(3): if board[r][c] == 'X': Xs += 1 row[r] += 1 col[c] += 1 if c == r: dia1 += 1 if c + r == 2: dia2 += 1 elif board[r][c] == 'O': Os += 1 row[r] -= 1 col[c] -= 1 if c == r: dia1 -= 1 if c + r == 2: dia2 -= 1 if max(max(row), dia1, dia2, max(col)) == 3: #X is winning, then O cannot win or cannot move after X wins if Xs == Os + 1 and min(min(row), dia1, dia2, min(col)) > -3: return True elif min(min(row), dia1, dia2, min(col)) == -3: #O is winning, then X cannot win or cannot move after X wins if Xs == Os and max(max(row), dia1, dia2, max(col)) < 3: return True else: #nobody is winning if ((Xs == Os) or (Xs == Os + 1)): return True return False
valid-tic-tac-toe-state
Python logical and self-explanatory
gulugulugulugulu
1
106
valid tic tac toe state
794
0.351
Medium
12,925
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/1363242/24ms-(faster-than-97)-Python3-Solution
class Solution: def validTicTacToe(self, board: List[str]) -> bool: X,O = self.countSymbols(board) if O>X: #Os can't be greater than Xs return False elif abs(X-O)>1: #Difference can only be 1 return False elif X>O: #X can't have more moves than O if O is already won if self.checkTriads(board,'O'): return False else: #X and O can't have equal moves if X is winning if self.checkTriads(board,'X'): return False return True def countSymbols(self, board): X = 0 O = 0 for row in board: for i in row: if i == 'X': X+=1 elif i == 'O': O+=1 return X,O def checkTriads(self, board, sym='X'): #Checking for Hight triads i = 0 while i<3: if (board[0][i] == board[1][i] == board[2][i] == sym): return True i+=1 #Checking for width i=0 while i<3: if (board[i][0] == board[i][1] == board[i][2] == sym): return True i+=1 #Checking for diag. if (board[0][0] == board[1][1] == board[2][2] == sym): return True if (board[0][2] == board[1][1] == board[2][0] == sym): return True return False
valid-tic-tac-toe-state
24ms (faster than 97%) Python3 Solution
jayshukla0034
1
219
valid tic tac toe state
794
0.351
Medium
12,926
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/2842387/Edge-case-galore
class Solution: def validTicTacToe(self, board: List[str]) -> bool: # create function to determine number of wins for a player # keep track of number of tiles for each player # validate different edge cases for how players are allowed to win # time O(m * n) space O(1) def find_win(player): total = 0 return diagonal(player) + horizontal(player) + vertical(player) def diagonal(player): total = 0 flat = "" # tl diagnal for i, j in zip(range(3), range(3)): flat += board[i][j] if flat == player * 3: total += 1 flat = "" # bl diagonal for i, j in zip(reversed(range(3)), range(3)): flat += board[i][j] if flat == player * 3: total += 1 return total def horizontal(player): total = 0 for i in range(3): if board[i] == player * 3: total += 1 return total def vertical(player): total = 0 flat = "" for j in range(3): for i in range(3): flat += board[i][j] if flat == player * 3: total += 1 flat = "" return total x_win, o_win = find_win("X"), find_win("O") x = o = 0 for row in board: for space in row: if space == "X": x += 1 elif space == "O": o += 1 if x_win > 2: return False if o_win > 2: return False if x_win > 0 and o_win > 0: return False if x_win and x == o or o_win and x > o: return False if x < o or abs(x - o) > 1: return False return True
valid-tic-tac-toe-state
Edge case galore
andrewnerdimo
0
1
valid tic tac toe state
794
0.351
Medium
12,927
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/1892966/Python-straightforward-game-rule
class Solution: def validTicTacToe(self, board: List[str]) -> bool: rows = [0,0,0] cols = [0,0,0] n_x = 0 n_o = 0 diag = [0,0] for i in range(3): for j in range(3): if board[i][j] == "O": rows[i] -= 1 cols[j] -= 1 n_o += 1 diag[0] -= 1 if i == j else 0 diag[1] -= 1 if 2-i == j else 0 elif board[i][j] == "X": rows[i] += 1 cols[j] += 1 n_x += 1 diag[0] += 1 if i == j else 0 diag[1] += 1 if 2-i == j else 0 x_win = 1 if max(rows + cols + diag) == 3 else 0 o_win = 1 if min(rows + cols + diag) == -3 else 0 if x_win and o_win: return False if n_o > n_x or abs(n_o - n_x) > 1: return False if x_win and n_o == n_x: return False if o_win and n_x > n_o: return False return True
valid-tic-tac-toe-state
Python straightforward game rule
ganyue246
0
106
valid tic tac toe state
794
0.351
Medium
12,928
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/1663163/python-simple-solution
class Solution: def validTicTacToe(self, board: List[str]) -> bool: os, xs = 0, 0 for i in range(3): for j in range(3): if board[i][j] == 'O': os += 1 elif board[i][j] == 'X': xs += 1 if abs(os - xs) >= 2: return False elif os - xs == 1: return False # os == xs or xs == os + 1 if os + xs in [0, 1, 2]: return True bingo = defaultdict(int) for i in range(3): if board[i][0] == board[i][1] == board[i][2]: bingo[(i, 0)] += 1 bingo[(i, 1)] += 1 bingo[(i, 2)] += 1 t = board[i][0] if (t=='X' and os == xs) or (t == 'O' and xs == os+1): return False if board[0][i] == board[1][i] == board[2][i]: bingo[(0, i)] += 1 bingo[(1, i)] += 1 bingo[(2, i)] += 1 t = board[0][i] if (t=='X' and os == xs) or (t == 'O' and xs == os+1): return False if board[0][0] == board[1][1] == board[2][2]: bingo[(0, 0)] += 1 bingo[(1, 1)] += 1 bingo[(2, 2)] += 1 t = board[0][0] if (t=='X' and os == xs) or (t == 'O' and xs == os+1): return False if board[2][0] == board[1][1] == board[0][2]: bingo[(2, 0)] += 1 bingo[(1, 1)] += 1 bingo[(0, 2)] += 1 t = board[2][0] if (t=='X' and os == xs) or (t == 'O' and xs == os+1): return False res = 0 for b in bingo: v = bingo[b] if v >= 2: res += 1 return res <= 1
valid-tic-tac-toe-state
python simple solution
byuns9334
0
269
valid tic tac toe state
794
0.351
Medium
12,929
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/1360248/Simple-Python-solution-with-explanation
class Solution(object): def __init__(self): self.winIndexes =[[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]] self.board = [] def validTicTacToe(self, board): """ :type board: List[str] :rtype: bool """ countX, countO = 0, 0 for row in board: countX += row.count('X') countO += row.count('O') self.board += list(row) if not (countX==countO or countX==countO+1): return False xWin = self.win('X') oWin = self.win('O') if(xWin==oWin==True): return False if((countX==countO and xWin) or (countX==countO+1 and oWin)): return False return True def win(self, c): for first,second, third in self.winIndexes: if(self.board[first] == self.board[second] == self.board[third] == c): return True return False
valid-tic-tac-toe-state
Simple Python solution with explanation
songire
0
115
valid tic tac toe state
794
0.351
Medium
12,930
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/1105218/Python-or-with-comments
class Solution: def validTicTacToe(self, board: List[str]) -> bool: def iswinner(player): for r in range(len(board)): if board[r][0] == board[r][1] == board[r][2] == player: return True for c in range(len(board)): if board[0][c] == board[1][c] == board[2][c] == player: return True if board[0][0] == board[1][1] == board[2][2] == player or \ board[0][2] == board[1][1] == board[2][0] == player: return True return False xcount, ocount = 0, 0 for r in range(len(board)): for c in range(len(board)): if board[r][c].strip() == "X": xcount += 1 elif board[r][c].strip() == "O": ocount += 1 if ocount > xcount or xcount - ocount > 1: # at any point X's count should be more than Os and the diff should exactly 1 return False if iswinner("O"): if iswinner("X"): return False #both can't be winners return ocount == xcount #if O is winner count of Os should be exactly equal to X's if iswinner("X") and xcount != ocount + 1: #if X is winner count of Xs should be equal (O's count +1) return False return True
valid-tic-tac-toe-state
Python | with comments
timotheeechalamet
0
171
valid tic tac toe state
794
0.351
Medium
12,931
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/964518/Apply-Game-Rules-or-24ms-or-Well-fomred-and-Well-commented
class Solution: def validTicTacToe(self, board): s = str(board) x_cnt = s.count('X') o_cnt = s.count('O') # X is at most one step ahead if x_cnt == o_cnt or x_cnt == o_cnt + 1: pass else: return False # get all information x_win, o_win, count = self.win_cnt(board) # if o win, x and o should take same steps if o_win == 1 and x_cnt > o_cnt: return False # if x win, x should be one step ahead if x_win == 1 and x_cnt == o_cnt: return False # normal situation if count <= 1: return True # X can combine two win situation at 5th step if count == 2: return max(x_cnt, o_cnt) == 5 # impossible if count > 2: return False def win_cnt(self, board): x_win, o_win = 0, 0 # - x_win += board.count('XXX') o_win += board.count('OOO') # | line = ''.join([row[0] for row in board]) if line == 'XXX': x_win += 1 if line == 'OOO': o_win += 1 line = ''.join([row[1] for row in board]) if line == 'XXX': x_win += 1 if line == 'OOO': o_win += 1 line = ''.join([row[2] for row in board]) if line == 'XXX': x_win += 1 if line == 'OOO': o_win += 1 # \ line = ''.join([board[0][0], board[1][1], board[2][2]]) if line == 'XXX': x_win += 1 if line == 'OOO': o_win += 1 # / line = ''.join([board[2][0], board[1][1], board[0][2]]) if line == 'XXX': x_win += 1 if line == 'OOO': o_win += 1 return x_win, o_win, x_win + o_win
valid-tic-tac-toe-state
Apply Game Rules | 24ms | Well fomred and Well commented
steve-jokes
0
126
valid tic tac toe state
794
0.351
Medium
12,932
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/931176/Python3-valid-condition
class Solution: def validTicTacToe(self, board: List[str]) -> bool: anti = diag = diff = 0 freq = [0]*8 mp = {"O": -1, " ": 0, "X": 1} # increment &amp; decrement for i in range(3): for j in range(3): x = mp[board[i][j]] diff += x freq[i] += x freq[j+3] += x if i == j: freq[6] += x if i+j == 2: freq[7] += x xwin = 3 in freq owin = -3 in freq if xwin and owin or xwin and diff != 1 or owin and diff != 0: return False return 0 <= diff <= 1
valid-tic-tac-toe-state
[Python3] valid condition
ye15
0
137
valid tic tac toe state
794
0.351
Medium
12,933
https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/362216/Solution-in-Python-3-(beats-100)-(three-lines)
class Solution: def validTicTacToe(self, b: List[str]) -> bool: T, w = {'XXX':0, 'OOO':0}, "".join(b).count('X') - "".join(b).count('O') for i in [0,1,2]: T[b[0][i]+b[1][i]+b[2][i]], T[b[i][0]+b[i][1]+b[i][2]], T[b[0][2*i//2]+b[1][1]+b[2][2*(1-i//2)]] = 1, 1, 1 return False if (w not in [0,1]) or (T['XXX'] == 1 and w != 1) or (T['OOO'] == 1 and w != 0) else True - Junaid Mansuri (LeetCode ID)@hotmail.com
valid-tic-tac-toe-state
Solution in Python 3 (beats 100%) (three lines)
junaidmansuri
-9
407
valid tic tac toe state
794
0.351
Medium
12,934
https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/discuss/2304108/Python-or-Two-pointer-technique-or-Easy-solution
class Solution: def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: start,end = -1, -1 res = 0 for i in range(len(nums)): if nums[i] > right: start = end = i continue if nums[i] >= left: end = i res += end - start return res
number-of-subarrays-with-bounded-maximum
Python | Two pointer technique | Easy solution
__Asrar
2
79
number of subarrays with bounded maximum
795
0.527
Medium
12,935
https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/discuss/931418/Python3-Kadane-ish-algo
class Solution: def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: ans = inc = cnt = 0 for x in nums: if x < left: cnt += 1 elif left <= x <= right: inc = cnt = cnt + 1 else: inc = cnt = 0 ans += inc return ans
number-of-subarrays-with-bounded-maximum
[Python3] Kadane-ish algo
ye15
1
90
number of subarrays with bounded maximum
795
0.527
Medium
12,936
https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/discuss/931418/Python3-Kadane-ish-algo
class Solution: def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: queue = deque() ans, ii = 0, -1 for i in range(len(nums)+1): if i == len(nums) or nums[i] > right: while queue: k = queue.popleft() ans += (k - ii) * (i - k) ii = k ii = i elif left <= nums[i] <= right: queue.append(i) return ans
number-of-subarrays-with-bounded-maximum
[Python3] Kadane-ish algo
ye15
1
90
number of subarrays with bounded maximum
795
0.527
Medium
12,937
https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/discuss/1875782/Python-easy-to-read-and-understand-or-two-pointers
class Solution: def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: ans, prev = 0, 0 i, j = 0, 0 n = len(nums) for j in range(n): if left <= nums[j] <= right: prev = (j-i+1) ans += prev elif nums[j] < left: ans += prev else: i, prev = j+1, 0 return ans
number-of-subarrays-with-bounded-maximum
Python easy to read and understand | two-pointers
sanial2001
0
76
number of subarrays with bounded maximum
795
0.527
Medium
12,938
https://leetcode.com/problems/rotate-string/discuss/2369025/or-python3-or-ONE-LINE-or-FASTER-THAN-99-or
class Solution: def rotateString(self, s: str, goal: str) -> bool: return len(s) == len(goal) and s in goal+goal
rotate-string
✅ | python3 | ONE LINE | FASTER THAN 99% | 🔥💪
sahelriaz
18
628
rotate string
796
0.542
Easy
12,939
https://leetcode.com/problems/rotate-string/discuss/356624/Solution-in-Python-3-(one-line)
class Solution: def rotateString(self, A: str, B: str) -> bool: return (A in B*2) and (len(A) == len(B)) - Junaid Mansuri (LeetCode ID)@hotmail.com
rotate-string
Solution in Python 3 (one line)
junaidmansuri
5
971
rotate string
796
0.542
Easy
12,940
https://leetcode.com/problems/rotate-string/discuss/1116435/Python-3-Pretty-simple-solution
class Solution: def rotateString(self, A: str, B: str) -> bool: if len(A) != len(B): return False if A == B: return True # Copy the original string to know when we've rotated back to the origin original_A = A while A: # Each iteration rotates A one character to the right A = A[-1:] + A[:-1] if A == B: return True if A == original_A: return False
rotate-string
Python 3 - Pretty simple solution
edgyporcupine
2
291
rotate string
796
0.542
Easy
12,941
https://leetcode.com/problems/rotate-string/discuss/1638385/Python-Fast-and-Easy-(bEATS-85)
class Solution: def rotateString(self, s: str, goal: str) -> bool: if len(s) != len(goal) or set(s) != set(goal): return False goal += ''.join(goal) return s in goal
rotate-string
Python Fast and Easy (bEATS 85%)
ElyasGoli
1
165
rotate string
796
0.542
Easy
12,942
https://leetcode.com/problems/rotate-string/discuss/1337272/Python-One-Line-easiest!
class Solution(object): def rotateString(self, A, B): return len(A)==len(B) and B in A+A
rotate-string
Python One Line, easiest!
aishwaryanathanii
1
130
rotate string
796
0.542
Easy
12,943
https://leetcode.com/problems/rotate-string/discuss/2751571/Simple-Python-Solution
class Solution: def rotateString(self, A: str, B: str) -> bool: if len(A) != len(B): return False if A == B: return True for _ in range(len(B) - 1): B = B[1:] + B[0] if A == B: return True return False
rotate-string
Simple Python Solution
dnvavinash
0
3
rotate string
796
0.542
Easy
12,944
https://leetcode.com/problems/rotate-string/discuss/2742772/Python-Easy
class Solution: def rotateString(self, s: str, goal: str) -> bool: for i in range(len(s)): tmp = s[i + 1:] + s[:i +1] if (tmp == goal): return True return False
rotate-string
Python Easy
lucasschnee
0
7
rotate string
796
0.542
Easy
12,945
https://leetcode.com/problems/rotate-string/discuss/2718455/using-python
class Solution: def rotateString(self, s: str, goal: str) -> bool: t=list(s) for i in range(len(s)): p=s[1:]+t[i] if p== goal: return True print(p) s=p return False
rotate-string
using python
sindhu_300
0
6
rotate string
796
0.542
Easy
12,946
https://leetcode.com/problems/rotate-string/discuss/2703682/python-time-complexity-O(n)-not-one-line-code
class Solution: def rotateString(self, s: str, goal: str) -> bool: if len(s) != len(goal): return False temp_string = s*2 count = 0 for i in range(len(temp_string)): next_temp_string = temp_string[i+1] if i+1 <= (len(temp_string)-1) else "" next_goal = goal[count+1] if count+1 <= (len(goal)-1) else "" if count == (len(goal) -1): return True if temp_string[i] == goal[count] and next_temp_string == next_goal: count += 1 else: count = 0 return False
rotate-string
python time complexity O(n), not one line code
haswanth_reddy
0
9
rotate string
796
0.542
Easy
12,947
https://leetcode.com/problems/rotate-string/discuss/2504940/Python-Solution
class Solution: def rotateString(self, s: str, goal: str) -> bool: for i in range(0,len(s)): str1=s[i+1:]+s[:i+1] if str1==goal: return True
rotate-string
Python Solution
deepanshu704281
0
13
rotate string
796
0.542
Easy
12,948
https://leetcode.com/problems/rotate-string/discuss/2334964/Python-easy-solution-for-beginners-using-slicing
class Solution: def rotateString(self, s: str, goal: str) -> bool: for i in range(len(s)): if s[i+1:] + s[:i+1] == goal: return True return False
rotate-string
Python easy solution for beginners using slicing
alishak1999
0
74
rotate string
796
0.542
Easy
12,949
https://leetcode.com/problems/rotate-string/discuss/2280975/Simple-easy-to-understand-Python-100-fast
class Solution: def rotateString(self, s: str, goal: str) -> bool: if len(s) != len(goal): return False idx = [] for i in range(len(s)): if s[i] == goal[0] and s[i:]+s[:i] == goal: return True return False
rotate-string
Simple easy to understand Python 100% fast
harsh30199
0
62
rotate string
796
0.542
Easy
12,950
https://leetcode.com/problems/rotate-string/discuss/2215375/Easy-Python-Code
class Solution: def rotateString(self, s: str, goal: str) -> bool: tr = s rot = s[1:]+s[:1] print(rot) while rot != tr: if rot == goal: return 1 rot = rot[1:]+rot[:1] return 0
rotate-string
Easy Python Code
AnUp_00900
0
33
rotate string
796
0.542
Easy
12,951
https://leetcode.com/problems/rotate-string/discuss/2142597/Python-Simple-KMP-Solution
class Solution: def rotateString(self, s: str, goal: str) -> bool: if len(s) != len(goal): return False txt = s + s n, m = len(txt), len(goal) lps = self.build_lps(goal) i, j = 0, 0 while i < n: if txt[i] == goal[j] : i, j = i + 1, j + 1 if j == m: return True else: if j == 0: i += 1 else: j = lps[j-1] return False def build_lps(self, pattern): lps = [0] * len(pattern) prev_lps, i = 0, 1 while i < len(pattern): if pattern[i] == pattern[prev_lps]: lps[i] = prev_lps + 1 prev_lps, i = prev_lps + 1, i + 1 else: if prev_lps == 0: lps[i] = 0 i += 1 else: prev_lps = lps[prev_lps - 1] return lps
rotate-string
Python - Simple KMP Solution
ErickMwazonga
0
53
rotate string
796
0.542
Easy
12,952
https://leetcode.com/problems/rotate-string/discuss/2098138/Simple-index-based-left-shift-97.08-faster-no-extra-space
class Solution: def rotateString(self, s: str, goal: str) -> bool: if s == goal: return True for i in range(1, len(s)): s = s[1:] + s[0] if s == goal: return True return False
rotate-string
Simple index based left shift 97.08 % faster no extra space
ankurbhambri
0
52
rotate string
796
0.542
Easy
12,953
https://leetcode.com/problems/rotate-string/discuss/2031364/Python-solution
class Solution: def rotateString(self, s: str, goal: str) -> bool: for i in range(len(s)): if s[i:]+s[:i] == goal: return True else: return False
rotate-string
Python solution
StikS32
0
51
rotate string
796
0.542
Easy
12,954
https://leetcode.com/problems/rotate-string/discuss/1766572/91.37-faster-runtime-or-99.62-faster-memory-or-python-3-or-O(n)
class Solution: def rotateString(self, s: str, goal: str) -> bool: i = 0 while(i<len(s)): goal = goal[-1]+goal[:-1] if s == goal: return True i += 1 return False
rotate-string
91.37% faster runtime | 99.62% faster memory | python 3 | O(n)
Coding_Tan3
0
118
rotate string
796
0.542
Easy
12,955
https://leetcode.com/problems/rotate-string/discuss/1723653/Python-Easy-Solution
class Solution: def rotateString(self, s: str, goal: str) -> bool: for i in range(len(s)): if s[i] == goal[0]: # check if goal's first letter is in s if s[i:]+s[:i] == goal: # cut string till i from front and add in the end return True return False
rotate-string
Python Easy Solution
priyanshu_leet
0
146
rotate string
796
0.542
Easy
12,956
https://leetcode.com/problems/rotate-string/discuss/1569040/Python-Solution-or-Faster-Than-99.37-or-Memory-Usage-Beats-92.14-or
class Solution: def rotateString(self, s: str, goal: str) -> bool: s=list(s) for i in range(len(s)): s.insert(0, s.pop(-1)) if "".join(s)==goal: return(True) break return(False)
rotate-string
Python Solution | Faster Than 99.37% | Memory Usage Beats 92.14% |
Captain_Leo
0
80
rotate string
796
0.542
Easy
12,957
https://leetcode.com/problems/rotate-string/discuss/1478129/Python-3-solution
class Solution: def rotateString(self, s: str, goal: str) -> bool: for i in range(len(s)): x = s[0] s = s.replace(s[0], '', 1) + x if s == goal: return True return False
rotate-string
Python 3 solution
shubhamPanchal
0
43
rotate string
796
0.542
Easy
12,958
https://leetcode.com/problems/rotate-string/discuss/1428122/Python3-Unique-Solution-Faster-Than-93.68-Memory-Less-Than-91.83
class Solution: def rotateString(self, s: str, goal: str) -> bool: if len(s) != len(goal): return False l = len(goal) d, i = defaultdict(set), 0 while i < l: d[goal[i]].add(goal[(i + 1) % l]) i += 1 i = 0 while i < l: found = False if s[(i + 1) % l] in d[s[i]]: found = True if not found: return False i += 1 return True
rotate-string
Python3 Unique Solution, Faster Than 93.68%, Memory Less Than 91.83%
Hejita
0
50
rotate string
796
0.542
Easy
12,959
https://leetcode.com/problems/rotate-string/discuss/1225413/Python3-simple-solution-faster-than-94-users
class Solution: def rotateString(self, s: str, goal: str) -> bool: if s == goal: return True for i,j in enumerate(s): if j == goal[0]: if (s[i:] + s[:i]) == goal:return True return False
rotate-string
Python3 simple solution faster than 94% users
EklavyaJoshi
0
47
rotate string
796
0.542
Easy
12,960
https://leetcode.com/problems/rotate-string/discuss/1208636/Python-Easy-to-Understand-Faster-than-99.87
class Solution: def rotateString(self, s: str, goal: str) -> bool: if len(s)!=len(goal): return False s=s*2 if goal in s: return True return False
rotate-string
Python Easy to Understand Faster than 99.87%
mk_mohtashim
0
186
rotate string
796
0.542
Easy
12,961
https://leetcode.com/problems/rotate-string/discuss/1136343/simple-and-easy-python
class Solution: def rotateString(self, A: str, B: str) -> bool: if A==B: return True for i in range(len(A)): if B == A[i:]+A[:i]: return True return False
rotate-string
simple and easy python
pheobhe
0
37
rotate string
796
0.542
Easy
12,962
https://leetcode.com/problems/rotate-string/discuss/1093976/Python-solution
class Solution: def rotateString(self, A: str, B: str) -> bool: if not A and not B: return True a = A for char in A: a = a[1:] + char if a == B: return True return False
rotate-string
Python solution
i2V0T3VOAqCfe
0
102
rotate string
796
0.542
Easy
12,963
https://leetcode.com/problems/rotate-string/discuss/579557/python
class Solution: def rotateString(self, A: str, B: str) -> bool: if len(A) != len(B): return False if A == B: return True for i in range(len(B)): if (A[i :] + A[0 : i]) == B: return True return False
rotate-string
python
CodeRot
0
96
rotate string
796
0.542
Easy
12,964
https://leetcode.com/problems/rotate-string/discuss/1328251/Python3-dollarolution
class Solution: def rotateString(self, s: str, goal: str) -> bool: if len(s) == len(goal): x = 2*s return goal in x return False
rotate-string
Python3 $olution
AakRay
-1
89
rotate string
796
0.542
Easy
12,965
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/752799/Python-simple-BFS-solution-explained
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: q = [[0]] result = [] target = len(graph) - 1 while q: temp = q.pop(0) if temp[-1] == target: result.append(temp) else: for neighbor in graph[temp[-1]]: q.append(temp + [neighbor]) return result
all-paths-from-source-to-target
Python simple BFS solution explained
spec_he123
6
787
all paths from source to target
797
0.815
Medium
12,966
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/298345/Python-faster-than-100-76-ms
class Solution(object): def __init__(self): self.memo = {} def allPathsSourceTarget(self, graph): """ :type graph: List[List[int]] :rtype: List[List[int]] """ self.memo = {len(graph)-1:[[len(graph)-1]]} def calc(N): if N in self.memo: return self.memo[N] a = [] for n in graph[N]: for path in calc(n): a.append([N]+path) self.memo[N] = a return a return calc(0)
all-paths-from-source-to-target
Python - faster than 100%, 76 ms
il_buono
3
865
all paths from source to target
797
0.815
Medium
12,967
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1734565/Python-ll-Iterative-DFS-Using-Stack
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: n = len(graph) stack = [[0]] paths = [] while stack: path = stack.pop() vertex = path[-1] if vertex == n-1: paths.append(path.copy()) for nodes in graph[vertex]: stack.append( path.copy()+[nodes]) return paths
all-paths-from-source-to-target
Python ll Iterative DFS Using Stack
morpheusdurden
2
193
all paths from source to target
797
0.815
Medium
12,968
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1600955/Extremely-clean-and-backtracking-based-DFS-in-Python
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: def dfs(path: List[int]): if path[-1] == len(graph) - 1: yield path else: for v in graph[path[-1]]: yield from dfs(path + [v]) return list(dfs([0]))
all-paths-from-source-to-target
Extremely clean and backtracking-based DFS in Python
mousun224
2
160
all paths from source to target
797
0.815
Medium
12,969
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1600355/Python3-RECURSION-Explained
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: n = len(graph) - 1 res = [] def helper(cur, acc): acc.append(cur) if cur == n: res.append(acc) return for next in graph[cur]: helper(next, list(acc)) helper(0, []) return res
all-paths-from-source-to-target
[Python3] RECURSION, Explained
artod
2
114
all paths from source to target
797
0.815
Medium
12,970
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1814971/Python-3-DFS-or-Backtracking-Simple-Solution-or-Beats-97
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: paths = [] visited = [False]*len(graph) def DFS(graph, src, dest, path): visited[src] = True path.append(src) if src == dest: paths.append(path[:]) else: for node in graph[src]: if not visited[node]: DFS(graph, node, dest, path) path.pop() visited[src] = False DFS(graph, 0, len(graph)-1, []) return paths
all-paths-from-source-to-target
[Python 3] DFS | Backtracking Simple Solution | Beats 97%
hari19041
1
77
all paths from source to target
797
0.815
Medium
12,971
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1422090/Python3-Simple-DFS-with-Backtracking-readable-solution-with-comments.
class Solution: def dfs(self, graph: List[List[int]], is_visited: set, node: int, target: int, stack: List, paths: List): # Return if node already visited if node in is_visited: return # Add node to visited set is_visited.add(node) # Add node to stack stack.append(node) # If node is the target, copy the current stack to paths if node == target: paths.append(stack.copy()) else: # if node is not the target then run dfs for adjacent node/s for adj_node in graph[node]: if adj_node not in is_visited: self.dfs(graph, is_visited, adj_node, target, stack, paths) # Pop the node from the stack: Backtracking stack.pop() # Remove node from visited set: Backtracking is_visited.remove(node) return def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: n = len(graph) paths = [] stack = [] is_visited = set() self.dfs(graph, is_visited, 0, n-1, stack, paths) return paths
all-paths-from-source-to-target
[Python3] Simple DFS with Backtracking, readable solution with comments.
ssshukla26
1
62
all paths from source to target
797
0.815
Medium
12,972
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1092481/Python3-(99)-DFS-Memo
class Solution: def __init__(self): self.seen = None self.memo = None self.end = None def dfs(self, graph, node): self.seen[node] = True if node == self.end: self.memo[node].append([node]) else: for nbor in graph[node]: if not self.seen[nbor]: self.dfs(graph, nbor) if self.memo[nbor]: for tail in self.memo[nbor]: self.memo[node].append([node] + tail) def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: if not graph: return None self.seen = [False for _ in range(len(graph))] self.memo = [[] for _ in range(len(graph))] self.end = len(graph) - 1 self.dfs(graph, 0) return self.memo[0]
all-paths-from-source-to-target
[Python3] (99%) DFS Memo
valige7091
1
177
all paths from source to target
797
0.815
Medium
12,973
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1058204/Python-Backtracking
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: def dfs_with_backtracking(node, path): seen.add(node) # add node to seen if node == len(graph)-1: # our termination condition result.append(path) return for next_node in graph[node]: # enumerate over next nodes if next_node in seen: continue # skip any invalid choices seen.add(next_node) dfs_with_backtracking(next_node, path+[next_node]) seen.remove(next_node) seen = set() result = [] dfs_with_backtracking(0, [0]) return result
all-paths-from-source-to-target
Python Backtracking
dev-josh
1
147
all paths from source to target
797
0.815
Medium
12,974
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/753537/Python3-dfs-with-memo
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: def fn(n): """Populate ans through dfs""" stack.append(n) if n == len(graph)-1: ans.append(stack.copy()) for nn in graph[n]: fn(nn) stack.pop() ans, stack = [], [] fn(0) return ans
all-paths-from-source-to-target
[Python3] dfs with memo
ye15
1
138
all paths from source to target
797
0.815
Medium
12,975
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/753537/Python3-dfs-with-memo
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: ans = [] stack = [(0, [0])] while stack: x, path = stack.pop() if x == len(graph)-1: ans.append(path) else: for xx in graph[x]: stack.append((xx, path+[xx])) return ans
all-paths-from-source-to-target
[Python3] dfs with memo
ye15
1
138
all paths from source to target
797
0.815
Medium
12,976
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/753537/Python3-dfs-with-memo
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: @cache def fn(n): """Return path from given node to dst node.""" if n == len(graph)-1: return [[n]] ans = [] for nn in graph[n]: ans.extend([[n] + x for x in fn(nn)]) return ans return fn(0)
all-paths-from-source-to-target
[Python3] dfs with memo
ye15
1
138
all paths from source to target
797
0.815
Medium
12,977
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/753537/Python3-dfs-with-memo
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: indeg = [0]*len(graph) for val in graph: for x in val: indeg[x] += 1 queue = deque(i for i, x in enumerate(indeg) if x == 0) dp = [[] for _ in range(len(graph))] while queue: x = queue.popleft() if x == 0: dp[0].append([0]) for xx in graph[x]: for seq in dp[x]: dp[xx].append(seq + [xx]) indeg[xx] -= 1 if indeg[xx] == 0: queue.append(xx) return dp[-1]
all-paths-from-source-to-target
[Python3] dfs with memo
ye15
1
138
all paths from source to target
797
0.815
Medium
12,978
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/667114/Short-Python-BFS-beats-99
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: q = deque([[0]]) paths = [] while q: curr = q.popleft() if curr[-1] == len(graph) - 1: paths.append(curr) continue for child in graph[curr[-1]]: q.append([*curr, child]) return paths
all-paths-from-source-to-target
Short Python BFS - beats 99%
auwdish
1
210
all paths from source to target
797
0.815
Medium
12,979
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2838410/Python-O(V-%2B-E)-solution-Accepted
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: queue = [[0]] ans = [] # step = 1 while queue: curr_path = queue.pop(0) if curr_path[-1] == len(graph) - 1: ans.append(curr_path) continue for neight in graph[curr_path[-1]]: queue.append(curr_path + [neight]) # print(f"step - {step}") # for el in queue: # print(el) # step += 1 return ans
all-paths-from-source-to-target
Python O(V + E) solution [Accepted]
lllchak
0
5
all paths from source to target
797
0.815
Medium
12,980
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2831434/Simple-DFS-Python-Solution-(BEATS-80)
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: result = [] self.dfs(graph, 0, len(graph) - 1, [0], result) return result def dfs(self, graph, start, dest, path, result): if start == dest: result.append(path.copy()) for neighbor in graph[start]: path.append(neighbor) self.dfs(graph, neighbor, dest, path, result) path.pop()
all-paths-from-source-to-target
Simple DFS Python Solution (BEATS 80%)
roygarcia
0
3
all paths from source to target
797
0.815
Medium
12,981
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2819387/Python-DFS-solution
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: #edges cases: if not graph: return [] # build di-graph d = {} for i in range(len(graph)): d[i] = graph[i] # apply dfs n = len(graph) stack = [(0, [0])] # store the node and the path leading to it res = [] while stack: node, path = stack.pop() if node == n-1: res.append(path) for ne in d[node]: stack.append((ne, path+[ne])) return res
all-paths-from-source-to-target
Python DFS solution
taoxinyyyun
0
5
all paths from source to target
797
0.815
Medium
12,982
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2818077/Easy-python-solution-using-DFS
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: res = [] def dfs(graph, src, temp, n): temp.append(src) if src == n: res.append(temp) for node in graph[src]: dfs(graph, node, temp[:], n) dfs(graph, 0, [], len(graph)-1) return res
all-paths-from-source-to-target
Easy python solution using DFS
i-haque
0
4
all paths from source to target
797
0.815
Medium
12,983
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2816314/Python-3-DFS-Solution
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: # With new list created for each path def dfs(curr, path): if curr == n - 1: res.append(path) for neighbor in graph[curr]: dfs(neighbor, path + [neighbor]) # With path removal def dfs(curr, path): # Start traversing, append node to path path.append(curr) if curr == n - 1: res.append(list(path)) path.pop() return for neighbor in graph[curr]: dfs(neighbor, path) # Finished traversing, remove the node from path path.pop() n = len(graph) res = [] dfs(0, []) return res
all-paths-from-source-to-target
Python 3 DFS Solution
Farawayy
0
2
all paths from source to target
797
0.815
Medium
12,984
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2815744/Python3-Use-DFS-to-search-out-all-paths-in-a-DAG.
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: # Method: DFS. No cycle, so no need to use visited array. res = [] cur_path = [] def dfs(x): if x == len(graph) - 1: res.append(cur_path.copy()) return for i in graph[x]: cur_path.append(i) dfs(i) cur_path.pop() cur_path.append(0) dfs(0) return res
all-paths-from-source-to-target
[Python3] Use DFS to search out all paths in a DAG.
Cceline00
0
2
all paths from source to target
797
0.815
Medium
12,985
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2815167/on-path-backtrack-in-python
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: res = [] # visited, onpath = [],[] def traverse(node, onpath): # onpath.append(node) if node == len(graph)-1: res.append(onpath.copy()) return for n in graph[node]: traverse(n,onpath+[n]) # onpath.pop() return traverse(0,[0]) return res
all-paths-from-source-to-target
on path backtrack in python
ychhhen
0
3
all paths from source to target
797
0.815
Medium
12,986
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2777888/Python-backtrack
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: result = [] def backtrack(i, cur): nonlocal result if i == len(graph) - 1: result.append(list(cur)) return for j in graph[i]: cur.append(j) backtrack(j, cur) cur.pop() return backtrack(0, [0]) return result
all-paths-from-source-to-target
[Python] backtrack
i-hate-covid
0
5
all paths from source to target
797
0.815
Medium
12,987
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2739208/Python-3-Solution-DFS
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: last_node = len(graph) - 1 ans = [] def dfs(graph, currentVertex, visited): visited.append(currentVertex) for vertex in graph[currentVertex]: if vertex not in visited: dfs(graph, vertex, visited.copy()) if visited[0] == 0 and visited[-1] == last_node: ans.append(visited) dfs(graph, 0, []) return ans
all-paths-from-source-to-target
Python 3 Solution - DFS
sipi09
0
6
all paths from source to target
797
0.815
Medium
12,988
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2731420/pythonornormal-answer
class Solution: def allPathsSourceTarget(self, graph): n = len(graph) ans = [] visited = set() temp = [0] # traverse the graph for child in graph[0]: self.dfs(child, temp[:], ans, graph, n) return ans def dfs(self, start, temp, ans, graph, n): if start == n-1: # reached the destination. temp.append(start) ans.append(temp[:]) return # Append the path temp.append(start) # traverse the graph for child in graph[start]: self.dfs(child, temp[:], ans, graph, n)
all-paths-from-source-to-target
python|normal answer
lucy_sea
0
3
all paths from source to target
797
0.815
Medium
12,989
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2711962/Python-solution-or-DFS
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: ans = [] def dfs(index, path): if index == len(graph) - 1: ans.append(path) return for i in range(len(graph[index])): dfs(graph[index][i], path + [graph[index][i]]) dfs(0,[0]) return ans
all-paths-from-source-to-target
Python solution | DFS
maomao1010
0
14
all paths from source to target
797
0.815
Medium
12,990
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2699655/Python3-Simple-Solution
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: dest = len(graph) - 1 res = [] def DFS(i, arr): temp = arr.copy() temp.append(i) if dest == i: res.append(temp) for num in graph[i]: DFS(num, temp) DFS(0, []) return res
all-paths-from-source-to-target
Python3 Simple Solution
mediocre-coder
0
4
all paths from source to target
797
0.815
Medium
12,991
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2437879/All-Paths-from-source-to-target-oror-Python3-oror-DFS
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: ans = [] src = 0 target = len(graph) - 1 self.dfs(src, target, graph, [0], ans) return ans def dfs(self, src, target, graph, path, ans): if(src == target): ans.append(list(path)) return for nbr in graph[src]: path.append(nbr) self.dfs(nbr, target, graph, path, ans) path.pop()
all-paths-from-source-to-target
All Paths from source to target || Python3 || DFS
vanshika_2507
0
10
all paths from source to target
797
0.815
Medium
12,992
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2428747/Python-Solution-or-Recursive-DFS-or-90-Faster-or-DAG-Path-Stack
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: def generate(node,path): # if we have reached target node if node == n-1: # append current path as an element to finalAns self.finalAns.append(path.copy()) else: # recurse for all children of current node for child in graph[node]: generate(child,path+[child]) # driver code n = len(graph) self.finalAns = [] generate(0,[0]) return self.finalAns
all-paths-from-source-to-target
Python Solution | Recursive DFS | 90% Faster | DAG Path Stack
Gautam_ProMax
0
49
all paths from source to target
797
0.815
Medium
12,993
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2416563/Short-and-fast-Backtracking-python-solution-beats-88
class Solution(object): def allPathsSourceTarget(self, graph): l=len(graph) def fn(i,d={}): if i in d: return d[i] if i==l-1: return [[l-1]] res=[] for j in graph[i]: inter=fn(j) for k in inter: res.append([i]+k) d[i]=res return res return fn(0)
all-paths-from-source-to-target
Short and fast Backtracking python solution beats 88%
babashankarsn
0
25
all paths from source to target
797
0.815
Medium
12,994
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2352642/Python3-O(N)-Time-Solution-Solved-using-BFS-%2B-Queue
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: #I was originally going to try tackling BFS manner but DFS seemed more intuitive and #easier to implement in more readable code! #Runtime: In worst case, we have to process each and every node through queue! -> O(n) #Space: O(n^2), due to our answer array! #our graph is adjacency list represented! #graph[i] is ith node's adjacency list containing all nodes that is connected to node i #by directed edge from node i to its' neighboring node! #initialize num_nodes in DAG! n = len(graph) #intialize answer ans = [] queue = deque() queue.append([0]) while queue: cur = queue.popleft() last_node = cur[len(cur)-1] if(last_node == n-1): ans.append(cur) else: neighbors = graph[last_node] for nei in neighbors: tmp = cur tmp = tmp + [nei] queue.append(tmp) return ans
all-paths-from-source-to-target
Python3 O(N) Time Solution Solved using BFS + Queue
JOON1234
0
35
all paths from source to target
797
0.815
Medium
12,995
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2352627/Python3-O(n)-Time-Solution-Using-DFS-%2B-Recursion
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: #I was originally going to try tackling BFS manner but DFS seemed more intuitive and #easier to implement in more readable code! #Runtime: O(n), where we have to visit every single node once to gaurantee all paths #from node 0 to node n- 1! #Space: We use mainly extra space in our recursive stack call frame -> O(n + n*n), the #longest path of recursion tree will consist of n nodes. However, the ans array will #have at most n distinct paths from source to destination and each distinct path can #have at most n nodes! -> O(n^2) #our graph is adjacency list represented! #graph[i] is ith node's adjacency list containing all nodes that is connected to node i #by directed edge from node i to its' neighboring node! #initialize num_nodes in DAG! n = len(graph) #intialize answer ans = [] def dfs(node, cur_path): nonlocal ans #check if node is n-1th node! if(node == n - 1): ans.append(cur_path + [node]) return #otherwise, check each of neighboring paths from current node! else: neighbors = graph[node] #in worst case, one node can have neighbor to all other n-1 nodes! #this means for loop can run at most around n times! for neighbor in neighbors: #the pre-path to reach neighbor is cur_path + given node! dfs(neighbor, cur_path + [node]) return dfs(0, []) return ans
all-paths-from-source-to-target
Python3 O(n) Time Solution Using DFS + Recursion
JOON1234
0
20
all paths from source to target
797
0.815
Medium
12,996
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2343359/Python3-Backtracking-solution-(not-DFS)
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: res = [] self.explore(graph, graph[0], [0], res) return res def explore(self, graph, candidates, step, res): if step[-1] == len(graph)-1: res.append(list(step)) else: for i in range(len(candidates)): step.append(candidates[i]) self.explore(graph, graph[candidates[i]], step, res) step.pop()
all-paths-from-source-to-target
Python3 -- Backtracking solution (not DFS)
tahir3
0
71
all paths from source to target
797
0.815
Medium
12,997
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2329932/Beats-97-Beginner-Python-DFS
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: paths = [] target = len(graph) - 1 def dfs(currentNode=0, currentPath=[0]): if currentNode == target: nonlocal paths paths.append(currentPath) return nextNodes = graph[currentNode] for nextNode in nextNodes: dfs(nextNode, currentPath + [ nextNode ]) dfs() return paths
all-paths-from-source-to-target
Beats 97% - Beginner Python - DFS
7yler
0
71
all paths from source to target
797
0.815
Medium
12,998
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2265645/Clear-python-solution-with-DFS-traversal
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: # all possible paths to end node self.res = [] # current path to end node path = [] self.traverse(graph, 0, path) return self.res def traverse(self, graph, s, path): # append current node s to path path.append(s) n = len(graph) if (s == n - 1): self.res.append(path.copy()); # traverse all neighbouring nodes of node s for v in graph[s]: self.traverse(graph, v, path) # remove the last children in the current path, starting from the leaf node in bottom-up pattern path.pop(-1)
all-paths-from-source-to-target
Clear python solution with DFS traversal
leqinancy
0
9
all paths from source to target
797
0.815
Medium
12,999