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/rabbits-in-forest/discuss/1770947/Python-O(n)-concise-solution-with-explanation
class Solution: def numRabbits(self, answers): count_dict = Counter(answers) ans = 0 for n, c in count_dict.items(): if c % (n+1) == 0: group = (c // (n+1)) else: group = (c // (n+1)) + 1 ans += (n+1) * group return ans
rabbits-in-forest
Python O(n) concise solution with explanation
caitlinttl
0
74
rabbits in forest
781
0.552
Medium
12,700
https://leetcode.com/problems/rabbits-in-forest/discuss/1724925/Python-3-easy-two-line-solution-O(n)-time-O(n)-space
class Solution: def numRabbits(self, answers: List[int]) -> int: counter = collections.Counter(answers) return sum(math.ceil(freq / (answer + 1)) * (answer + 1) for answer, freq in counter.items())
rabbits-in-forest
Python 3, easy two line solution, O(n) time, O(n) space
dereky4
0
68
rabbits in forest
781
0.552
Medium
12,701
https://leetcode.com/problems/rabbits-in-forest/discuss/1680015/Easy-Python
class Solution: def numRabbits(self, answers: List[int]) -> int: nums = {} for num in answers: if num in nums: nums[num] -= 1 if nums[num] == 0: del nums[num] else: if num != 0: nums[num] = num return sum(nums.values())+ len(answers)
rabbits-in-forest
Easy Python
neth_37
0
25
rabbits in forest
781
0.552
Medium
12,702
https://leetcode.com/problems/rabbits-in-forest/discuss/1622823/Python-Solution-faster-than-99.68-of-python-3-solutions
class Solution: def numRabbits(self, answers: List[int]) -> int: ans=0 d=defaultdict(lambda:0) for i in answers:d[i]+=1 for key,value in d.items(): tmp=value//(key+1) if value%(key+1)!=0:tmp+=1 #print('for key=',key,'value=',value,'tmp=',tmp) ans+=tmp*(key+1) return ans
rabbits-in-forest
Python Solution faster than 99.68% of python 3 solutions
reaper_27
0
60
rabbits in forest
781
0.552
Medium
12,703
https://leetcode.com/problems/rabbits-in-forest/discuss/1215698/python-easy-and-concise-solution
class Solution(object): def numRabbits(self, answers): c=collections.Counter(answers) res=0 for answer in c: if c[answer]%(answer+1)==0: res+=(c[answer]//(answer+1))*(answer+1) else : res+=(c[answer]//(answer+1)+1)*(answer+1) return res
rabbits-in-forest
python easy and concise solution
aayush_chhabra
0
78
rabbits in forest
781
0.552
Medium
12,704
https://leetcode.com/problems/rabbits-in-forest/discuss/925818/Python3-O(N)-via-hash
class Solution: def numRabbits(self, answers: List[int]) -> int: ans = 0 cnt = defaultdict(int) for x in answers: if not cnt[x] % (1 + x): ans += 1 + x # reached capacity & update ans cnt[x] += 1 return ans
rabbits-in-forest
[Python3] O(N) via hash
ye15
0
55
rabbits in forest
781
0.552
Medium
12,705
https://leetcode.com/problems/transform-to-chessboard/discuss/1305763/Python3-alternating-numbers
class Solution: def movesToChessboard(self, board: List[List[int]]) -> int: n = len(board) def fn(vals): """Return min moves to transform to chessboard.""" total = odd = 0 for i, x in enumerate(vals): if vals[0] == x: total += 1 if i&amp;1: odd += 1 elif vals[0] ^ x != (1 << n) - 1: return inf ans = inf if len(vals) <= 2*total <= len(vals)+1: ans = min(ans, odd) if len(vals)-1 <= 2*total <= len(vals): ans = min(ans, total - odd) return ans rows, cols = [0]*n, [0]*n for i in range(n): for j in range(n): if board[i][j]: rows[i] ^= 1 << j cols[j] ^= 1 << i ans = fn(rows) + fn(cols) return ans if ans < inf else -1
transform-to-chessboard
[Python3] alternating numbers
ye15
8
379
transform to chessboard
782
0.518
Hard
12,706
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1957176/Python-In-Order-Traversal-Explained-Well-Via-Comments
class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: # list with two element # the first for the previous element # the second for the min value pre_mn = [-float("inf"), float("inf")] def dfs(tree): if not tree: return # Keep going to the left dfs(tree.left) # if we can't go further, update min and pre pre_mn[1] = min(pre_mn[1], abs(tree.val) - pre_mn[0]) pre_mn[0] = tree.val # keep traversing in-order dfs(tree.right) dfs(root) # return min (the second element in the list) return pre_mn[1]
minimum-distance-between-bst-nodes
Python In-Order Traversal, Explained Well Via Comments
Hejita
1
89
minimum distance between bst nodes
783
0.569
Easy
12,707
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/2548468/Simple-Python-Solution-using-inorder-traversal
class Solution: def traverse(self,root,vals): if root is None: return self.traverse(root.left,vals) vals.append(root.val) self.traverse(root.right,vals) def minDiffInBST(self, root: Optional[TreeNode]) -> int: vals =[] self.traverse(root,vals) ans = [abs(vals[i+1]-vals[i]) for i in range(len(vals)-1)] return min(ans)
minimum-distance-between-bst-nodes
Simple Python Solution [using inorder traversal]
miyachan
0
10
minimum distance between bst nodes
783
0.569
Easy
12,708
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/2493933/Simple-inorder-traversal
class Solution: def __init__(self): self.arr = [] def inOrder(self,node): if node is None: return [] if node: self.inOrder(node.left) self.arr.append(node.val) self.inOrder(node.right) return self.arr def minDiffInBST(self, root: Optional[TreeNode]) -> int: inorder = self.inOrder(root) min_diff = float("inf") for i in range(1,len(inorder)): min_diff = min(min_diff,abs(inorder[i]-inorder[i-1])) return min_diff
minimum-distance-between-bst-nodes
Simple inorder traversal
aruj900
0
62
minimum distance between bst nodes
783
0.569
Easy
12,709
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/2016888/Python-2-lines
class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: inOrder = lambda n: inOrder(n.left) + [n.val] + inOrder(n.right) if n else [] vals = inOrder(root) return min(a - b for a, b in zip(vals[1:], vals))
minimum-distance-between-bst-nodes
Python 2 lines
SmittyWerbenjagermanjensen
0
117
minimum distance between bst nodes
783
0.569
Easy
12,710
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1988491/Python-Heapq-Solution-or-Faster-than-81-submits
class Solution: def __init__(self) : self.data = list() def visit(self, root) : if root : heappush(self.data, root.val) self.visit(root.left) self.visit(root.right) def minDiffInBST(self, root: Optional[TreeNode]) -> int: self.visit(root) tmp = None min_num = 10**5+1 while self.data : if tmp is not None : sec_tmp = heappop(self.data) if abs(sec_tmp-tmp) < min_num : min_num = abs(sec_tmp-tmp) tmp = sec_tmp else : tmp = heappop(self.data) return min_num
minimum-distance-between-bst-nodes
[ Python ] Heapq Solution | Faster than 81% submits
crazypuppy
0
41
minimum distance between bst nodes
783
0.569
Easy
12,711
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1828482/Inorder-traversal
class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: minimum = float("inf") previous = float("inf") stack = [] while(stack or root): while(root): stack.append(root) root = root.left root = stack.pop() minimum = min(minimum, abs(previous - root.val)) previous = root.val root = root.right return minimum
minimum-distance-between-bst-nodes
Inorder traversal
beginne__r
0
56
minimum distance between bst nodes
783
0.569
Easy
12,712
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1622369/Python-3-recursive-solution-O(n)-time-O(1)-space
class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: self.res = math.inf def helper(root): if root.left: # min value from left, max value from left low, left = helper(root.left) self.res = min(self.res, root.val - left) else: low = root.val if root.right: # min value from right, max value from right right, high = helper(root.right) self.res = min(self.res, right - root.val) else: high = root.val return low, high helper(root) return self.res
minimum-distance-between-bst-nodes
Python 3 recursive solution O(n) time, O(1) space
dereky4
0
128
minimum distance between bst nodes
783
0.569
Easy
12,713
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1511759/Python3-simple-recursive-solution
class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: def make(root): if not root: return if root.left: make(root.left) self.ans.append(root.val) if root.right: make(root.right) self.ans = [] make(root) ans = 10**5 for i in range(len(self.ans)-1): x = self.ans[i+1] - self.ans[i] if x < ans: ans = x return ans
minimum-distance-between-bst-nodes
Python3 simple recursive solution
EklavyaJoshi
0
56
minimum distance between bst nodes
783
0.569
Easy
12,714
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1402470/Python-oror-Very-Simple-oror-O(N)-time-Recursion-oror-beat-~(97)
class Solution: def minDiffInBST(self, root: TreeNode) -> int: lst = [] def inorder(root): if root: inorder(root.left) lst.append(root.val) inorder(root.right) inorder(root) maxi = 10 ** 5 for i in range(1, len(lst)): if abs(lst[i] - lst[i - 1]) < maxi: maxi = abs(lst[i] - lst[i - 1]) return maxi
minimum-distance-between-bst-nodes
Python || Very Simple || O(N) time Recursion || beat ~(97%)
naveenrathore
0
189
minimum distance between bst nodes
783
0.569
Easy
12,715
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1354182/Python-Solution
class Solution: def minDiffInBST(self, root: TreeNode) -> int: left_diff = float('inf') right_diff = float('inf') if root.left: left_tree = root.left while left_tree.right: left_tree = left_tree.right left_diff = root.val - left_tree.val left_diff = min(left_diff, self.minDiffInBST(root.left)) if root.right: right_tree = root.right while right_tree.left: right_tree = right_tree.left right_diff = right_tree.val - root.val right_diff = min(right_diff, self.minDiffInBST(root.right)) return min(left_diff, right_diff)
minimum-distance-between-bst-nodes
Python Solution
peatear-anthony
0
79
minimum distance between bst nodes
783
0.569
Easy
12,716
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1351706/Python-Morris-Traversal-O(n)-Time-O(1)-space
class Solution: def minDiffInBST(self, root: TreeNode) -> int: minDiff = float('inf') curr = root while curr: if not curr.left: curr = curr.right else: prev = curr.left while prev.right and prev.right != curr: prev = prev.right if not prev.right: prev.right = curr curr = curr.left else: prev.right = None minDiff = min(minDiff, abs(prev.val - curr.val)) curr = curr.right curr = root while curr: if not curr.right: curr = curr.left else: prev = curr.right while prev.left and prev.left != curr: prev = prev.left if not prev.left: prev.left = curr curr = curr.right else: prev.left = None minDiff = min(minDiff, abs(prev.val - curr.val)) curr = curr.left return minDiff
minimum-distance-between-bst-nodes
Python Morris Traversal O(n) Time, O(1) space
ItaloL
0
81
minimum distance between bst nodes
783
0.569
Easy
12,717
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1340855/Iterative-and-recursive-inorder-traversal-in-python-3
class Solution: def minDiffInBST(self, root: TreeNode) -> int: stack, node, prev = [], root, None ans = 10 ** 5 while stack or node: while node: stack.append(node) node = node.left node = stack.pop() if prev: ans = min(ans, node.val - prev.val) prev, node = node, node.right return ans
minimum-distance-between-bst-nodes
Iterative and recursive inorder traversal in python 3
mousun224
0
63
minimum distance between bst nodes
783
0.569
Easy
12,718
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1340855/Iterative-and-recursive-inorder-traversal-in-python-3
class Solution: def getMinimumDifference(self, root: TreeNode) -> int: inorder_list = [] def inorder(node: TreeNode): if not node: return inorder(node.left) inorder_list.append(node.val) inorder(node.right) inorder(root) return min(inorder_list[i+1] - inorder_list[i] for i in range(len(inorder_list) - 1))
minimum-distance-between-bst-nodes
Iterative and recursive inorder traversal in python 3
mousun224
0
63
minimum distance between bst nodes
783
0.569
Easy
12,719
https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1188411/Python3-Simple-solution-inorder-traversal-24-ms-runtime
class Solution: def minDiffInBST(self, root: TreeNode) -> int: low = [] def inorder (root): if root is None: return inorder(root.left) low.append(root.val) inorder(root.right) inorder(root) print(low) return min(low[i+1] - low[i] for i in range(len(low) - 1))
minimum-distance-between-bst-nodes
Python3, Simple solution, inorder traversal, 24 ms runtime
naiem_ece
0
65
minimum distance between bst nodes
783
0.569
Easy
12,720
https://leetcode.com/problems/letter-case-permutation/discuss/379928/Python-clear-solution
class Solution(object): def letterCasePermutation(self, S): """ :type S: str :rtype: List[str] """ def backtrack(sub="", i=0): if len(sub) == len(S): res.append(sub) else: if S[i].isalpha(): backtrack(sub + S[i].swapcase(), i + 1) backtrack(sub + S[i], i + 1) res = [] backtrack() return res
letter-case-permutation
Python clear solution
DenysCoder
164
7,000
letter case permutation
784
0.735
Medium
12,721
https://leetcode.com/problems/letter-case-permutation/discuss/1464233/2-Python-Solution-Iterative-and-Recursive
class Solution: def letterCasePermutation(self, S: str) -> List[str]: output = [""] for ch in S: for i in range(len(output)): if ch.isalpha(): output.append(output[i]+ch.lower()) output[i] = output[i]+ch.upper() else: output[i] = output[i]+ch return output
letter-case-permutation
2 Python Solution - Iterative and Recursive
abrarjahin
6
359
letter case permutation
784
0.735
Medium
12,722
https://leetcode.com/problems/letter-case-permutation/discuss/1464233/2-Python-Solution-Iterative-and-Recursive
class Solution: def letterCasePermutation(self, s: str) -> List[str]: return self.helper(s, "", []) def helper(self, s: str, current: str, solution:List[str]) -> List[str]: if len(s)==0: solution.append(current) return solution if s[0].isalpha(): self.helper(s[1:], current+s[0].lower(), solution) self.helper(s[1:], current+s[0].upper(), solution) else: self.helper(s[1:], current+s[0], solution) return solution
letter-case-permutation
2 Python Solution - Iterative and Recursive
abrarjahin
6
359
letter case permutation
784
0.735
Medium
12,723
https://leetcode.com/problems/letter-case-permutation/discuss/295975/Python-faster-than-99-32-ms
class Solution(object): def letterCasePermutation(self, S): """ :type S: str :rtype: List[str] """ digits = {str(x) for x in range(10)} A = [''] for c in S: B = [] if c in digits: for a in A: B.append(a+c) else: for a in A: B.append(a+c.lower()) B.append(a+c.upper()) A=B return A
letter-case-permutation
Python - faster than 99%, 32 ms
il_buono
5
625
letter case permutation
784
0.735
Medium
12,724
https://leetcode.com/problems/letter-case-permutation/discuss/1791038/Python-3-(60ms)-or-Simple-Solution-or-Easy-to-Understand
class Solution: def letterCasePermutation(self, s: str) -> List[str]: res = [''] for ch in s: if ch.isalpha(): res = [i+j for i in res for j in [ch.upper(), ch.lower()]] else: res = [i+ch for i in res] return res
letter-case-permutation
Python 3 (60ms) | Simple Solution | Easy to Understand
MrShobhit
3
144
letter case permutation
784
0.735
Medium
12,725
https://leetcode.com/problems/letter-case-permutation/discuss/372703/Python-recursive-solution-Easy-to-understand
class Solution: def __init__(self): self.res = [] def letterCasePermutation(self, S: str) -> List[str]: # edge case: empty input if S == "": return [""] # start recursion at root of tree self.funct("", S) return self.res def funct(self, base, remaining): # base case: we arrived to a leaf of the tree if len(remaining) == 1: if remaining.isdigit(): self.res.append(base + remaining) else: self.res.append(base + remaining) self.res.append(base + remaining.swapcase()) # average case: else: if remaining[0].isdigit(): self.funct(base + remaining[0], remaining[1:]) else: self.funct(base + remaining[0], remaining[1:]) self.funct(base + remaining[0].swapcase(), remaining[1:])
letter-case-permutation
Python recursive solution - Easy to understand
fernandowm
3
224
letter case permutation
784
0.735
Medium
12,726
https://leetcode.com/problems/letter-case-permutation/discuss/355092/Solution-in-Python-3-(beats-~97)-(four-lines)
class Solution: def letterCasePermutation(self, S: str) -> List[str]: T, a = [S.lower()], [i for i, j in enumerate(S) if j.isalpha()] for i in range(len(a)): for j in range(2**i): T.append(T[j][:a[i]]+T[j][a[i]].upper()+T[j][a[i]+1:]) return T - Junaid Mansuri (LeetCode ID)@hotmail.com
letter-case-permutation
Solution in Python 3 (beats ~97%) (four lines)
junaidmansuri
3
419
letter case permutation
784
0.735
Medium
12,727
https://leetcode.com/problems/letter-case-permutation/discuss/1530642/WEEB-DOES-PYTHON-BFS
class Solution: def letterCasePermutation(self, s: str) -> List[str]: queue = deque([(list(s), 0)]) return self.bfs(queue, s) def bfs(self, queue, s): result = [] while queue: curPath, idx = queue.popleft() result.append("".join(curPath)) for i in range(idx, len(s)): if s[i].isalpha(): if s[i].islower(): newPath = curPath.copy() newPath[i] = newPath[i].upper() queue.append((newPath, i+1)) else: newPath = curPath.copy() newPath[i] = newPath[i].lower() queue.append((newPath, i+1)) return result
letter-case-permutation
WEEB DOES PYTHON BFS
Skywalker5423
2
119
letter case permutation
784
0.735
Medium
12,728
https://leetcode.com/problems/letter-case-permutation/discuss/1068504/Python.-A-really-cool-and-simple-solution.-faster-than-99.25
class Solution: def letterCasePermutation(self, S: str) -> List[str]: ans = [S] for index, ch in enumerate(S): if ch.isalpha(): ans.extend([tmp[:index] + ch.swapcase() + tmp[index + 1:]for tmp in ans]) return ans
letter-case-permutation
Python. A really cool and simple solution. faster than 99.25%
m-d-f
2
125
letter case permutation
784
0.735
Medium
12,729
https://leetcode.com/problems/letter-case-permutation/discuss/2816452/BEATS-99-SUBMISSIONS-oror-EASIEST-ITERATIVE-SOLUTION-oror-FASTEST
class Solution: def letterCasePermutation(self, s: str) -> List[str]: output=[""] for c in s: t=[] if c.isalpha(): for o in output: t.append(o+c.upper()) t.append(o+c.lower()) else: for o in output: t.append(o+c) output=t return output
letter-case-permutation
BEATS 99% SUBMISSIONS || EASIEST ITERATIVE SOLUTION || FASTEST
Pritz10
1
52
letter case permutation
784
0.735
Medium
12,730
https://leetcode.com/problems/letter-case-permutation/discuss/2379797/Easy-python-solution-beats-95-using-recursion
class Solution(object): def letterCasePermutation(self, s): if s=="": return [""] t=s[0].lower() li=[] res=self.letterCasePermutation(s[1:]) for i in res: li.append(t+i) if t not in "1234567890": for i in res: li.append(t.upper()+i) return li
letter-case-permutation
Easy python solution beats 95% using recursion
babashankarsn
1
77
letter case permutation
784
0.735
Medium
12,731
https://leetcode.com/problems/letter-case-permutation/discuss/2017549/Very-Simple-Backtracking-Commented-Python-Code
class Solution: def letterCasePermutation(self, s: str) -> List[str]: res = [] r = len(s)-1 s = list(s) def backtrack(l): # On the prev problems, we stoped when l == r cuz it didn't need # to swap when I'm at the end of the string, so the base case doesn't # let the "de rec undo" apply, it filters it early and stores the # result in res, while on the other hand here we want to apply the # "do rec undo" code to the last char of the string so we will allow # at l == r by converting the contition to l > r if l > r: res.append("".join(s)) return # Notice in this line in other backtracking examples we create a loop, we did # thats because we needed to callthe backtrack function n times where n is the # size of the input (and this input decreases "backtrack(l+1)" as we apply) # but here we knew that we wanted to call backtrack function only 2 times # to handle the upper and lower cases, so it has no meaning to call # it on every char on the input string, we only need # to call it twice on every character if s[l].isalpha(): s[l] = s[l].swapcase() backtrack(l+1) s[l] = s[l].swapcase() backtrack(l+1) backtrack(0) return res
letter-case-permutation
Very Simple Backtracking Commented Python Code
muhammadbadawy
1
66
letter case permutation
784
0.735
Medium
12,732
https://leetcode.com/problems/letter-case-permutation/discuss/1874671/Python3-or-BackTracking
class Solution: def letterCasePermutation(self, s: str) -> List[str]: res = [] def backtrack(indx,path): if indx >= len(s): res.append(path) return if s[indx].isnumeric(): backtrack(indx+1,path + s[indx]) else: backtrack(indx+1,path + s[indx].swapcase()) backtrack(indx+1,path + s[indx]) backtrack(0,"") return res
letter-case-permutation
Python3 | BackTracking
iamskd03
1
17
letter case permutation
784
0.735
Medium
12,733
https://leetcode.com/problems/letter-case-permutation/discuss/1068261/Python-2-liner
class Solution: def letterCasePermutation(self, S: str) -> List[str]: L = [set([i.lower(), i.upper()]) for i in S] return map(''.join, itertools.product(*L))
letter-case-permutation
Python 2-liner
lokeshsenthilkumar
1
126
letter case permutation
784
0.735
Medium
12,734
https://leetcode.com/problems/letter-case-permutation/discuss/1068179/Python-Iterative-Solution-With-Explanation
class Solution: def letterCasePermutation(self, s: str) -> List[str]: p=[[]] for i in s: if "0"<=i<="9": #if a digit is encountered the for j in p: #then we add it to each of the permutations j.append(i) else: #else new_p=[] #a new list is created u,l=i.upper(),i.lower() for j in p: new_p.append(j+[u]) #every upper character is appended to the permutation and then appended to the newly created list j.append(l) #similarly lower character is appended to the character and then new_p.append(j) #appended to the newly created list p=new_p #assign new list of permuations to the old one. print(p) ''' printing p for better understanding Iteration 1:[['A'], ['a']] Iteration 2:[['A', '1'], ['a', '1']] Iteration 3:[['A', '1', 'B'], ['A', '1', 'b'], ['a', '1', 'B'], ['a', '1', 'b']] Iteration 4:[['A', '1', 'B', '2'], ['A', '1', 'b', '2'], ['a', '1', 'B', '2'], ['a', '1', 'b', '2']] ''' return ["".join(i) for i in p]
letter-case-permutation
Python Iterative Solution With Explanation
Umadevi_R
1
55
letter case permutation
784
0.735
Medium
12,735
https://leetcode.com/problems/letter-case-permutation/discuss/1068075/Super-Simple-Recursive-Python-Solution-With-An-Explanation!
class Solution: def letterCasePermutation(self, S: str) -> List[str]: # We're using a set, so we don't have to check if we already have this combination. ret_set = set() # This function will calculate the possibilities. def permutations(s, n=0): # This is called the base case. # If n, the index we want to play around with, is the same as the length of the string, # we don't want to call our recursive function again, as we'll get an index error. if n > len(s) - 1: return # Create two versions of the string. One were the letter is lower-cased, the other where # it is upper cased. l = s[:n] + s[n].lower() + s[n+1:] u = s[:n] + s[n].upper() + s[n+1:] # This is the equivalent of .add, but for multiple elements. # It checks if l is in the set, then adds if it isn't, then does the same for u. ret_set.update([l, u]) # Recurse! For each string, we run this function again. # This means that for the string "cavalierpoet", we call the function on: # "cavalierpoet" and "Cavalierpoet", then on: # "cavalierpoet" and "cAvalierpoet" and "Cavalierpoet" and "CAvalierpoet", and so on. # We always pass both variations back, and increment n, meaning that we 'toggle' the next letter. # ('1'.lower() does not cause an error.) return permutations(l, n+1), permutations(u, n+1) # Call the recursive function. permutations(S) # Return the set! return ret_set
letter-case-permutation
Super Simple Recursive Python Solution - With An Explanation!
Cavalier_Poet
1
38
letter case permutation
784
0.735
Medium
12,736
https://leetcode.com/problems/letter-case-permutation/discuss/1068075/Super-Simple-Recursive-Python-Solution-With-An-Explanation!
class Solution: def letterCasePermutation(self, S: str) -> List[str]: ret_set = set() def permutations(s, n=0): if n > len(s) - 1: return l = s[:n] + s[n].lower() + s[n+1:] u = s[:n] + s[n].upper() + s[n+1:] ret_set.update([l, u]) return permutations(l, n+1), permutations(u, n+1) permutations(S) return ret_set
letter-case-permutation
Super Simple Recursive Python Solution - With An Explanation!
Cavalier_Poet
1
38
letter case permutation
784
0.735
Medium
12,737
https://leetcode.com/problems/letter-case-permutation/discuss/2813119/Python-or-Simple-Recursion
class Solution: def letterCasePermutation(self, s: str) -> List[str]: res = [] def helper(arr, pos, slate): if pos == len(arr): res.append(''.join(slate[:])) return if arr[pos].isdigit(): helper(arr, pos+1, slate+[arr[pos]]) else: helper(arr, pos+1, slate+[arr[pos].upper()]) helper(arr, pos+1, slate+[arr[pos].lower()]) helper(s, 0, []) return res
letter-case-permutation
Python | Simple Recursion
ajay_gc
0
2
letter case permutation
784
0.735
Medium
12,738
https://leetcode.com/problems/letter-case-permutation/discuss/2804011/Backtracking-python3-solution
class Solution: def findLetterPermutations(self, index: int, word: str, curr_list: List[str], answer: List[str]) -> None: if index == len(word): permutation = ''.join(curr_list) answer.append(permutation) return ch = word[index] if ch.isdigit(): curr_list.append(ch) self.findLetterPermutations(index+1, word, curr_list, answer) curr_list.pop() else: # upper case curr_list.append(ch.upper()) self.findLetterPermutations(index+1, word, curr_list, answer) curr_list.pop() # lower case curr_list.append(ch.lower()) self.findLetterPermutations(index+1, word, curr_list, answer) curr_list.pop() # O(2^n) time, # O(2^n) space, # Approach: backtracking, recursion def letterCasePermutation(self, s: str) -> List[str]: answer = [] self.findLetterPermutations(0, s, [], answer) return answer
letter-case-permutation
Backtracking python3 solution
destifo
0
4
letter case permutation
784
0.735
Medium
12,739
https://leetcode.com/problems/letter-case-permutation/discuss/2766800/python3-solution-by-recursion
class Solution: def letterCasePermutation(self, s: str) -> List[str]: def backtrack(curr: str): if len(curr) == len(s): output.append(curr[:]) return i = len(curr) if s[i].isalpha(): backtrack(curr + s[i].upper()) backtrack(curr + s[i].lower()) else: backtrack(curr + s[i]) output = [] backtrack('') return output
letter-case-permutation
python3 solution by recursion
nolleh7707
0
1
letter case permutation
784
0.735
Medium
12,740
https://leetcode.com/problems/letter-case-permutation/discuss/2746326/Recursion-solution-with-Time-complexity-of-O(2n-*-n)-and-with-Aux-space-complexity-of-O(n)
class Solution: def letterCasePermutation(self, s: str) -> List[str]: result = [] def helper(s: str, i: int, slate: List[str]): if i == len(s): result.append("".join(slate)) return else: if s[i].isdigit(): slate.append(s[i]) helper(s, i+1, slate) slate.pop() else: slate.append(s[i].upper()) helper(s, i+1, slate) slate.pop() slate.append(s[i].lower()) helper(s, i+1, slate) slate.pop() helper(s, 0, []) return result
letter-case-permutation
Recursion solution with Time complexity of O(2^n * n) & with Aux space complexity of O(n)
vineel369
0
2
letter case permutation
784
0.735
Medium
12,741
https://leetcode.com/problems/letter-case-permutation/discuss/2705745/Python3-Recursive-Approach
class Solution: def letterCasePermutation(self, s: str) -> List[str]: def perm(inp,out,res): if len(inp)==0: if out not in res: res.append(out) return out1 = out out2 = out if not inp[0].isnumeric(): out1 = out1+inp[0].upper() out2 = out2+inp[0].lower() else: out1 = out1+inp[0] out2 = out2+inp[0] perm(inp[1:],out1,res) perm(inp[1:],out2,res) return res = [] out = "" perm(s,out,res) return res
letter-case-permutation
Python3 Recursive Approach
shashank732001
0
6
letter case permutation
784
0.735
Medium
12,742
https://leetcode.com/problems/letter-case-permutation/discuss/2673184/easy-approach!
class Solution: def letterCasePermutation(self, s: str) -> List[str]: ans = [""] for s in s: if s.isdigit(): ans = [c+s for c in ans] else: temp1 = [c+s.lower() for c in ans] temp2 = [c+s.upper() for c in ans] ans = temp1 + temp2 return ans
letter-case-permutation
easy approach!
sanjeevpathak
0
3
letter case permutation
784
0.735
Medium
12,743
https://leetcode.com/problems/letter-case-permutation/discuss/2670595/Python-solution-with-recursion
class Solution: def letterCasePermutation(self, s: str) -> List[str]: res = [] def recurse(curr, remaining): if not remaining: res.append(curr) return if remaining[0].isdigit(): recurse(curr + remaining[0], remaining[1:]) else: recurse(curr + remaining[0].upper(), remaining[1:]) recurse(curr + remaining[0].lower(), remaining[1:]) recurse('', s) return res
letter-case-permutation
Python solution with recursion
michaelniki
0
4
letter case permutation
784
0.735
Medium
12,744
https://leetcode.com/problems/letter-case-permutation/discuss/2624804/Python3-or-Recursive
class Solution: def letterCasePermutation(self, s: str) -> List[str]: res = [] def dfs(i, path): if i == len(s): res.append(''.join(path)) return if s[i].isdigit(): dfs(i+1, path + [s[i]]) else: dfs(i+1, path + [s[i].lower()]) dfs(i+1, path + [s[i].upper()]) dfs(0, []) return res
letter-case-permutation
Python3 | Recursive
Ploypaphat
0
9
letter case permutation
784
0.735
Medium
12,745
https://leetcode.com/problems/letter-case-permutation/discuss/2605474/python3-Faster-then-90
class Solution: def letterCasePermutation(self, s: str) -> List[str]: def helper(temp,s): if not s: ans.append(temp) return if s[0].isalpha(): helper(temp+s[0].lower(),s[1:]) helper(temp+s[0].upper(),s[1:]) else: helper(temp+s[0],s[1:]) ans = [] helper("",s) return ans
letter-case-permutation
python3 Faster then 90%
pranjalmishra334
0
22
letter case permutation
784
0.735
Medium
12,746
https://leetcode.com/problems/letter-case-permutation/discuss/2520979/Python3-Faster-Than-99
class Solution: def letterCasePermutation(self, s: str) -> List[str]: @cache def perms(s): n = len(s) if n == 0: return [""] i = 0 while i < n and ord(s[i]) < 65: i += 1 if i == n: return [s] u = l = s[i] if u.islower(): u = u.upper() else: l = l.lower() res = [] for ss in perms(s[i+1:]): res.append(s[:i] + l + ss) res.append(s[:i] + u + ss) return res return perms(s)
letter-case-permutation
Python3 Faster Than 99%
ryangrayson
0
26
letter case permutation
784
0.735
Medium
12,747
https://leetcode.com/problems/letter-case-permutation/discuss/2479233/Python-Recursion-Solution
class Solution: def letterCasePermutation(self, s: str) -> List[str]: ansList = [] def isIntOrChar(val): try: x = int(val) return 'integer' except ValueError: return 'char' def recur(index, st): if index == -1: ansList.append(st) return else: if isIntOrChar(s[index]) == 'integer': recur(index-1, s[index] + st) else: recur(index-1, s[index].lower()+st) recur(index-1, s[index].upper()+st) recur(len(s)-1, '') return ansList
letter-case-permutation
Python Recursion Solution
DietCoke777
0
22
letter case permutation
784
0.735
Medium
12,748
https://leetcode.com/problems/letter-case-permutation/discuss/2450828/Python3-or-Recursion-%2B-Backtracking
class Solution: #Let n = len(s)! #Time-Complexity: O(2^n), in worst case my input string can be only english leters, which means #branching factor will always be 2! Also, height of rec. tree is n! #Space-Complexity: O(n), since call stack will be at max depth of n! def letterCasePermutation(self, s: str) -> List[str]: #Approach: We can simply go character by character and append to the next corresponding #character in built-up string! For the built-up string, I can pass it around multiple #recursive calls across rec. tree by reference, and whenever we hit base case, we can #simply append built-up string to answer! ans = [] n = len(s) def helper(i, cur): nonlocal ans, n, s #base case: if i == n: we handled every single character! if(i == n): ans.append(cur[::]) return current_char = s[i] #if current character is a digit, we simply need to append it and recurse further! if(current_char.isdigit()): cur += current_char helper(i+1, cur) #once we finish recursion, we need to make sure to restore cur for backtracking! #exclude last character we concatenated before making rec. call! cur = cur[:len(cur)-1] return else: #otherwise, make 2 rec. calls: one to concatenate lowercase and another to #add uppercase character! #check if s[i] is lowercase! if(current_char.islower()): cur += current_char #make rec. call with lowercase char! helper(i+1, cur) cur = cur[:len(cur)-1] #concatenate uppercase version of current char! cur += current_char.upper() #recurse! helper(i+1, cur) #backtrack again and restore cur! cur = cur[:len(cur)-1] return #otherwise, do same thing but for uppercase! else: cur += current_char helper(i+1, cur) cur = cur[:len(cur)-1] cur += current_char.lower() helper(i+1, cur) cur = cur[:len(cur)-1] return helper(0, "") return ans
letter-case-permutation
Python3 | Recursion + Backtracking
JOON1234
0
23
letter case permutation
784
0.735
Medium
12,749
https://leetcode.com/problems/letter-case-permutation/discuss/2439556/Python-Solution-or-Two-Ways-or-Backtracking-or-90-Faster
class Solution: # classic backtracking way def letterCasePermutation(self, s: str) -> List[str]: def traverse(string,index): if len(string) == len(s): ans.append(string) else: if s[index].isalpha(): traverse(string+s[index].swapcase(),index+1) traverse(string+s[index],index+1) ans = [] traverse("",0) return ans # To avoid O(m+n) string concatenation, another way def letterCasePermutation(self, s: str) -> List[str]: def traverse(string,index): if len(string) == len(s): ans.append(''.join(string[:])) return else: string.append(s[index]) traverse(string,index+1) string.pop(-1) if s[index].isalpha(): string.append(s[index].swapcase()) traverse(string,index+1) string.pop(-1) ans = [] traverse([],0) return ans
letter-case-permutation
Python Solution | Two Ways | Backtracking | 90% Faster
Gautam_ProMax
0
32
letter case permutation
784
0.735
Medium
12,750
https://leetcode.com/problems/letter-case-permutation/discuss/2295562/using-reccursion
class Solution: def letterCasePermutation(self, s: str) -> List[str]: # find the full length of string full_l = len(s) # define a reccursion function def myownrecc(ss, i): # if reached end append the string if i == full_l: output.append(ss) return # if condition satisfied for current index split into two reccursion one with upper case and another lowe case if ss[i].isalpha(): lowers = ss[:i]+ss[i].lower()+ss[i+1:] uppers = ss[:i]+ss[i].upper()+ss[i+1:] myownrecc(lowers, i+1) myownrecc(uppers, i+1) else: # contnue with next index myownrecc(ss, i+1) output = [] myownrecc(s, 0)
letter-case-permutation
using reccursion
krishnamsgn
0
9
letter case permutation
784
0.735
Medium
12,751
https://leetcode.com/problems/letter-case-permutation/discuss/2074495/Python3-or-DFS-or-Easy-Understand
class Solution: def letterCasePermutation(self, s: str) -> List[str]: self.d = {} for char in s: if not char.isdigit(): self.d[char] = [char.lower(), char.upper()] result = [] self.dfs(s, "", result) return result def dfs(self, s, path, result): if not s: return result.append(path) char = s[0] if char.isdigit(): self.dfs(s[1:], path+char, result) else: for char in self.d[char]: self.dfs(s[1:], path+char, result)
letter-case-permutation
Python3 | DFS | Easy Understand
itachieve
0
17
letter case permutation
784
0.735
Medium
12,752
https://leetcode.com/problems/letter-case-permutation/discuss/1988941/Python-recursion-solution
class Solution: def letterCasePermutationHelper(self, s: str, i: int, n: int, resultArr: List[str], res: str) -> None: #Base Case if i == n: resultArr.append(res) return asciiVal = ord(s[i]) if 65 <= asciiVal <= 90: # Add/Subtract by 32 for converting because difference of ascii value of a and A is 32 self.letterCasePermutationHelper(s, i+1, n, resultArr, res + chr(asciiVal + 32)) self.letterCasePermutationHelper(s, i+1, n, resultArr, res+s[i]) elif 97 <= asciiVal <= 122: self.letterCasePermutationHelper(s, i+1, n, resultArr, res + chr(asciiVal - 32)) self.letterCasePermutationHelper(s, i+1, n, resultArr, res+s[i]) else: self.letterCasePermutationHelper(s, i+1, n, resultArr, res+s[i]) def letterCasePermutation(self, s: str) -> List[str]: resultArr = list() n = len(s) self.letterCasePermutationHelper(s, 0, n, resultArr, '') return resultArr
letter-case-permutation
Python recursion solution
dbansal18
0
39
letter case permutation
784
0.735
Medium
12,753
https://leetcode.com/problems/letter-case-permutation/discuss/1948057/Python-Faster-than-97-with-ASCII-Solution
class Solution: def letterCasePermutation(self, s: str) -> List[str]: res = list() for i in s : if 97 <= ord(i) <= 122 : if res : a = [r+i for r in res] b = [r+chr(ord(i)-32) for r in res] else : a = [i] b = [chr(ord(i)-32)] res = a + b elif 65 <= ord(i) <= 90 : if res : a = [r+i for r in res] b = [r+chr(ord(i)+32) for r in res] else : a = [i] b = [chr(ord(i)+32)] res = a + b else : if res : res = [r+i for r in res] else : res.append(i) return res
letter-case-permutation
[ Python ] Faster than 97% with ASCII Solution
crazypuppy
0
40
letter case permutation
784
0.735
Medium
12,754
https://leetcode.com/problems/letter-case-permutation/discuss/1646344/Python-solution
class Solution: def letterCasePermutation(self, s: str) -> List[str]: def allposs(s,length, res): if(length == len(s)): res.append(s) return res if(s[length].isdigit()): res = allposs(s,length+1,res) else: s = s[0:length] +s[length].lower() +s[length+1:] res = allposs(s,length+1,res) s = s[0:length] +s[length].upper() +s[length+1:] res = allposs(s,length+1, res) return res return allposs(s,0,list())
letter-case-permutation
Python solution
mayankpi
0
52
letter case permutation
784
0.735
Medium
12,755
https://leetcode.com/problems/letter-case-permutation/discuss/1583153/Python3-Clean-recursive-solution-beats-99
class Solution: def letterCasePermutation(self, s: str) -> List[str]: if len(s) == 1: if s.isalpha(): return [s.lower(), s.upper()] else: return [s] nextLetterCasePermutations = self.letterCasePermutation(s[1:]) if s[0].isalpha(): for i in range(len(nextLetterCasePermutations)): permutation = nextLetterCasePermutations[i] nextLetterCasePermutations[i] = s[0].upper() + permutation nextLetterCasePermutations.append(s[0].lower() + permutation) return nextLetterCasePermutations else: for (i, permutation) in enumerate(nextLetterCasePermutations): nextLetterCasePermutations[i] = s[0] + permutation return nextLetterCasePermutations
letter-case-permutation
[Python3] Clean recursive solution beats 99%
parof
0
50
letter case permutation
784
0.735
Medium
12,756
https://leetcode.com/problems/letter-case-permutation/discuss/1387280/python3-or-Call-twice-for-alpha-and-once-for-digit-or-Backtracking
class Solution: def letterCasePermutation(self, s: str) -> List[str]: self.ans=[] n=len(s) self.solve(0,s,[],n) return self.ans def solve(self,strt,s,ds,n): if len(ds)==n: self.ans.append("".join(ds[:])) return for i in range(strt,n): if s[i].isdigit(): ds.append(s[i]) self.solve(i+1,s,ds,n) ds.pop() else: ds.append(s[i]) self.solve(i+1,s,ds,n) ds.pop() if s[i].islower(): ds.append(s[i].upper()) self.solve(i+1,s,ds,n) ds.pop() elif s[i].isupper(): ds.append(s[i].lower()) self.solve(i+1,s,ds,n) ds.pop() return
letter-case-permutation
python3 | Call twice for alpha and once for digit | Backtracking
swapnilsingh421
0
53
letter case permutation
784
0.735
Medium
12,757
https://leetcode.com/problems/letter-case-permutation/discuss/1365342/Python-Faster-than-98-(-perhaps-using-too-much-space-)
class Solution: def letterCasePermutation(self, s: str) -> List[str]: output = [''] for char in s: if char.isnumeric(): output = [x+char for x in output] else: output = [x+char.lower() for x in output] + [x+char.upper() for x in output] return output
letter-case-permutation
Python Faster than 98% ( perhaps using too much space ?)
StneFx
0
137
letter case permutation
784
0.735
Medium
12,758
https://leetcode.com/problems/letter-case-permutation/discuss/1246225/Python-JavaScript-solutions
class Solution: def letterCasePermutation(self, s: str) -> List[str]: # T: O(M * 2^L) # S: O(L) N = len(s) s = s.lower() ans = [] def helper(index, current): if index == N: ans.append(current) return if S[index].isalpha(): helper(index + 1, current + s[index].lower()) helper(index + 1, current + s[index].upper()) else: helper(index + 1, current + S[index]) helper(0, "") return ans
letter-case-permutation
Python, JavaScript solutions
treksis
0
113
letter case permutation
784
0.735
Medium
12,759
https://leetcode.com/problems/letter-case-permutation/discuss/1068877/recursive-backtracking-solution
class Solution: def __init__(self): # O(1) lookup times for keeping track of when and when not to permute self.sett = set() # recursive backtracking solution def permute(self, s: list[str], l: int, r: int) -> None: # base case of finished processing # so add to set if l > r: string = "".join(s) if string not in self.sett: self.sett.add(string) return for i in range(l, r+1): # recurse when current character is uppercase, but only do so # if we haven't seen such a permutation before s[i] = s[i].upper() string = "".join(s) if string not in self.sett: self.permute(s, l+1, r) # recurse when current character is lowercase, but only do so # if we haven't seen such a permutation before s[i] = s[i].lower() string = "".join(s) if string not in self.sett: self.permute(s, l+1, r) def letterCasePermutation(self, s: str) -> List[str]: self.permute(list(s), 0, len(s)-1) return list(self.sett)
letter-case-permutation
recursive backtracking solution
leozhang1
0
17
letter case permutation
784
0.735
Medium
12,760
https://leetcode.com/problems/letter-case-permutation/discuss/1068621/Python-3-Ways-or-Optimization-or-T~O(2N)S~O(N)
class Solution: def letterCasePermutation(self, S: str) -> List[str]: self.N = len(S) self.S = S self.retList = [] curString = "" def dfs(index,curString): if index == self.N: self.retList.append(curString) return char = self.S[index] if char.isalpha(): #two ways to create string - capital this letter or lowercase this letter dfs(index+1,curString[:]+char.upper()) dfs(index+1,curString[:]+char.lower()) else: #digit, just add it as what it is dfs(index+1,curString[:]+char) dfs(0,curString) return self.retList
letter-case-permutation
[Python] 3 Ways | Optimization | T~O(2^N)/S~O(N)
Vikktour
0
85
letter case permutation
784
0.735
Medium
12,761
https://leetcode.com/problems/letter-case-permutation/discuss/1068621/Python-3-Ways-or-Optimization-or-T~O(2N)S~O(N)
class Solution: def letterCasePermutation(self, S: str) -> List[str]: self.N = len(S) self.S = S self.retList = [] self.curString = "" def dfs(index): if index == self.N: self.retList.append(self.curString) return char = self.S[index] if char.isalpha(): #two ways to create string - capital this letter or lowercase this letter self.curString += char.upper() dfs(index+1) self.curString = self.curString[:-1] #backtrack and remove last char self.curString += char.lower() dfs(index+1) self.curString = self.curString[:-1] #backtrack and remove last char else: #digit, just add it as what it is self.curString += char dfs(index+1) self.curString = self.curString[:-1] #backtrack and remove last char dfs(0) return self.retList
letter-case-permutation
[Python] 3 Ways | Optimization | T~O(2^N)/S~O(N)
Vikktour
0
85
letter case permutation
784
0.735
Medium
12,762
https://leetcode.com/problems/letter-case-permutation/discuss/1068621/Python-3-Ways-or-Optimization-or-T~O(2N)S~O(N)
class Solution: def letterCasePermutation(self, S: str) -> List[str]: self.N = len(S) self.S = S self.retList = [] self.curStringAsList = ["-" for _ in range(self.N)] #dummy string list, we're going to change values at each index - Note that I'm using list because string can't be modified at index def dfs(index): #print("curStringAsList: {}".format(self.curStringAsList)) if index == self.N: self.retList.append("".join(self.curStringAsList)) return char = self.S[index] if char.isalpha(): #two ways to create string - capital this letter or lowercase this letter self.curStringAsList[index] = char.upper() dfs(index+1) self.curStringAsList[index] = char.lower() dfs(index+1) else: #digit, just add it as what it is self.curStringAsList[index] = char dfs(index+1) return dfs(0) return self.retList
letter-case-permutation
[Python] 3 Ways | Optimization | T~O(2^N)/S~O(N)
Vikktour
0
85
letter case permutation
784
0.735
Medium
12,763
https://leetcode.com/problems/letter-case-permutation/discuss/1068156/Your-runtime-beats-88.03-of-python3-submissions.-python3
class Solution: def letterCasePermutation(self, S: str) -> List[str]: def solve(s,i,n): if i==n: res.append(s) return if S[i].isalpha(): solve(s+S[i].swapcase(),i+1,n) solve(s+S[i],i+1,n) res=[] solve("",0,len(S)) return res
letter-case-permutation
Your runtime beats 88.03 % of python3 submissions. python3
_Rehan12
0
15
letter case permutation
784
0.735
Medium
12,764
https://leetcode.com/problems/letter-case-permutation/discuss/1068125/Simple-iterative-solution-in-Python3-briefly-explained
class Solution: def letterCasePermutation(self, S: str) -> List[str]: s = S.lower() if s.isnumeric(): return [s] ans = [] alpha = [] for i in range(len(s)): if s[i].isalpha(): alpha.append(i) n = len(alpha) for i in range(2 ** n): b = bin(i)[2:].zfill(n) temp = list(s) for j in range(len(b)): if b[j] == '1': temp[alpha[j]] = temp[alpha[j]].upper() ans.append(''.join(temp)) return ans
letter-case-permutation
Simple iterative solution in Python3, briefly explained
amoghrajesh1999
0
26
letter case permutation
784
0.735
Medium
12,765
https://leetcode.com/problems/letter-case-permutation/discuss/1068114/Python-or-Easy-iterative-solution-or-beats-88
class Solution: def letterCasePermutation(self, S: str) -> List[str]: ans = [] if not S: return [] if S[0].isnumeric(): ans = [S[0]] else: ans = [S[0].upper(), S[0].lower()] for i in range(1,len(S)): if S[i].isnumeric(): ans = [j + S[i] for j in ans] else: ans1 = [None]*(2*len(ans)) for j in range(len(ans)): ans1[2*j] = ans[j] + S[i].lower() ans1[2*j+1] = ans[j] + S[i].upper() ans = ans1 return ans
letter-case-permutation
Python | Easy iterative solution | beats 88%
SlavaHerasymov
0
41
letter case permutation
784
0.735
Medium
12,766
https://leetcode.com/problems/letter-case-permutation/discuss/753407/Easy-to-Read-Python-Recursive-Solution-with-Comments!
class Solution: def letterCasePermutation(self, S: str) -> List[str]: res = [] l = len(S) def helper(st, idx): # If we've reached the end of our S, append our current st. if idx == l: res.append(st) return # If our S[idx] character is a letter call recursively with and upper and lower. if S[idx].isalpha(): helper(st+S[idx].lower(), idx+1) helper(st+S[idx].upper(), idx+1) # Else add the number to our st and continue to increment. else: helper(st+S[idx], idx+1) helper('', 0) return res
letter-case-permutation
Easy to Read Python Recursive Solution with Comments!
Pythagoras_the_3rd
0
88
letter case permutation
784
0.735
Medium
12,767
https://leetcode.com/problems/letter-case-permutation/discuss/387238/Python3-iterative-solution
class Solution: def letterCasePermutation(self, S: str) -> List[str]: ans = [""] for c in S: ans = [x + cc for x in ans for cc in {c, c.swapcase()}] return ans
letter-case-permutation
[Python3] iterative solution
ye15
0
96
letter case permutation
784
0.735
Medium
12,768
https://leetcode.com/problems/letter-case-permutation/discuss/387238/Python3-iterative-solution
class Solution: def letterCasePermutation(self, S: str) -> List[str]: def fn(i): """Populate ans via a stack.""" if i == len(S): return ans.append("".join(stack)) for c in {S[i], S[i].swapcase()}: stack.append(c) fn(i+1) stack.pop() ans, stack = [], [] fn(0) return ans
letter-case-permutation
[Python3] iterative solution
ye15
0
96
letter case permutation
784
0.735
Medium
12,769
https://leetcode.com/problems/letter-case-permutation/discuss/387238/Python3-iterative-solution
class Solution: def letterCasePermutation(self, S: str) -> List[str]: def fn(i): """Return letter case permutation of S[i:].""" if i == len(S): return [""] return [c + x for c in {S[i], S[i].swapcase()} for x in fn(i+1)] return fn(0)
letter-case-permutation
[Python3] iterative solution
ye15
0
96
letter case permutation
784
0.735
Medium
12,770
https://leetcode.com/problems/letter-case-permutation/discuss/366071/Python3-Simple-Recursive-Solution
class Solution: def letterCasePermutation(self, S: str) -> List[str]: if not S: return [] permutations = [] self.get_permutations(S, "", permutations) return permutations def get_permutations(self, inp: str, candidate: str, permutations: List[str]) -> None: if not inp: permutations.append(candidate) return next_char = inp[0] next_input = inp[1:] if next_char.isalpha(): self.get_permutations(next_input, candidate + next_char.upper(), permutations) self.get_permutations(next_input, candidate + next_char.lower(), permutations) else: self.get_permutations(next_input, candidate + next_char, permutations)
letter-case-permutation
Python3 Simple Recursive Solution
llanowarelves
0
133
letter case permutation
784
0.735
Medium
12,771
https://leetcode.com/problems/letter-case-permutation/discuss/1069341/Python3-or-Simple-recursion
class Solution: def letterCasePermutation(self, S: str) -> List[str]: # ending condition if len(S)==1: if S.isdigit(): return [S] else: return [S.lower(), S.upper()] first_char, remain = S[0], S[1:] remain_permutation = self.letterCasePermutation(remain) # if digit if first_char.isdigit(): return [str(first_char) + item for item in remain_permutation] # if letter else: return [first_char.lower() + item for item in remain_permutation] + [first_char.upper() + item for item in remain_permutation]
letter-case-permutation
Python3 | Simple recursion
geoffrey0104
-1
34
letter case permutation
784
0.735
Medium
12,772
https://leetcode.com/problems/is-graph-bipartite/discuss/1990803/JavaC%2B%2BPythonJavaScriptKotlinSwiftO(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022
class Solution: def isBipartite(self, graph: list[list[int]]) -> bool: vis = [False for n in range(0, len(graph))] while sum(vis) != len(graph): # Since graph isn't required to be connected this process needs to be repeated ind = vis.index(False) # Find the first entry in the visited list that is false vis[ind] = True grp = {ind:True} # initialize first node as part of group 1 q = [ind] # Add current index to queue while q: # Go to each node in the graph u = q.pop(0) for v in graph[u]: # Go to each vertice connected to the current node if vis[v] == True: # If visited check that it is in the opposite group of the current node if grp[u] == grp[v]: return False # If a single edge does not lead to a group change return false else: # If not visited put v in opposite group of u, set to visited, and append to q vis[v] = True grp[v] = not grp[u] q.append(v) return True
is-graph-bipartite
[Java/C++/Python/JavaScript/Kotlin/Swift]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022
cucerdariancatalin
3
356
is graph bipartite
785
0.527
Medium
12,773
https://leetcode.com/problems/is-graph-bipartite/discuss/1999283/Python-3-or-DFS-and-BFS-or-Explanation
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) graph = [set(g) for g in graph] colors = [-1] * n def bfs(i): q = collections.deque([[i, 0]]) while q: idx, color = q.popleft() colors[idx] = color for nei in graph[idx]: if colors[nei] >= 0: if 1-color != colors[nei]: return False continue q.append((nei, 1-color)) return True for i in range(n): if colors[i] < 0 and not bfs(i): return False return True
is-graph-bipartite
Python 3 | DFS & BFS | Explanation
idontknoooo
1
124
is graph bipartite
785
0.527
Medium
12,774
https://leetcode.com/problems/is-graph-bipartite/discuss/1999283/Python-3-or-DFS-and-BFS-or-Explanation
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) colors = [-1] * n def dfs(i, color): colors[i] = color for node in graph[i]: if colors[node] == color: return False elif colors[node] < 0 and not dfs(node, 1 - color): return False return True for i in range(n): if colors[i] < 0 and not dfs(i, 0): return False return True
is-graph-bipartite
Python 3 | DFS & BFS | Explanation
idontknoooo
1
124
is graph bipartite
785
0.527
Medium
12,775
https://leetcode.com/problems/is-graph-bipartite/discuss/1990627/Python-Solution-With-Union-Find
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) u = [i for i in range(n)] def find(i): if i == u[i]: return i else: u[i] = find(u[i]) return u[i] def union(a, b): r_a = find(a) r_b = find(b) if r_a != r_b: u[r_a] = r_b u[a] = r_b for g in range(len(graph)): root = find(g) for i in range(1, len(graph[g])): union(graph[g][i], graph[g][i-1]) if root == find(graph[g][i]) or root == find(graph[g][i - 1]): return False return True
is-graph-bipartite
Python Solution With Union Find
h920032
1
81
is graph bipartite
785
0.527
Medium
12,776
https://leetcode.com/problems/is-graph-bipartite/discuss/1990506/Java-or-Python-or-DFS-or-0ms-or-100
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: numNode = len(graph) set1 = [False for _ in range(numNode)] set2 = [False for _ in range(numNode)] for i in range(numNode): if (set1[i] or set2[i]): continue if (not self.dfs(i, set1, set2, graph)): return False return True def dfs(self, cur: int, set1: List[bool], set2: List[bool], graph: List[List[int]]) -> bool: if (set1[cur]): return not set2[cur] set1[cur] = True for n in graph[cur]: if (not self.dfs(n, set2, set1, graph)): return False return True
is-graph-bipartite
Java | Python | DFS | 0ms | 100%
YsGBt
1
123
is graph bipartite
785
0.527
Medium
12,777
https://leetcode.com/problems/is-graph-bipartite/discuss/1990427/Python3-Simple-BFS-Coloring
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: visited = {} for node in range(len(graph)): if node not in visited: visited[node] = 0 q = deque() q.append(node) while q: curr = q.popleft() for adj in graph[curr]: if adj not in visited: visited[adj] = visited[curr]^1 q.append(adj) elif visited[adj] == visited[curr]: return False return True
is-graph-bipartite
Python3 Simple BFS Coloring
constantine786
1
134
is graph bipartite
785
0.527
Medium
12,778
https://leetcode.com/problems/is-graph-bipartite/discuss/1258718/Python-Clean-DFS-solution
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: n=len(graph) color=[0]*n for i in range(n): if color[i]==0 and not self.validcolor(graph,color,1,i): return False return True def validcolor(self,graph,color,blue,i): if color[i]!=0: return color[i]==blue color[i]=blue for neighbour in graph[i]: if not self.validcolor(graph,color,-blue,neighbour): return False return True
is-graph-bipartite
[Python] Clean DFS solution
jaipoo
1
206
is graph bipartite
785
0.527
Medium
12,779
https://leetcode.com/problems/is-graph-bipartite/discuss/656096/Python3-concise-dfs
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: def dfs(n, i=1): """Return True if bipartite for node n""" if seen[n]: return (i-seen[n])%2 == 0 seen[n] = i return all(dfs(x, i+1) for x in graph[n]) seen = [0]*len(graph) return all(dfs(n) for n in range(len(graph)) if not seen[n])
is-graph-bipartite
[Python3] concise dfs
ye15
1
76
is graph bipartite
785
0.527
Medium
12,780
https://leetcode.com/problems/is-graph-bipartite/discuss/656096/Python3-concise-dfs
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: seen = [0]*len(graph) for k in range(len(graph)): if not seen[k]: seen[k] = 1 stack = [k] while stack: n = stack.pop() for nn in graph[n]: if not seen[nn]: seen[nn] = seen[n] + 1 stack.append(nn) elif seen[n] &amp; 1 == seen[nn] &amp; 1: return False # check parity return True
is-graph-bipartite
[Python3] concise dfs
ye15
1
76
is graph bipartite
785
0.527
Medium
12,781
https://leetcode.com/problems/is-graph-bipartite/discuss/656096/Python3-concise-dfs
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: def dfs(n, k=1): """Return True if n is not on odd-length cycle.""" if seen[n]: return k*seen[n] > 0 # True on even-length cycle seen[n] = k return all(dfs(nn, -k) for nn in graph[n]) # all neighbors on even-length cycle seen = [0]*len(graph) return all(dfs(i) for i in range(len(graph)) if not seen[i])
is-graph-bipartite
[Python3] concise dfs
ye15
1
76
is graph bipartite
785
0.527
Medium
12,782
https://leetcode.com/problems/is-graph-bipartite/discuss/2842288/Easy-python-solution-using-DFS
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) color = [-1]*n for i in range(n): if color[i] == -1: if self.dfs(i, graph, color, 0) == False: return False return True def dfs(self, src, graph, color, c): color[src] = c for node in graph[src]: if color[node] == -1: if self.dfs(node, graph, color, 1-c) == False: return False else: if color[node] == c: return False return True
is-graph-bipartite
Easy python solution using DFS
i-haque
0
1
is graph bipartite
785
0.527
Medium
12,783
https://leetcode.com/problems/is-graph-bipartite/discuss/2839940/Easy-python-solution-using-BFS
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) color = [-1] * n for i in range(n): if color[i] == -1: if self.check(i, graph, color) == False: return False return True def check(self, src, graph, color): q = collections.deque() q.append(src) color[src] = 0 while q: for _ in range(len(q)): node = q.popleft() for n in graph[node]: if color[node] == color[n]: return False elif color[n] == -1: if color[node] == 0: color[n] = 1 else: color[n] = 0 q.append(n) return True
is-graph-bipartite
Easy python solution using BFS
i-haque
0
1
is graph bipartite
785
0.527
Medium
12,784
https://leetcode.com/problems/is-graph-bipartite/discuss/2824455/Python-BFS
class Solution: def isBipartite(self, adj: List[List[int]]) -> bool: color = [False for _ in range(len(adj))] visited = set() ok = True def bfs(start): nonlocal ok queue = deque() queue.append(start) visited.add(start) while queue and ok: node = queue.pop() for neighbor in adj[node]: if neighbor in visited: if color[node] == color[neighbor]: ok = False return else: color[neighbor] = not color[node] visited.add(neighbor) queue.append(neighbor) for i in range(len(adj)): bfs(i) return ok def isBipartite(self, adj: List[List[int]]) -> bool: color = [False for _ in range(len(adj))] visited = set() ok = True def dfs(node): nonlocal ok if not ok: return visited.add(node) for neighbor in adj[node]: if neighbor in visited: if color[node] == color[neighbor]: ok = False return else: color[neighbor] = not color[node] dfs(neighbor) for i in range(len(adj)): dfs(i) return ok
is-graph-bipartite
Python BFS
Farawayy
0
1
is graph bipartite
785
0.527
Medium
12,785
https://leetcode.com/problems/is-graph-bipartite/discuss/2822072/DFS-in-Python
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: num = range(len(graph)) visited = [False for i in num] colors = visited.copy() isBi = True def traverse(n): nonlocal isBi if not isBi: return visited[n] = True for neighbor in graph[n]: if not visited[neighbor]: colors[neighbor] = not colors[n] traverse(neighbor) else: if colors[neighbor] == colors[n]: isBi = False return for i in num: if not visited[i]: traverse(i) return isBi
is-graph-bipartite
DFS in Python
ychhhen
0
2
is graph bipartite
785
0.527
Medium
12,786
https://leetcode.com/problems/is-graph-bipartite/discuss/2821651/Judgment-dichotomy-chart
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: self.ok = True #final result n = len(graph) self.color = [True]*n #record the color of node self.visited = [False]*n #record if the node is visited for v in range(n): self.traverse(graph,v) return self.ok def traverse(self,graph,v): if self.ok is False: return self.visited[v] = True for w in graph[v]: if self.visited[w] is False: #paint node w self.color[w] = not self.color[v] self.traverse(graph,w) else: if self.color[w] == self.color[v]: self.ok = False return
is-graph-bipartite
Judgment dichotomy chart
Romantic_taxi_driver
0
1
is graph bipartite
785
0.527
Medium
12,787
https://leetcode.com/problems/is-graph-bipartite/discuss/2819952/Python3-both-BFS-and-DFS-methods.
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: # Method2: DFS. visited = [0] * len(graph) def isDFSCheckNeigh(node, color): if visited[node] != 0: # Already visited return visited[node] == color visited[node] = color for neigh in graph[node]: if isDFSCheckNeigh(neigh, -visited[node]) == False: return False return True for i in range(len(graph)): if visited[i] != 0: # Already visited continue if isDFSCheckNeigh(i, 1) == False: return False return True
is-graph-bipartite
[Python3] both BFS and DFS methods.
Cceline00
0
1
is graph bipartite
785
0.527
Medium
12,788
https://leetcode.com/problems/is-graph-bipartite/discuss/2778138/Python-DFS
class Solution(object): def isBipartite(self, graph): # used as both visited and color color = {} for node in range(len(graph)): if node in color: continue stack = [node] color[node] = True while stack: node = stack.pop() for i in graph[node]: if i not in color: color[i] = not color[node] stack.append(i) elif color[i] == color[node]: return False return True
is-graph-bipartite
[Python] DFS
i-hate-covid
0
1
is graph bipartite
785
0.527
Medium
12,789
https://leetcode.com/problems/is-graph-bipartite/discuss/2736310/Python-DFS-solution
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: seen = {} for node in range(len(graph)): if node not in seen: stack = [node] seen[node] = 0 while stack: cur = stack.pop() for neighbor in graph[cur]: # if not seen: set the color and add to stack if neighbor not in seen: stack.append(neighbor) seen[neighbor] = seen[cur]^1 # if seen: check if the color is the same elif seen[neighbor] == seen[cur]: return False return True
is-graph-bipartite
Python DFS solution
gcheng81
0
2
is graph bipartite
785
0.527
Medium
12,790
https://leetcode.com/problems/is-graph-bipartite/discuss/2734056/Python-or-simple-DFS
class Solution: def traverse(self, painting, graph, now_point, colors): painting[now_point] = colors # print(now_point, colors) for i in graph[now_point]: if painting[i] == 0: self.traverse(painting, graph, i, colors*(-1)) else: if painting[i] == colors: self.flag = False # print(self.flag) return def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) painting = [0 for _ in range(n)] self.flag = True for i in range(n): if painting[i] == 0: self.traverse(painting, graph, i, 1) if not self.flag: return self.flag return self.flag
is-graph-bipartite
Python | simple DFS
lucy_sea
0
1
is graph bipartite
785
0.527
Medium
12,791
https://leetcode.com/problems/is-graph-bipartite/discuss/2730193/Python-Simple-Recursive-Solution
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: self.Bipartite = True self.visited = [False for _ in range(len(graph))] self.color = [False for _ in range(len(graph))] def traverse(node): if self.visited[node] or not self.Bipartite: return self.visited[node] = True for neighbour in graph[node]: # color the opposite color if not seen if not self.visited[neighbour]: self.color[neighbour] = not self.color[node] traverse(neighbour) # if seen, check if the color is the same else: if self.color[neighbour] == self.color[node]: self.Bipartite = False for i in range(len(graph)): traverse(i) return self.Bipartite
is-graph-bipartite
Python Simple Recursive Solution
Rui_Liu_Rachel
0
4
is graph bipartite
785
0.527
Medium
12,792
https://leetcode.com/problems/is-graph-bipartite/discuss/2704276/Python-%2B-Easy-to-understand%2B-Detailed-explanation
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: ok = True # whether graph is bipartite visited = [False for x in range(len(graph))] color = [False for x in range(len(graph))] # store color of each node def traverse(graph,s): nonlocal ok, visited, color if not ok: # if not bipartite return # end traversing visited[s] = True for edge in graph[s]: if not visited[edge]: color[edge] = ~color[s] traverse(graph, edge) # 相邻节点 w 已经被访问过 #根据 v 和 w 的颜色判断是否是二分图 else: if color[edge] == color[s]: # 颜色一样 ok = False # 因为图不一定是联通的,可能存在多个子图 # 所以要把每个节点都作为起点进行一次遍历 # 如果发现任何一个子图不是二分图,整幅图都不算二分图 for i in range(len(graph)): if not visited[i]: traverse(graph, i) return ok
is-graph-bipartite
Python + Easy to understand+ Detailed explanation
Michael_Songru
0
1
is graph bipartite
785
0.527
Medium
12,793
https://leetcode.com/problems/is-graph-bipartite/discuss/2694109/BFS-solution-in-python
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: color=[-1]*len(graph) for i in range(len(graph)): if color[i]==-1: color[i]=1 queue=deque() queue.append(i) while queue: cur=queue.popleft() for node in graph[cur]: if color[node]==-1: color[node]=1-color[cur] queue.append(node) elif color[node]==color[cur]: return False return True
is-graph-bipartite
BFS solution in python
shashank_2000
0
8
is graph bipartite
785
0.527
Medium
12,794
https://leetcode.com/problems/is-graph-bipartite/discuss/2670810/Simple-BFS-python-solution-using-deque
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: q = deque([]) for v in range(len(graph)): q.append(v) A, B = {v}, set() while q: for i in range(len(q)): node = q.popleft() for neigh in graph[node]: if neigh in A: return False if neigh in B: continue q.append(neigh) B.add(neigh) A, B = B, A return True
is-graph-bipartite
Simple BFS python solution using deque
whimsical
0
4
is graph bipartite
785
0.527
Medium
12,795
https://leetcode.com/problems/is-graph-bipartite/discuss/2480958/python3-bfs
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) colors = [-1 for _ in range(n)] def bfs(node): colors[node] = 1 q = [node] while len(q): currNode = q.pop(0) newColor = 1 if colors[currNode] == 0 else 0 for nei in graph[currNode]: if colors[nei] == -1: colors[nei] = newColor q.append(nei) elif colors[nei] == colors[currNode]: return False return True print(colors) for i in range(n): if colors[i] == -1: if not bfs(i): return False print(colors) return True
is-graph-bipartite
python3 - bfs
gurucharandandyala
0
8
is graph bipartite
785
0.527
Medium
12,796
https://leetcode.com/problems/is-graph-bipartite/discuss/2480949/python-3-DFS
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) colors = [-1 for _ in range(n)] def isValid(node,color): for nei in graph[node]: if colors[nei] == color: return False return True def dfs(node,color): if not isValid(node,color): return False colors[node] = color newColor = 1 if color == 0 else 0 for nei in graph[node]: if colors[nei] == -1: res = dfs(nei,newColor) if not res: return False elif colors[nei] == color: return False return True for i in range(n): if colors[i] == -1: if not dfs(i,0): return False return True
is-graph-bipartite
python 3 - DFS
gurucharandandyala
0
12
is graph bipartite
785
0.527
Medium
12,797
https://leetcode.com/problems/is-graph-bipartite/discuss/2430988/Python-DFS-95-Faster
class Solution(object): def isBipartite(self, graph): color = {} visited = set() def dfs(i): for child in graph[i]: if child in color: if color[child] == color[i]: return False else: color[child] = color[i]^1 if not dfs(child): return False return True for i in range(len(graph)): if i not in color: color[i] = 1 if not dfs(i): return False return True
is-graph-bipartite
Python DFS 95% Faster
Abhi_009
0
40
is graph bipartite
785
0.527
Medium
12,798
https://leetcode.com/problems/is-graph-bipartite/discuss/2331001/JavaC%2B%2BPythonJavaScriptKotlinSwiftO(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022
class Solution: def isBipartite(self, graph: list[list[int]]) -> bool: vis = [False for n in range(0, len(graph))] while sum(vis) != len(graph): # Since graph isn't required to be connected this process needs to be repeated ind = vis.index(False) # Find the first entry in the visited list that is false vis[ind] = True grp = {ind:True} # initialize first node as part of group 1 q = [ind] # Add current index to queue while q: # Go to each node in the graph u = q.pop(0) for v in graph[u]: # Go to each vertice connected to the current node if vis[v] == True: # If visited check that it is in the opposite group of the current node if grp[u] == grp[v]: return False # If a single edge does not lead to a group change return false else: # If not visited put v in opposite group of u, set to visited, and append to q vis[v] = True grp[v] = not grp[u] q.append(v) return True
is-graph-bipartite
[Java/C++/Python/JavaScript/Kotlin/Swift]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022
cucerdariancatalin
0
14
is graph bipartite
785
0.527
Medium
12,799