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/flatten-a-multilevel-doubly-linked-list/discuss/652275/Python3-recursive-and-iterative-solution | class Solution:
def flatten(self, head: 'Node') -> 'Node':
def fn(node, default=None):
"""Return head of (recursively) flattened linked list"""
if not node: return default
node.next = fn(node.child, fn(node.next, default))
if node.next: node.next.prev = node
node.child = None
return node
return fn(head) | flatten-a-multilevel-doubly-linked-list | [Python3] recursive & iterative solution | ye15 | 3 | 118 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,600 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/652275/Python3-recursive-and-iterative-solution | class Solution:
def flatten(self, head: 'Node') -> 'Node':
prev = None
stack = [head]
while stack:
node = stack.pop()
if node:
node.prev = prev
if prev: prev.next = node
prev = node
stack.append(node.next)
stack.append(node.child)
node.child = None
return head | flatten-a-multilevel-doubly-linked-list | [Python3] recursive & iterative solution | ye15 | 3 | 118 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,601 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/652275/Python3-recursive-and-iterative-solution | class Solution:
def flatten(self, head: 'Node') -> 'Node':
node = head
stack = []
while node:
if node.child:
if node.next: stack.append(node.next)
node.next = node.child
node.next.prev = node
node.child = None
elif not node.next and stack:
node.next = stack.pop()
node.next.prev = node
node = node.next
return head | flatten-a-multilevel-doubly-linked-list | [Python3] recursive & iterative solution | ye15 | 3 | 118 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,602 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/2017920/Python-Intuitive-Recursive-Approach-with-Detailed-Explanation | class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
if not head:
return
def dfs(node):
if node.child: #if node has a child, we go down
temp = node.next # store the next node to temp
node.next = node.child # current node's next points to its child
node.child.prev = node # current node's child's prev points to current node
last = dfs(node.child) # dfs the list that starts with current node's child (i.e., list with one level down), this will return the end node of the list one level below
node.child = None # assign null to child
if temp and last: # if the original next node is not null and the last node of the list one level below are both not null, we should connect them
last.next = temp
temp.prev = last
return dfs(temp) # after connection, we should keep searching down the list on the current level
else: # if the original next node is Null, we can't append it to our current list. As a result, we can simply return the last node from below so we can connect it with the list one level above.
return last
elif node.next: # if there is a next element, go right
return dfs(node.next)
else: # we've hit the end of the current list, return the last node
return node
dfs(head)
return(head)
`` | flatten-a-multilevel-doubly-linked-list | Python Intuitive Recursive Approach with Detailed Explanation | lukefall425 | 2 | 67 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,603 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/2552169/Python-runtime-O(n)-memory-O(n)-(92.89) | class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
cur = head
while cur:
if cur.child == None:
cur = cur.next
else:
subHead = self.flatten(cur.child)
nextNode = cur.next
subHead.prev = cur
cur.next = subHead
cur.child = None
while cur.next:
cur = cur.next
if nextNode:
cur.next = nextNode
nextNode.prev = cur
return head | flatten-a-multilevel-doubly-linked-list | Python, runtime O(n) memory O(n) (92.89%) | tsai00150 | 1 | 126 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,604 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/2552169/Python-runtime-O(n)-memory-O(n)-(92.89) | class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
if not head:
return None
cur = head
nextNode = []
pre = None
while cur or nextNode:
if cur:
if cur.child == None:
pre = cur
cur = cur.next
else:
if cur.next:
nextNode.append(cur.next)
cur.next = cur.child
cur.child.prev = cur
cur.child = None
else:
pre.next = nextNode.pop()
pre.next.prev = pre
cur = pre.next
return head | flatten-a-multilevel-doubly-linked-list | Python, runtime O(n) memory O(n) (92.89%) | tsai00150 | 1 | 126 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,605 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1719944/O(N)-time-O(1)-space-Python-recursive-solution | class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
if not head:
return
traverse = head
while traverse:
if traverse.child: # if there is child, recursively call flatten() on child
child_linked_list = self.flatten(traverse.child)
traverse_child = child_linked_list
while traverse_child.next:
traverse_child = traverse_child.next # iterate to last element of child linked list
traverse_child.next = traverse.next # combine the last child node to parent next node, for .next and .prev
if traverse.next:
traverse.next.prev = traverse_child
traverse.next = child_linked_list
child_linked_list.prev = traverse
traverse.child = None
traverse = traverse.next
return head | flatten-a-multilevel-doubly-linked-list | O(N) time, O(1) space Python recursive solution | winnietheflu | 1 | 52 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,606 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1551313/DFS-with-recursion-or-O(n)-O(n) | class Solution(object):
def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
nodes = []
def dfs(node):
nodes.append(node)
if node.child:
dfs(node.child)
if node.next:
dfs(node.next)
if head == None: return None
dfs(head)
for i in range(len(nodes)):
nodes[i].next = nodes[i+1] if i+1 < len(nodes) else None
nodes[i].prev = nodes[i-1] if i-1 >= 0 else None
nodes[i].child = None
return nodes[0] | flatten-a-multilevel-doubly-linked-list | DFS with recursion | O(n), O(n) | nomofika | 1 | 113 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,607 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/2713706/Easiest-Method-or-Beginner's-Friendly-or-Python | class Solution(object):
def flatten(self, head):
if not(head): return head
def rec(values, head):
while head:
values.append(head.val)
if head.child is not None:
rec(values, head.child)
head = head.next
values = []
rec(values, head)
head = tail = Node(values[0])
for i in range(1, len(values)):
newNode = Node(values[i])
tail.next = newNode
newNode.prev = tail
tail = tail.next
return head | flatten-a-multilevel-doubly-linked-list | Easiest Method | Beginner's Friendly | Python | its_krish_here | 0 | 17 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,608 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/2429564/16-lines-of-python-code-greater-94-faster-%3A) | class Solution(object):
def flatten(self, head):
self.end = Node(-1) # used a global val for each recursion so that i can have the last node in each level
str1 = head
while str1:
next1 = str1.next
if str1.child != None: #checking if the the node has a child
str1.next = self.flatten(str1.child) # 2.next -> 4
str1.child.prev,str1.child = str1,None # as per diagram 4.next -> 2 and 2's child -> None
self.end.next = next1 # 5.next -> 3 as per diagram
if next1: #next1 might be NONE.
next1.prev = self.end #3.prev -> 5
str1 = self.end
self.end = str1 #holds the last node.
str1 = str1.next
return head #same flow if the list has more childs | flatten-a-multilevel-doubly-linked-list | 16 lines of python code => 94% faster :) | sudharshan1706 | 0 | 37 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,609 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/2320700/Help-List-Not-Valid | class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
current = head
tail = []
children = 0
prev = None
while current or children:
if not current and children:
child_tail = tail.pop()
child_tail.prev = prev
prev.next = child_tail
children -= 1
prev = current
current = child_tail
continue
if current.child:
tail.append(current.next)
current.next = current.child
current.child = None
children += 1
prev = current
current = current.next
return head | flatten-a-multilevel-doubly-linked-list | Help - List Not Valid | fissioner | 0 | 17 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,610 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/2148873/Python-O(N)-Solution-Using-Stack | class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
stack = []
curr = head
prev = None
while curr:
curr.prev = prev
if curr.next:
stack.append(curr.next)
if curr.child:
stack.append(curr.child)
curr.child = None
prev = curr
if stack:
curr.next = stack.pop()
curr = curr.next
return head | flatten-a-multilevel-doubly-linked-list | Python O(N) Solution Using Stack | bretticus-mc | 0 | 34 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,611 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/2029186/Python-DFS-simple-solution | class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
if not head: return None
ans = []
self.dfs(head, ans)
for i in range(len(ans)-1): # Build the new linked list
ans[i].next = ans[i+1]
ans[i].child = None
ans[i+1].prev = ans[i]
ans[-1].next = None
return ans[0]
def dfs(self, node, ans): # The solution is to use dfs to traverse this graph
ans.append(node)
if node.child:
self.dfs(node.child, ans)
if node.next:
self.dfs(node.next, ans) | flatten-a-multilevel-doubly-linked-list | Python DFS simple solution | FlorinnC1 | 0 | 63 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,612 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1984213/Python-oror-Intuitive-Iterative-Solution | class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
prev = Node(0)
prev.next = head
curr = head
while curr:
if curr.child:
curr.child.prev = curr
temp = curr.next
curr.next = curr.child
child = curr.child
while child.next:
child = child.next
child.next = temp
if child.next:
child.next.prev = child
curr.child = None
curr = curr.next
return prev.next | flatten-a-multilevel-doubly-linked-list | Python || Intuitive Iterative Solution | morpheusdurden | 0 | 51 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,613 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1897624/Python-straight-forward-solution-with-a-few-comment | class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
if not head:
return None
def get_head_and_tail(node): # Once there exist a child, we adjust node.next to child_head,
head = node # and child_tail.next to node.next
while node.next: # That's why I write this function to get head and tail.
node = node.next
tail = node
return head, tail
dummy = head
while head:
if head.child:
self.flatten(head.child)
child_head, child_tail = get_head_and_tail(head.child) # Getting head and tail of child
temp = head.next
head.next, child_head.prev = child_head, head # Adjustment of node, node.next, child_head, child_tail
child_tail.next = temp
if temp: # check whether node.next is None
temp.prev = child_tail
head.child = None
head = temp
else:
head = head.next
return dummy | flatten-a-multilevel-doubly-linked-list | Python straight - forward solution with a few comment | byroncharly3 | 0 | 59 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,614 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1551536/Python-3-oror-Stack-oror-Easy-Understanding | class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head:
return head
stack = []
temp = head
while True:
if not temp:
break
if not temp.next:
if stack:
node = stack.pop()
temp.next = node
if node:
node.prev = temp
if temp.child:
stack.append(temp.next)
temp.next = temp.child
temp.child.prev = temp
temp.child = None
temp = temp.next
return head | flatten-a-multilevel-doubly-linked-list | Python 3 || Stack || Easy Understanding | Sheersendu | 0 | 50 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,615 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1551436/Python3-solution | class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head: return head
def dfs(node):
visited.append(node)
if node.child and node.child not in visited:
dfs(node.child)
if node.next and node.next not in visited:
dfs(node.next)
visited = []
dfs(head)
p = Node()
for node in visited:
node.child = None
p.next = node
node.prev = p
p = node
head.prev = None
return head | flatten-a-multilevel-doubly-linked-list | Python3 solution | dalechoi | 0 | 17 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,616 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1551151/Python-Two-version-of-solution-with-using-stack | class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head:
return None
dummy = Node(0, None, None, None)
stack = [head]
prev = dummy
while stack:
cur = stack.pop()
cur.prev = prev
prev.next = cur
if cur.next:
stack.append(cur.next)
if cur.child:
stack.append(cur.child)
cur.child = None
prev = cur
dummy.next.prev = None
return dummy.next | flatten-a-multilevel-doubly-linked-list | [Python] Two version of solution with using stack | maosipov11 | 0 | 9 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,617 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1551151/Python-Two-version-of-solution-with-using-stack | class Solution:
def flatten(self, head: 'Node') -> 'Node':
dummy = Node(0, None, head, None)
stack = []
prev = None
while head or stack:
if not head and stack:
_next = stack.pop()
prev.next = _next
_next.prev = prev
head = _next
continue
prev = head
if not head.child:
head = head.next
continue
if head.next:
stack.append(head.next)
child = head.child
head.next = child
child.prev = head
head.child = None
head = child
return dummy.next | flatten-a-multilevel-doubly-linked-list | [Python] Two version of solution with using stack | maosipov11 | 0 | 9 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,618 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1056478/Python-DFS-stack-construct-DLL-from-list-(28ms) | class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head: return head
d = []
stack = [head]
while stack:
n = stack.pop()
d.append(n.val)
if n.next:
stack.append(n.next)
if n.child:
stack.append(n.child)
res = t = None
for n in d:
if not res:
t = Node(n)
res = t
else:
t.next = Node(n, t)
t = t.next
return res | flatten-a-multilevel-doubly-linked-list | Python - DFS stack - construct DLL from list (28ms) | kysr007 | 0 | 95 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,619 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/537234/Python3-simple-solution | class Solution:
def flatten(self, head: 'Node') -> 'Node':
self.walk(head)
return head
def walk(self, node: 'Node') -> 'Node':
if node is None:
return None
if node.child is not None:
child_tail = self.walk(node.child)
child_tail.next = node.next
node.next, node.child.prev = node.child, node
node.child = None
if child_tail.next is None:
return child_tail
else:
child_tail.next.prev = child_tail
return self.walk(child_tail.next)
elif node.next is not None:
return self.walk(node.next)
else:
return node | flatten-a-multilevel-doubly-linked-list | Python3 simple solution | tjucoder | 0 | 54 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,620 |
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/469610/python-recursive-dfs | class Solution:
def flatten(self, head: 'Node') -> 'Node':
if head is None:
return None
return self.dfs(head)
def dfs(self, node):
original_next = node.next
tail = node
if node.child:
node.next = self.dfs(node.child)
node.next.prev = node
node.child = None
tail = node.next
while tail.next:
tail = tail.next
if original_next:
tail.next = self.dfs(original_next)
tail.next.prev = tail
return node | flatten-a-multilevel-doubly-linked-list | python recursive dfs | anonymouscoder1555 | 0 | 33 | flatten a multilevel doubly linked list | 430 | 0.595 | Medium | 7,621 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769493/SIMPLE-PYTHON-SOLUTION-USING-BFS | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
dic=defaultdict(lambda :0)
lst=[[start,0]]
dic[start]=1
while lst:
x,d=lst.pop(0)
if x==end:
return d
for i in range(len(bank)):
ct=0
for j in range(8):
if x[j]!=bank[i][j]:
ct+=1
if ct==1:
if dic[bank[i]]==0:
lst.append([bank[i],d+1])
dic[bank[i]]=1
return -1 | minimum-genetic-mutation | SIMPLE PYTHON SOLUTION USING BFS | beneath_ocean | 2 | 148 | minimum genetic mutation | 433 | 0.52 | Medium | 7,622 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2097023/Python-3.10%3A-DFS-BFS.-VERY-SHORT. | class Solution:
def minMutation(self, start: str, end: str, bank: list[str]) -> int:
bank = set(bank) | {start}
def dfs(st0, cnt):
if st0 == end:
return cnt
bank.remove(st0)
for i, ch0 in enumerate(st0):
for ch1 in "ACGT":
if (
ch0 != ch1
and (st1 := st0[:i] + ch1 + st0[i + 1 :]) in bank
and (res := dfs(st1, cnt + 1)) != -1
):
return res
return -1
return dfs(start, 0) | minimum-genetic-mutation | Python 3.10: DFS, BFS. VERY SHORT. | miguel_v | 2 | 156 | minimum genetic mutation | 433 | 0.52 | Medium | 7,623 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2097023/Python-3.10%3A-DFS-BFS.-VERY-SHORT. | class Solution:
def minMutation(self, start: str, end: str, bank: list[str]) -> int:
bank = set(bank)
dq = deque([(start, 0)])
while dq:
st0, cnt = dq.popleft()
if st0 == end:
return cnt
for i, ch0 in enumerate(st0):
for ch1 in "ACGT":
if ch0 != ch1 and (st1 := st0[:i] + ch1 + st0[i + 1 :]) in bank:
bank.remove(st1)
dq.append((st1, cnt + 1))
return -1 | minimum-genetic-mutation | Python 3.10: DFS, BFS. VERY SHORT. | miguel_v | 2 | 156 | minimum genetic mutation | 433 | 0.52 | Medium | 7,624 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/1511660/Well-Coded-oror-Easy-to-understand-oror-91-faster-oror-Beginners | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
if end not in bank:
return -1
q = deque()
q.append((start,0))
while q:
tochk,limit = q.popleft()
if tochk == end:
return limit
w = 0
while w<len(bank):
word = bank[w]
c = 0
for i in range(8):
if tochk[i]!=word[i]:
c+=1
if c==1:
q.append((word,limit+1))
bank.remove(word)
continue
w+=1
return -1 | minimum-genetic-mutation | ππ Well-Coded || Easy-to-understand || 91% faster || Beginners π | abhi9Rai | 2 | 224 | minimum genetic mutation | 433 | 0.52 | Medium | 7,625 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2768754/Python3-Simple-BFS-for-beginners-with-explanation-step-by-step | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
bank = set(bank)
if end not in bank: return -1
queue = deque()
queue.append((start,0))
while queue:
word,steps = queue.popleft()
if word == end: return steps
for i,ch in enumerate(word):
for new_ch in "ACGT":
new_word = word[:i] + new_ch + word[i+1:]
if new_word in bank:
queue.append((new_word,steps+1))
bank.remove(new_word)
return -1 | minimum-genetic-mutation | [Python3] Simple BFS for beginners with explanation step by step | shriyansnaik | 1 | 50 | minimum genetic mutation | 433 | 0.52 | Medium | 7,626 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/1184400/Python-Get's-the-job-done | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
def is_mutation(s, e):
s = collections.Counter([(i, c) for i, c in enumerate(s)])
e = collections.Counter([(i, c) for i, c in enumerate(e)])
return sum(((s | e) - (s & e)).values()) == 2
queue = collections.deque([(start, 0, bank)])
while queue:
s, num_mutations, bank = queue.popleft()
if s == end:
return num_mutations
for i in bank:
if not is_mutation(s, i): continue
queue.append((i, num_mutations+1, [j for j in bank if j != i]))
return -1 | minimum-genetic-mutation | Python, Get's the job done | dev-josh | 1 | 214 | minimum genetic mutation | 433 | 0.52 | Medium | 7,627 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/1184400/Python-Get's-the-job-done | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
graph = {s : collections.Counter([(i, c) for i, c in enumerate(s)]) for s in [start, end] + bank}
mutation = lambda s, e: sum(((graph[s] | graph[e]) - (graph[s] & graph[e])).values()) == 2
queue = collections.deque([("", start, 0)])
while queue:
prev, s, count = queue.popleft()
if s == end:
return count
for i in bank:
if i == prev or not mutation(s, i): continue
queue.append((s, i, count+1))
return -1 | minimum-genetic-mutation | Python, Get's the job done | dev-josh | 1 | 214 | minimum genetic mutation | 433 | 0.52 | Medium | 7,628 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/704135/Python3-bi-directional-bfs-(97.38) | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
graph = {}
for gene in bank:
for i in range(8):
graph.setdefault(gene[:i] + "*" + gene[i+1:], []).append(gene)
ans = 0 # count of mutations
fwd, bwd = {start}, {end} # forward & backward frontiers
seen = {start, end}
while fwd and bwd: # bi-directional bfs
ans += 1
if len(fwd) > len(bwd): fwd, bwd = bwd, fwd # grow smaller frontier
newf = set()
for gene in fwd:
for i in range(8):
for gg in graph.get(gene[:i] + "*" + gene[i+1:], []):
if gg in bwd: return ans # meeting of two frontiers
if gg not in seen:
newf.add(gg)
seen.add(gg)
fwd = newf
return -1 | minimum-genetic-mutation | [Python3] bi-directional bfs (97.38%) | ye15 | 1 | 165 | minimum genetic mutation | 433 | 0.52 | Medium | 7,629 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2797529/BFS-Search-with-Tuples! | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
def canMutate(gene1, gene2):
mutationsNeeded = 0
for i in range(len(gene1)):
if gene1[i] != gene2[i]:
mutationsNeeded += 1
return mutationsNeeded
mut_count = 0
depth = 0
seen = set()
mutate_q = [(start, 0)] #Each mutation keeps track of how "deep" it is with a tuple.
while len(mutate_q) > 0:
current_mut = mutate_q[0]
if canMutate(current_mut[0], end) == 0:
return current_mut[1] #Return the depth of the current mutation if it matches the end mutation.
for mut in bank:
if canMutate(current_mut[0], mut) == 1 and mut not in seen:
mutate_q.append((mut, current_mut[1] + 1)) #Add one to depth every time we append to the queue.
seen.add(mut)
mutate_q.pop(0)
return -1 | minimum-genetic-mutation | BFS Search with Tuples! | mephiticfire | 0 | 2 | minimum genetic mutation | 433 | 0.52 | Medium | 7,630 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2784832/python-solution-with-comments | class Solution:
def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int:
#searching in set is faster than in array
bank = set(bank)
#since each valid gene should be in bank
#so if endgene is not in the bank hence we cannot acheive it ever
if endGene not in bank:
return -1
visited = set()
visited.add(startGene)
q=[[startGene,0]]
while len(q)!=0:
for i in range(len(q)):
node,level = q.pop(0)
#we check each valid gene and if it's equal to endgene then return its level
if node == endGene:
return level
#make all the 32 combinations for the node
for i in range(len(node)):
for letter in 'ACGT':
new_gene = node[:i] + letter + node[i+1:]
if new_gene not in visited and new_gene in bank:
q.append([new_gene,level+1])
visited.add(new_gene)
return -1 | minimum-genetic-mutation | python solution with comments | user9781TM | 0 | 2 | minimum genetic mutation | 433 | 0.52 | Medium | 7,631 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2771640/Python3-or-BFS-with-bitmasks | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
def distanceOne(gene1: str, gene2: str) -> bool:
differenceFound = False
for char1, char2 in zip(gene1, gene2):
if char1 != char2:
if not differenceFound:
differenceFound = True
else:
return False
return differenceFound
def possibleNext(gene: str, visited: int) -> (str, int):
for i, bankGene in enumerate(bank):
if not (1 << i) & visited and distanceOne(gene, bankGene):
yield (bankGene, visited | (1 << i))
geneStack = collections.deque(possibleNext(start, 0))
while geneStack:
gene, visited = geneStack.popleft()
if gene == end:
return bin(visited)[2:].count("1")
geneStack.extend(possibleNext(gene, visited))
return -1 | minimum-genetic-mutation | Python3 | BFS with bitmasks | sr_vrd | 0 | 3 | minimum genetic mutation | 433 | 0.52 | Medium | 7,632 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2771631/Python-DFS-Solution | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
if end not in bank:
return 0 if (start == end) else -1
def difference(A, B):
c = 0
for i in range(len(A)):
if A[i] != B[i]:
c+=1
return c
bank += [start]
# create the graph
adj = collections.defaultdict(set)
for i in range(len(bank)-1):
for j in range(len(bank)):
if difference(bank[i], bank[j]) == 1:
adj[bank[i]].add(bank[j])
adj[bank[j]].add(bank[i])
best = float('inf')
seen = {}
def dfs(node, count):
nonlocal end, best
if node==end:
best = min(best, count)
seen[node] = count
for nei in adj[node]:
if nei not in seen or seen[nei] > count+1: # should explore it IF current path to nei is SHORTER. (note that if we used BFS, this second condition would be true by nature)
dfs(nei, count+1)
dfs(start, 0)
return best if (best != float('inf')) else -1 | minimum-genetic-mutation | Python DFS Solution | dyxuki | 0 | 3 | minimum genetic mutation | 433 | 0.52 | Medium | 7,633 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2771184/Python-BFS-Solution | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
if start not in bank:
bank.append(start)
queue = [(start, 0)]
visited = set()
while len(queue) > 0:
curGene, mutation = queue.pop(0)
if curGene not in visited:
visited.add(curGene)
for nxtGene in self.validMutations(curGene, bank):
if nxtGene == end:
return mutation + 1
if nxtGene not in visited:
queue.append([nxtGene, mutation + 1])
return -1
def validMutations(self, gene: str, bank: List[str]) -> List[str]:
valid = []
for nxtGene in bank:
if nxtGene == gene:
continue
diff = 0
for i in range(len(gene)):
if gene[i] != nxtGene[i]:
diff += 1
if diff == 1: valid.append(nxtGene)
return valid | minimum-genetic-mutation | Python BFS Solution | gequalspisquared | 0 | 25 | minimum genetic mutation | 433 | 0.52 | Medium | 7,634 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2770773/Pyhton-BFS | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
n = len(start)
q = deque([(start, 0)])
visited = set([start])
while q:
node, dist = q.popleft()
if node == end:
return dist
for i in range(n):
for char in "ACGT":
mutation = node[:i] + char + node[i+1:]
if mutation in bank and mutation not in visited:
q.append((mutation, dist + 1))
visited.add(mutation)
return -1 | minimum-genetic-mutation | Pyhton, BFS | blue_sky5 | 0 | 6 | minimum genetic mutation | 433 | 0.52 | Medium | 7,635 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2770549/BFS-Fast-and-Easy-Solution | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
bank = set(bank)
if end not in bank:
return -1
q = deque([(start, 0)])
visited = set(start)
while q:
gene, no_of_mutation = q.popleft()
if gene == end:
return no_of_mutation
for i in range(len(gene)):
for letter in 'ACGT':
new_gene = gene[ : i] + letter + gene[i + 1 : ]
if new_gene not in visited and new_gene in bank:
visited.add(new_gene)
q.append((new_gene, no_of_mutation + 1))
return -1 | minimum-genetic-mutation | BFS - Fast and Easy Solution | user6770yv | 0 | 4 | minimum genetic mutation | 433 | 0.52 | Medium | 7,636 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2770446/Python-DFS | class Solution(object):
def dfs(self, current, end, mutations, remaining_bank):
if current == end:
return mutations
if len(remaining_bank) == 0:
return -1
mutation_list = []
for gene in remaining_bank:
genes_separated = sum([gene[i] != current[i] for i in range(len(gene))])
if genes_separated == 1:
sep_mutations = self.dfs(gene, end, mutations + 1 , [i for i in remaining_bank if i != gene])
if sep_mutations != -1:
mutation_list.append(sep_mutations)
return min(mutation_list) if len(mutation_list) != 0 else -1
def minMutation(self, start, end, bank):
mutations = self.dfs(start, end, 0, bank)
return mutations | minimum-genetic-mutation | Python DFS | fhormel | 0 | 18 | minimum genetic mutation | 433 | 0.52 | Medium | 7,637 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2770377/Python-(Faster-than-96)-or-BFS-solution | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
count = 0
visited = set()
visited.add(start)
queue = deque()
queue.append(start)
while queue:
for _ in range(len(queue)):
word = queue.popleft()
if word == end:
return count
for ch in 'ACGT':
for i in range(len(word)):
newWord = list(word)
newWord[i] = ch
newWord = ''.join(newWord)
if newWord not in visited and newWord in bank:
queue.append(newWord)
visited.add(newWord)
count += 1
return -1 | minimum-genetic-mutation | Python (Faster than 96%) | BFS solution | KevinJM17 | 0 | 6 | minimum genetic mutation | 433 | 0.52 | Medium | 7,638 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2770182/USEPYTHON | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
def checkNeighbor(a,b):
return sum([1 for i in range(len(a)) if a[i]!=b[i]]) == 1
q = deque([start])
visited = {start}
### use extra variable to store mutations
mutations = 0
while q:
### use for loop to check all nodes in the q
### so that after the for loop, we can increment mutations by 1
for _ in range(len(q)):
cur = q.popleft()
if cur == end:
return mutations
for nei in bank:
if checkNeighbor(cur,nei) and nei not in visited:
visited.add(nei)
q.append(nei)
### increment mutations by 1
mutations += 1
return -1 | minimum-genetic-mutation | USEPYTHON | iamdiinesh | 0 | 5 | minimum genetic mutation | 433 | 0.52 | Medium | 7,639 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2770019/Deque-oror-Python3 | class Solution(object):
def minMutation(self, start, end, bank):
bfsQueue = deque([(start, 0)])
validGene = set(bank)
while bfsQueue:
curGene, curStep = bfsQueue.popleft()
if curGene == end:
return curStep
for i in range(8):
for nucleoBase in ('A', 'C', 'G', 'T'):
mutateGene = curGene[:i] + nucleoBase + curGene[i+1:]
if mutateGene in validGene:
validGene.remove(mutateGene)
bfsQueue.append((mutateGene, curStep + 1))
return -1 | minimum-genetic-mutation | Deque || Python3 | joshua_mur | 0 | 3 | minimum genetic mutation | 433 | 0.52 | Medium | 7,640 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769697/Python-or-Simple-and-fast-BFS-solution | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
st = defaultdict(set)
def calc_dist(a, b):
count = 0
for i in range(len(a)):
if a[i] != b[i]:
count += 1
return count
for ind, item in enumerate([start] + bank):
for ind2, item2 in enumerate([start] + bank):
if ind < ind2:
continue
if calc_dist(item, item2) == 1:
st[item].add(item2)
st[item2].add(item)
distances = {item: -1 for item in ([start] + bank)}
distances[start] = 0
q = deque([start])
while q:
cur_v = q.popleft()
for neigh_v in st[cur_v]:
if distances[neigh_v] == -1:
distances[neigh_v] = distances[cur_v] + 1
q.append(neigh_v)
try:
return distances[end]
except KeyError:
return -1 | minimum-genetic-mutation | Python | Simple and fast BFS solution | LordVader1 | 0 | 20 | minimum genetic mutation | 433 | 0.52 | Medium | 7,641 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769562/python-solution-or-BFS | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
def CountDiff(gene1, gene2):
SumOfDiff = 0
for i in range(8):
if gene1[i] != gene2[i]:
SumOfDiff += 1
return SumOfDiff
if end not in bank:
return -1
ans = float('inf')
q = deque()
q.append((start, 0))
seen = [start]
while q:
gene, dis = q.popleft()
if gene == end:
ans = min(ans, dis)
for i in range(len(bank)):
if bank[i] not in seen and CountDiff(gene, bank[i]) == 1:
q.append((bank[i], dis + 1))
seen.append(bank[i])
return -1 if ans == float('inf') else ans | minimum-genetic-mutation | python solution | BFS | maomao1010 | 0 | 14 | minimum genetic mutation | 433 | 0.52 | Medium | 7,642 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769470/python-straight-foward-solution | class Solution:
def dif_check(self, s1,s2):
return sum([1 if s1[i] != s2[i] else 0 for i in range(len(s1))])
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
bank = set(bank + [start])
visited = set()
q = collections.deque([start])
nodes = collections.defaultdict(list)
for gene in bank:
for g_temp in bank - {gene}:
if self.dif_check(g_temp, gene) == 1:
nodes[gene].append(g_temp)
#bfs
mutations = 0
while q:
temp_bank = []
while q:
temp_bank.append(q.pop())
visited.add(temp_bank[-1])
for gene in temp_bank:
for node in nodes[gene]:
if node not in visited:
if node == end:
return mutations + 1
else:
q.append(node)
mutations += 1
return -1 | minimum-genetic-mutation | python straight-foward solution | gkpani97 | 0 | 14 | minimum genetic mutation | 433 | 0.52 | Medium | 7,643 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769340/Python3-or-DFS-solution | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
bank = [start]+bank
n = len(bank)
adjList = defaultdict(list)
for i in range(n):
for j in range(i+1,n):
counter = 0
for k in range(len(start)):
if(bank[i][k]!=bank[j][k]):
counter+=1
if(counter==1):
adjList[bank[i]].append(j)
adjList[bank[j]].append(i)
visitedList = [False for x in range(n)]
visitedList[0] = True
ans = [float("inf")]
DFS(start,0,bank,end,adjList,ans,visitedList)
if(ans[0]==float("inf")):
return -1
return ans[0]
def DFS(nowString,depth,bank,end,adjList,ans,visitedList):
print(nowString)
if(nowString==end):
ans[0] = min(ans[0],depth)
else:
for pos in adjList[nowString]:
if(not visitedList[pos]):
visitedList[pos] = True
DFS(bank[pos],depth+1,bank,end,adjList,ans,copy.deepcopy(visitedList)) | minimum-genetic-mutation | Python3 | DFS solution | ty2134029 | 0 | 4 | minimum genetic mutation | 433 | 0.52 | Medium | 7,644 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769204/Python-oror-Easy-Solution-oror-All-Outputs | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
queue = [[start, 0]]
ans = float('inf')
dp = {}
while queue:
p = queue.pop(0)
start = p[0]
if start not in dp:
dp[start] = True
if start == end:
ans = min(ans, p[1])
for i in range(len(start)):
for c in ["A", "C", "G", "T"]:
new_start = start[:i]+c+start[i+1:]
if new_start in bank:
queue.append([new_start, p[1] + 1])
return ans if ans != float('inf') else -1 | minimum-genetic-mutation | Python || Easy Solution || All Outputs | Rahul_Kantwa | 0 | 5 | minimum genetic mutation | 433 | 0.52 | Medium | 7,645 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769177/py3-code | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
# [1] initialize queue with starting gene
q, bank = collections.deque([(start,0)]), set(bank)
while q:
g, m = q.popleft()
if g == end : return m
# [2] try all possible mutations, namely,
# try every nucleotide in each position
for i in range(len(g)):
for n in "ATGC":
gm = g[0:i] + n + g[i+1:]
# [3] successful branches are added to
# the queue for further mutagenesis
if gm in bank:
bank.remove(gm)
q.append((gm, m+1))
return -1 | minimum-genetic-mutation | py3 code | rupamkarmakarcr7 | 0 | 5 | minimum genetic mutation | 433 | 0.52 | Medium | 7,646 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769060/python3-solution | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
def checkNeighbor(a,b):
return sum([1 for i in range(len(a)) if a[i]!=b[i]]) == 1
q = deque([start])
### initialize the empty visited set
visited = set()
mutations = 0
while q:
for _ in range(len(q)):
cur = q.popleft()
if cur == end:
return mutations
### check if cur is in visited here instead of check nei is in visited latter
if cur not in visited:
visited.add(cur)
for nei in bank:
if checkNeighbor(cur,nei):
q.append(nei)
mutations += 1
return -1 | minimum-genetic-mutation | python3 solution | avs-abhishek123 | 0 | 7 | minimum genetic mutation | 433 | 0.52 | Medium | 7,647 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2768777/Python3-Convert-States-To-Numbers | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
v = {"ACGT"[i]: i for i in range(4)}
c = lambda x: sum([v[x[i]] * (4**i) for i in range(len(x))])
d = {c(x): inf for x in bank}
st = c(start)
en = c(end)
if en not in d:
return -1
d[st] = 0
mutations = {v: [] for v in d.keys()}
for k1 in d.keys():
for k2 in d.keys():
if k2 > k1:
cnt = 0
bm = 3
for i in range(8):
if (k1 & bm) != (k2 & bm):
cnt += 1
if cnt == 2:
break
bm <<= 2
if cnt == 1:
mutations[k1].append(k2)
mutations[k2].append(k1)
visited = [st]
while visited:
cur = visited.pop(0)
cd = d[cur]
assert cd <= len(d)
for dest in mutations[cur]:
if d[dest]>cd: # it's BFS, so it should be inf unless visited
if dest == en:
return cd + 1
d[dest] = cd + 1
visited.append(dest)
return -1 | minimum-genetic-mutation | Python3 Convert States To Numbers | godshiva | 0 | 5 | minimum genetic mutation | 433 | 0.52 | Medium | 7,648 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2768716/python3-graph-sol-for-reference | class Solution:
def oneCharDiff(self, a, b):
diffcnt = 0
for i in range(len(a)):
if a[i] != b[i]:
diffcnt += 1
return diffcnt == 1
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
nb = len(bank)
graph = defaultdict(list)
for i in range(nb):
if self.oneCharDiff(bank[i], start):
graph[bank[i]].append(start)
graph[start].append(bank[i])
for i in range(nb):
for j in range(nb):
if i != j and self.oneCharDiff(bank[i], bank[j]):
graph[bank[i]].append(bank[j])
graph[bank[j]].append(bank[i])
if not graph[end]: return -1
st = [(0,start)]
w = defaultdict(lambda: float('inf'))
visited = defaultdict(bool)
while st:
dist,node = heapq.heappop(st)
visited[node] = True
for nei in graph[node]:
if w[nei] > dist+1:
w[nei] = dist+1
if not visited[nei]:
heapq.heappush(st, (w[nei], nei))
return w[end] | minimum-genetic-mutation | [python3] graph sol for reference | vadhri_venkat | 0 | 4 | minimum genetic mutation | 433 | 0.52 | Medium | 7,649 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2768694/python-solution | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
queue = []
queue.append((start, 0))
availableSequences = set(bank)
while queue:
sequence, steps = queue.pop(0)
if sequence == end:
return steps
for i in range(len(sequence)):
for char in 'ACGT':
currentSequence = sequence[:i]+char+sequence[i+1:]
if currentSequence in availableSequences:
availableSequences.remove(currentSequence)
queue.append((currentSequence, steps+1))
return -1 | minimum-genetic-mutation | python solution | MuraliChrishna | 0 | 16 | minimum genetic mutation | 433 | 0.52 | Medium | 7,650 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2238205/Python3-Solution-with-using-bfs | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
q = collections.deque()
q.append((start, 0))
bank = set(bank)
while q:
cur_mut, step = q.popleft()
if cur_mut == end:
return step
for g in 'ACGT':
for i in range(len(cur_mut)):
new_mut = cur_mut[:i] + g + cur_mut[i + 1:]
if new_mut in bank:
q.append((new_mut, step + 1))
bank.remove(new_mut)
return - 1 | minimum-genetic-mutation | [Python3] Solution with using bfs | maosipov11 | 0 | 35 | minimum genetic mutation | 433 | 0.52 | Medium | 7,651 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/2035074/Python-easy-to-read-and-understand-or-BFS | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
if end not in bank:
return -1
visit = set()
visit.add(start)
q = [start]
steps = 0
bank.append(start)
choice = ['A', 'C', 'G', 'T']
while q:
num = len(q)
for _ in range(num):
match = q.pop(0)
if match == end:
return steps
if match not in bank:
continue
for i in range(8):
for j in range(4):
temp = match[:i] + choice[j] + match[i + 1:]
if temp not in visit:
visit.add(temp)
q.append(temp)
if q: steps += 1
return -1 | minimum-genetic-mutation | Python easy to read and understand | BFS | sanial2001 | 0 | 71 | minimum genetic mutation | 433 | 0.52 | Medium | 7,652 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/1692825/WEEB-DOES-PYTHON-BFS | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
bank = set(bank)
if end not in bank: return -1
queue = deque([(start, 0)])
while queue:
curStr, steps = queue.popleft()
if curStr == end:
return steps
for i in range(len(curStr)):
for char in ["A", "C", "G", "T"]:
if curStr[i] == char: continue
newStr = curStr[:i] + char + curStr[i+1:]
if newStr in bank:
queue.append((newStr, steps + 1))
return -1 | minimum-genetic-mutation | WEEB DOES PYTHON BFS | Skywalker5423 | 0 | 71 | minimum genetic mutation | 433 | 0.52 | Medium | 7,653 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/1491211/Python-or-BFS | class Solution:
def minMutation(self, start: str, end: str, bank) -> int:
if end not in bank:
return -1
q=[(start,0)]
visit=[start]
while q:
gene,d=q.pop(0)
if gene==end:
return d
for g in bank:
if g not in visit:
cnt=0
for i in range(len(g)):
if g[i]!=gene[i]:
cnt+=1
if cnt==1:
visit.append(g)
q.append((g,d+1))
return -1 | minimum-genetic-mutation | Python | BFS | heckt27 | 0 | 55 | minimum genetic mutation | 433 | 0.52 | Medium | 7,654 |
https://leetcode.com/problems/minimum-genetic-mutation/discuss/1383864/Python-Solution-using-Recursion | class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
res = []
def is_valid_mutate(a, b):
return sum(1 if a[i] != b[i] else 0 for i in range(len(a))) == 1
def helper(start, bank, count, res):
if not bank:
return
for i in range(len(bank)):
curr = bank[i]
# curr gene can be mutated from start
if not is_valid_mutate(curr, start):
continue
# we found the mutation from curr to end
if curr == end:
res.append(count + 1)
return
# we put leftover gene bank without curr
# and see our curr gene as start can be mutate to leftover gene bank
helper(curr, bank[:i] + bank[i+1:], count + 1, res)
helper(start, bank, 0, res)
return min(res) if res else -1 | minimum-genetic-mutation | Python Solution using Recursion | zhouquan0x16 | 0 | 98 | minimum genetic mutation | 433 | 0.52 | Medium | 7,655 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1015806/One-Line-python-Solution | class Solution:
def countSegments(self, s: str) -> int:
return len([i for i in s.split(" ") if i!=""]) | number-of-segments-in-a-string | One Line python Solution | moazmar | 3 | 464 | number of segments in a string | 434 | 0.377 | Easy | 7,656 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2603152/Python-91-Faster-Simple-Solution | class Solution:
def countSegments(self, s: str) -> int:
#create a list based on a space split
slist = list(s.split(" "))
#return the len of list minus empty item
return(len(slist)-slist.count("")) | number-of-segments-in-a-string | Python 91% Faster - Simple Solution | ovidaure | 1 | 86 | number of segments in a string | 434 | 0.377 | Easy | 7,657 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2794202/Simple-solution-for-the-problem | class Solution:
def countSegments(self, s: str) -> int:
if s=="":
return(0)
j = s.split(" ")
print(j)
c=0
for it in j:
if it!="":
c+=1
return(c) | number-of-segments-in-a-string | Simple solution for the problem | harshgupta204016 | 0 | 2 | number of segments in a string | 434 | 0.377 | Easy | 7,658 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2759882/Python-1-line-code | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | Python 1 line code | kumar_anand05 | 0 | 3 | number of segments in a string | 434 | 0.377 | Easy | 7,659 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2741121/Two-Lines-Python-Solution | class Solution:
def countSegments(self, s: str) -> int:
l= s.split()
return len(l) | number-of-segments-in-a-string | Two Lines Python Solution | dnvavinash | 0 | 4 | number of segments in a string | 434 | 0.377 | Easy | 7,660 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2739908/Python-3-Solution | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | Python 3 Solution | mati44 | 0 | 1 | number of segments in a string | 434 | 0.377 | Easy | 7,661 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2675456/Easy-to-Understand-or-Beginner's-Friendly-or-Python | class Solution(object):
def countSegments(self, s):
if not(s): return 0
ans, temp = 0, ''
for ch in s:
if ch == ' ' and temp != '':
ans += 1
temp = ''
if ch != ' ': temp += ch
return ans + 1 if temp != '' else ans | number-of-segments-in-a-string | Easy to Understand | Beginner's Friendly | Python | its_krish_here | 0 | 13 | number of segments in a string | 434 | 0.377 | Easy | 7,662 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2647575/One-line-solution | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | One line solution | shubhamshinde245 | 0 | 2 | number of segments in a string | 434 | 0.377 | Easy | 7,663 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2601057/python-or-without-the-usage-of-split | class Solution:
def countSegments(self, s: str) -> int:
s += " "
count = 0
for i in range(len(s)):
if s[i] == " " and i != 0:
if s[i - 1] != " ":
count += 1
return count | number-of-segments-in-a-string | python | without the usage of split | sproq | 0 | 10 | number of segments in a string | 434 | 0.377 | Easy | 7,664 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2502140/*-Python-oror-One-Liner-* | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | β’ Python || One Liner β’ | keertika27 | 0 | 16 | number of segments in a string | 434 | 0.377 | Easy | 7,665 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2371915/1-liner-no-brainer | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | 1 liner no brainer | sunakshi132 | 0 | 19 | number of segments in a string | 434 | 0.377 | Easy | 7,666 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/2145213/Using-.split()-method | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | Using .split() method | thanhinterpol | 0 | 41 | number of segments in a string | 434 | 0.377 | Easy | 7,667 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1914779/Python3-2-Solutions | class Solution:
def countSegments(self, s: str) -> int:
return len([i for i in s.split(' ') if i != '']) | number-of-segments-in-a-string | [Python3] 2 Solutions | abhijeetmallick29 | 0 | 52 | number of segments in a string | 434 | 0.377 | Easy | 7,668 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1914779/Python3-2-Solutions | class Solution:
def countSegments(self, s: str) -> int:
count = 0
for i in range(len(s)):
if (i == 0 or s[i-1] == ' ') and s[i] != ' ':
count += 1
return count; | number-of-segments-in-a-string | [Python3] 2 Solutions | abhijeetmallick29 | 0 | 52 | number of segments in a string | 434 | 0.377 | Easy | 7,669 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1760427/Python-oror-Runtime-faster-than-97.5-oror-Memory-less-than-99 | class Solution:
def countSegments(self, s: str) -> int:
if not s:
return 0
return len(s.split()) | number-of-segments-in-a-string | Python || Runtime faster than 97.5% || Memory less than 99% | Akhilesh_Pothuri | 0 | 31 | number of segments in a string | 434 | 0.377 | Easy | 7,670 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1739701/simple-python-solution | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | simple python solution | vijayvardhan6 | 0 | 33 | number of segments in a string | 434 | 0.377 | Easy | 7,671 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1512440/Python-O(n)-time-O(1)-space-complex-solution-without-strip() | class Solution:
def countSegments(self, s: str) -> int:
n = len(s)
cnt = 0
start = 0
end = n-1
if n == 0:
return 0
while start <= n-1 and s[start] == ' ':
start += 1
if start == n:
return 0
while end >= 0 and s[end] == ' ':
end -= 1
if end == -1:
return 0
if end + 1 <= start:
return 0
for i in range(start, end + 1):
if i >=1 and s[i] == ' ' and s[i-1] != ' ':
cnt +=1
return cnt+1 | number-of-segments-in-a-string | Python O(n) time, O(1) space complex solution without strip() | byuns9334 | 0 | 86 | number of segments in a string | 434 | 0.377 | Easy | 7,672 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1495185/python-3 | class Solution:
def countSegments(self, s: str) -> int:
count=0
if s=="":
return 0
lst=list(s.split(" "))
print(lst)
for ch in lst:
if ch != '':
count+=1
return count | number-of-segments-in-a-string | python 3 | minato_namikaze | 0 | 60 | number of segments in a string | 434 | 0.377 | Easy | 7,673 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1473062/Python-Stack | class Solution:
def countSegments(self, s: str) -> int:
result, stack = 0, []
for c in s:
if c == ' ':
if stack:
result += 1
stack.clear()
else:
stack += [c]
return result + (1 if stack else 0) | number-of-segments-in-a-string | [Python] Stack | dev-josh | 0 | 38 | number of segments in a string | 434 | 0.377 | Easy | 7,674 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1473062/Python-Stack | class Solution:
def countSegments(self, s: str) -> int:
result, seen = 0, False
for c in s:
if c == ' ':
result += int(seen)
seen = False
continue
seen = True
return result + int(seen) | number-of-segments-in-a-string | [Python] Stack | dev-josh | 0 | 38 | number of segments in a string | 434 | 0.377 | Easy | 7,675 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1267642/Easy-Python-Solution(93.08) | class Solution:
def countSegments(self, s: str) -> int:
h=0
c=0
# s=' '+s
if not s:
return 0
for i in range(len(s)):
if(s[i]!=' '):
h+=1
elif(h>0):
c+=1
h=0
if(h>0):
c+=1
return c | number-of-segments-in-a-string | Easy Python Solution(93.08%) | Sneh17029 | 0 | 170 | number of segments in a string | 434 | 0.377 | Easy | 7,676 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1262177/Python3-simple-%22one-liner%22-solution | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | Python3 simple "one-liner" solution | EklavyaJoshi | 0 | 41 | number of segments in a string | 434 | 0.377 | Easy | 7,677 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1159186/This-shows-why-Python-is-awesome | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | This shows why Python is awesome | fadista | 0 | 29 | number of segments in a string | 434 | 0.377 | Easy | 7,678 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/336553/Solution-in-Python-3-(beats-~100)-(-one-line-) | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split())
- Python 3
- Junaid Mansuri | number-of-segments-in-a-string | Solution in Python 3 (beats ~100%) ( one line ) | junaidmansuri | 0 | 335 | number of segments in a string | 434 | 0.377 | Easy | 7,679 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1425480/EASY-PYTHON-1-LINE-99 | class Solution:
def countSegments(self, s: str) -> int:
return len(s.split()) | number-of-segments-in-a-string | EASY PYTHON 1 LINE 99% | Umarabdullah101 | -1 | 76 | number of segments in a string | 434 | 0.377 | Easy | 7,680 |
https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1159362/Code-for-Every-Language | class Solution:
def countSegments(self, s: str) -> int:
count = 0
for i in range(len(s)):
if s[i] != " " and (i==0 or s[i-1]== " "):
count+=1
return count | number-of-segments-in-a-string | Code for Every Language | asifrasool573 | -1 | 100 | number of segments in a string | 434 | 0.377 | Easy | 7,681 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/1896849/Python-easy-to-read-and-understand-or-sorting | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: x[1])
n = len(intervals)
ans, curr = 1, intervals[0]
for i in range(n):
if intervals[i][0] >= curr[1]:
ans += 1
curr = intervals[i]
return n - ans | non-overlapping-intervals | Python easy to read and understand | sorting | sanial2001 | 2 | 196 | non overlapping intervals | 435 | 0.499 | Medium | 7,682 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/2519472/Clean-8-Lines-Python3-or-99-Time-and-Memory-or-Greedy | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key = lambda k: k[1])
removed, last_end = 0, float('-inf')
for start, end in intervals:
if start < last_end:
removed += 1
else:
last_end = end
return removed | non-overlapping-intervals | Clean 8 Lines Python3 | 99% Time & Memory | Greedy | ryangrayson | 1 | 71 | non overlapping intervals | 435 | 0.499 | Medium | 7,683 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/2386577/Python-Greedy-Beats-92-with-full-working-explanation | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: # Time: O(nlogn) and Space: O(1)
intervals.sort()
res = 0
prevEnd = intervals[0][1]
for start, end in intervals[1:]: # we will start from 1 as we already had taken 0 as a base value
if start >= prevEnd: # Non overlapping when new interval starts after or from the previous one
prevEnd = end # prev = [2, prevEnd=3] & new = [start=3, end=4], we have a new end now after checking the new non overlapping interval
else: # Overlapping when new interval starts in between or from the previous one
res += 1 # prev = [1, prevEnd=2] & new = [start=1, end=3] --> we will delete new=[1, 3] & set prev = [1, prevEnd=2]
prevEnd = min(end, prevEnd) # we will delete on the interval on the basis of whose interval ends last
return res | non-overlapping-intervals | Python [Greedy / Beats 92%] with full working explanation | DanishKhanbx | 1 | 106 | non overlapping intervals | 435 | 0.499 | Medium | 7,684 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/1832287/Python-Solution | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals = sorted(intervals)
ans = 0
endDate = intervals[0][1]
for currentInterval in range(1, len(intervals)):
if intervals[currentInterval][0] < endDate :
ans += 1
endDate = min(endDate, intervals[currentInterval][1])
else:
endDate = intervals[currentInterval][1]
return ans | non-overlapping-intervals | Python Solution | DietCoke777 | 1 | 64 | non overlapping intervals | 435 | 0.499 | Medium | 7,685 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/1570424/Python-Greedy-easy-understanding | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
# greedy
# always pick the earlist end time because it provide more capacity to the later intervals
intervals.sort(key = lambda x : x[1])
# use fit to record the order or fitting intervals and compare with the next one
# to check if the next one is fit
fit = []
for i in intervals:
if fit == [] or i[0]>= fit[-1][1]:
fit.append(i)
return len(intervals) - len(fit)
# time complexity: sorting (nlogn) + traversal (n) which is 0(nlogn)
# space : the lenth of fit which is O(n) | non-overlapping-intervals | Python Greedy, easy understanding | Msparks | 1 | 96 | non overlapping intervals | 435 | 0.499 | Medium | 7,686 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/1510947/Python3-Solution-with-using-sorting | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals = sorted(intervals, key=lambda interval: interval[1])
last_valid_interval_idx = 0
cnt = 0
for cur_idx in range(1, len(intervals)):
if intervals[cur_idx][0] < intervals[last_valid_interval_idx][1]:
cnt += 1
else:
last_valid_interval_idx = cur_idx
return cnt | non-overlapping-intervals | [Python3] Solution with using sorting | maosipov11 | 1 | 109 | non overlapping intervals | 435 | 0.499 | Medium | 7,687 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/1468599/Be-Greedy-Sometime-or-Python | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
n = len(intervals)
if n<=0:
return 0
intervals.sort()
ans = 0
end = intervals[0][1]
print(intervals)
for i in range(1, n):
if intervals[i][0] < end:
ans += 1
end = min(end, intervals[i][1])
else:
end = intervals[i][1]
return ans | non-overlapping-intervals | Be Greedy Sometime | Python | Sanjaychandak95 | 1 | 107 | non overlapping intervals | 435 | 0.499 | Medium | 7,688 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/2801061/Greedy-approach-with-Python3 | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
s_int=sorted(intervals, key=lambda s:s[0]*100000+s[1])
new_int=[]
for i in range(len(s_int)):
if len(new_int)>0 and (s_int[i][0]==s_int[i-1][0]):
pass
else:
while len(new_int)>0 and new_int[-1][1]>s_int[i][1]:
new_int.pop()
if len(new_int)==0 or (s_int[i][0]>=new_int[-1][1]):
new_int.append(s_int[i])
return len(intervals)-len(new_int) | non-overlapping-intervals | Greedy approach with Python3 | guankiro | 0 | 7 | non overlapping intervals | 435 | 0.499 | Medium | 7,689 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/2673676/Python-Easy-Solution | class Solution:
def eraseOverlapIntervals(self, arr: List[List[int]]) -> int:
arr.sort(key=lambda x:x[1])
print(arr)
count=1
prevS , prevE=arr[0]
for s ,e in arr:
if s<prevE:
continue
else:
prevS , prevE = s , e
count+=1
return len(arr)-count | non-overlapping-intervals | Python Easy Solution | pranjalmishra334 | 0 | 67 | non overlapping intervals | 435 | 0.499 | Medium | 7,690 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/2558963/Python-Easy-Solution | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key = lambda x : x[1])
res = 0
lastNonOverlap = 0
for i in range(1, len(intervals)):
if intervals[i][0] < intervals[lastNonOverlap][1]:
res += 1
else:
lastNonOverlap = i
return res | non-overlapping-intervals | Python Easy Solution | lokeshsenthilkumar | 0 | 127 | non overlapping intervals | 435 | 0.499 | Medium | 7,691 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/2438263/short-Python-solution-using-stack | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
st = []
intervals.sort(key= lambda x:x[0])
ans = 0
for inte in intervals:
if not st or inte[0] >= st[-1][1]:
st.append(inte)
continue
if inte[0] >= st[-1][0] and inte[1] <= st[-1][1]:
st.pop()
st.append(inte)
ans += 1
return ans | non-overlapping-intervals | short Python solution using stack | 96sayak | 0 | 25 | non overlapping intervals | 435 | 0.499 | Medium | 7,692 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/1921277/Python-Intervals-solution-explained | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
# we require the intervals to be
# in sorted order otherwise the intervals
# would all be scattered around
# for e.g. intervals = [1,2],[3,5],[2,3]
# the third interval should be merged with
# the first but since they are not sorted
# our result would be incorrect
intervals.sort()
res = 0
# we're just going to maintain
# a previousEnd of the last
# element of our virtual (non-overlapping)
# interval list, start with the first here
prevEnd = intervals[0][1]
# usual intervals pattern, start
# with the second interval
for start, end in intervals[1:]:
# if there's an overlap between
# the current interval and the
# one that we had previously
# the new prev or the new interval
# would be the one which ends first
# or said another way, we'll remove
# the interval which ends later
# and so prevEnd now will become
# the end of the interval which
# we'd like to keep in our list
# also, since we're "removing"
# virtually an interval, increment
# result variable
if start < prevEnd:
res += 1
prevEnd = min(end, prevEnd)
else:
# if there's no overlap, we'll
# just set this interval end
# to our prevEnd and move fwd.
prevEnd = end
return res | non-overlapping-intervals | [Python] Intervals solution explained | buccatini | 0 | 78 | non overlapping intervals | 435 | 0.499 | Medium | 7,693 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/1573386/Greedy-Approach-oror-Well-Explained-and-Coded-oror-Easy-to-understand | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key = lambda x:x[0])
st = []
for a,b in intervals:
if len(st)!=0:
if a<st[-1]:
st.append(min(st.pop(),b))
else:
st.append(b)
else:
st.append(b)
return len(intervals)-len(st) | non-overlapping-intervals | ππ Greedy Approach || Well-Explained & Coded || Easy to understand π | abhi9Rai | 0 | 195 | non overlapping intervals | 435 | 0.499 | Medium | 7,694 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/1570809/Python-O(nlogn)-time | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort()
res = 0
end = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0] < end:
end = min(end, intervals[i][1])
res += 1
else:
end = intervals[i][1]
return res | non-overlapping-intervals | Python O(nlogn) time | dereky4 | 0 | 287 | non overlapping intervals | 435 | 0.499 | Medium | 7,695 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/983107/Simple-Python-solution | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
curr_interval, count = None, 0
for i in sorted(intervals, key=lambda a: (a[1])):
if not curr_interval or curr_interval[1] <= i[0]:
curr_interval = i
count += 1
return len(intervals) - count | non-overlapping-intervals | Simple Python solution | cj1989 | 0 | 202 | non overlapping intervals | 435 | 0.499 | Medium | 7,696 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/793411/Python3-greedy | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
ans, prev = 0, -inf #end of previous interval
for x, y in sorted(intervals, key=lambda x: x[1]):
if x < prev: ans += 1 #current start is smaller than previous end => overlapping
else: prev = y
return ans | non-overlapping-intervals | [Python3] greedy | ye15 | 0 | 69 | non overlapping intervals | 435 | 0.499 | Medium | 7,697 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/793411/Python3-greedy | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
ans, prev = 0, -inf # previous ending
for x, y in sorted(intervals):
if prev <= x: prev = y
else:
prev = min(prev, y)
ans += 1
return ans | non-overlapping-intervals | [Python3] greedy | ye15 | 0 | 69 | non overlapping intervals | 435 | 0.499 | Medium | 7,698 |
https://leetcode.com/problems/non-overlapping-intervals/discuss/1443051/Simple-Python-O(n)-greedy-solution | class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
# removing minimum number of intervals is equivalent to
# keeping the maximum number of intervals, which can be
# solved greedily. We can sort by finish time and schedule by
# earliest non-conflicting finish time to leave for more space
# for subsequent intervals.
intervals.sort(key = lambda x: x[1])
n_keep, prev_end = 1, intervals[0][1]
for i in range(1, len(intervals)):
cur_start, cur_end = intervals[i]
if cur_start >= prev_end:
n_keep += 1
prev_end = cur_end
return len(intervals)-n_keep | non-overlapping-intervals | Simple Python O(n) greedy solution | Charlesl0129 | -3 | 277 | non overlapping intervals | 435 | 0.499 | Medium | 7,699 |
Subsets and Splits