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/single-number-ii/discuss/628337/Two-python-sol-sharing.-w-Comment
class Solution: def singleNumber(self, nums: List[int]) -> int: single_num = 0 # compute single number by bit masking for bit_shift in range(32): sum = 0 for number in nums: # collect the bit sum sum += ( number >> bit_shift ) &amp; 1 # Extract bit information of single number by modulo # Other number's bit sum is removed by mod 3 (i.e., all other numbers appear three times) single_num |= ( sum % 3 ) << bit_shift if ( single_num &amp; (1 << 31) ) == 0: return single_num else: # handle for negative number return -( (single_num^(0xFFFF_FFFF))+1 )
single-number-ii
Two python sol sharing. [w/ Comment]
brianchiang_tw
4
922
single number ii
137
0.579
Medium
1,800
https://leetcode.com/problems/single-number-ii/discuss/1259539/Easy-and-Intuitive-solution-without-Bit-manipulation
class Solution: def singleNumber(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] nums.sort() if len(nums) >= 2 and nums[0] != nums[1]: return nums[0] if len(nums) >= 2 and nums[-1] != nums[-2]: return nums[-1] for i in range(1, len(nums)-1): if nums[i-1] != nums[i] and nums[i] != nums[i+1]: return nums[i] # Time: O(N logN) + O(N) # Space: O(1)
single-number-ii
Easy and Intuitive solution without Bit manipulation
v21
2
205
single number ii
137
0.579
Medium
1,801
https://leetcode.com/problems/single-number-ii/discuss/2761958/Python3-Bit-Manipulation
class Solution: def singleNumber(self, nums: List[int]) -> int: b1, b2 = 0, 0 for i in nums: # like C[b] += i b2 |= (b1 &amp; i) b1 ^= i # like C[b] %= 3 shared = (b1 &amp; b2) b1 ^= shared b2 ^= shared return b1
single-number-ii
Python3 Bit Manipulation
godshiva
1
17
single number ii
137
0.579
Medium
1,802
https://leetcode.com/problems/single-number-ii/discuss/2747995/Python3ororSimple-Easy-understanding
class Solution: def singleNumber(self, nums: List[int]) -> int: di={} for i in nums: if i in di: di[i]+=1 else: di[i]=1 for i,j in enumerate(di): if di[j]==1: return j
single-number-ii
Python3||Simple Easy understanding
Sneh713
1
305
single number ii
137
0.579
Medium
1,803
https://leetcode.com/problems/single-number-ii/discuss/1092202/Pyrhon3-sort()-easy-for-any-times
class Solution: def singleNumber(self, nums: List[int]) -> int: n = len(nums) if n == 1: return nums[0] nums.sort() for i in range(2,n,3): #for twice range(1,n,2),for three times range(2,n,3),for m times range(m-1,n,m) if nums[i] != nums[i-2]: return nums[i-2] return nums[-1]
single-number-ii
Pyrhon3 sort() easy for any times
2017JAMESFU
1
98
single number ii
137
0.579
Medium
1,804
https://leetcode.com/problems/single-number-ii/discuss/2823375/Python3-easy-to-understand
class Solution: def singleNumber(self, nums: List[int]) -> int: for k, v in Counter(nums).items(): if v == 1: return k
single-number-ii
Python3 - easy to understand
mediocre-coder
0
6
single number ii
137
0.579
Medium
1,805
https://leetcode.com/problems/single-number-ii/discuss/2796476/reshenie-podoshlo-i-k-proshlomu-zadaniyu
class Solution: def singleNumber(self, nums: List[int]) -> int: for idx, i in enumerate(nums): if not (i in nums[:idx] or i in nums[idx + 1 :]): return i
single-number-ii
решение подошло и к прошлому заданию
s-cod
0
1
single number ii
137
0.579
Medium
1,806
https://leetcode.com/problems/single-number-ii/discuss/2780500/Python-or-4-lines-or-state-machine-or-O(n)-and-O(1)
class Solution: def singleNumber(self, xs: List[int]) -> int: a, b = 0, 0 for x in xs: a, b = (a&amp;b)^(a&amp;x)^(b&amp;x)^a, (a&amp;b)^(a&amp;x)^b^x return b
single-number-ii
Python | 4 lines | state machine | O(n) and O(1)
on_danse_encore_on_rit_encore
0
9
single number ii
137
0.579
Medium
1,807
https://leetcode.com/problems/single-number-ii/discuss/2778549/python-easy-solution
class Solution: def singleNumber(self, nums: List[int]) -> int: for i in nums: if nums.count(i) == 1: return i
single-number-ii
python easy solution
seifsoliman
0
7
single number ii
137
0.579
Medium
1,808
https://leetcode.com/problems/single-number-ii/discuss/2773593/python-3-Sol-faster-then-93
class Solution: def singleNumber(self, nums: List[int]) -> int: summ1=sum(set(nums)) summ2=sum(nums) ans=((summ1*3)-summ2)//2 return ans
single-number-ii
python 3 Sol faster then 93%
pranjalmishra334
0
8
single number ii
137
0.579
Medium
1,809
https://leetcode.com/problems/single-number-ii/discuss/2760166/easy-solution-from-python-beginner
class Solution: def singleNumber(self, nums: List[int]) -> int: ans = 0 for i in nums: if nums.count(i) == 1: ans = i return ans
single-number-ii
easy solution from python beginner
kanykeiat
0
5
single number ii
137
0.579
Medium
1,810
https://leetcode.com/problems/single-number-ii/discuss/2750318/python3ororOne-Liner-using-sum
class Solution: def singleNumber(self, nums): return (3*sum(set(nums))-sum(nums))//2
single-number-ii
python3||One Liner using sum
alamwasim29
0
6
single number ii
137
0.579
Medium
1,811
https://leetcode.com/problems/single-number-ii/discuss/2719996/O(N-*-N)-Easy-Understanding-Solution-Python-and-Golang
class Solution: # O(N * N) def singleNumber(self, nums: List[int]) -> int: cache = {} for num in nums: cache[num] = cache.get(num, 0) + 1 for key, value in cache.items(): if value == 1: return key
single-number-ii
O(N * N) Easy Understanding Solution [Python and Golang]
namashin
0
6
single number ii
137
0.579
Medium
1,812
https://leetcode.com/problems/single-number-ii/discuss/2715701/~100-ms-runtime-explanation
class Solution: def singleNumber(self, nums: List[int]) -> int: return (3 * sum(set(nums)) - sum(nums)) // 2 # 3 * sum(set(nums)) == sum(nums) + 2x # 3 * (sum(nums)) - sum(nums) == 2x # (3 * sum(nums) - sum(nums)) // 2 == x
single-number-ii
~100 ms runtime explanation
neversleepsainou
0
5
single number ii
137
0.579
Medium
1,813
https://leetcode.com/problems/single-number-ii/discuss/2601164/python3-using-dictionary
class Solution: def singleNumber(self, nums: List[int]) -> int: counts = Counter(nums) return sorted(counts.items(), key=lambda items:items[1])[0][0]
single-number-ii
[python3] using dictionary
hhlinwork
0
12
single number ii
137
0.579
Medium
1,814
https://leetcode.com/problems/single-number-ii/discuss/2592555/Python-solution-using-Counter-function
class Solution: def singleNumber(self, nums: List[int]) -> int: a = Counter(nums) for k,v in a.items(): if v==1: return k
single-number-ii
Python solution using Counter function
abdulrazak01
0
25
single number ii
137
0.579
Medium
1,815
https://leetcode.com/problems/single-number-ii/discuss/2474048/Python-Short-and-Easy-Solution-oror-Documented
class Solution: def singleNumber(self, nums: List[int]) -> int: return (3 * sum(set(nums)) - sum(nums)) // 2
single-number-ii
[Python] Short and Easy Solution || Documented
Buntynara
0
37
single number ii
137
0.579
Medium
1,816
https://leetcode.com/problems/single-number-ii/discuss/2153841/faster-than-70.54-of-Python3-oror-one-line-solution
class Solution: def singleNumber(self, nums: List[int]) -> int: return (sum(set(nums))*3 - sum(nums))//2
single-number-ii
faster than 70.54% of Python3 || one line solution
writemeom
0
99
single number ii
137
0.579
Medium
1,817
https://leetcode.com/problems/single-number-ii/discuss/2146350/Python-oneliner
class Solution: def singleNumber(self, nums: List[int]) -> int: return [x for x in nums if nums.count(x) == 1][0]
single-number-ii
Python oneliner
StikS32
0
73
single number ii
137
0.579
Medium
1,818
https://leetcode.com/problems/single-number-ii/discuss/2022419/Simple-python-solution-64-ms-(collections.Counter)
class Solution: def singleNumber(self, nums: List[int]) -> int: d = Counter(nums) return sorted(d, key=d.get)[0]
single-number-ii
Simple python solution 64 ms (collections.Counter)
andrewnerdimo
0
104
single number ii
137
0.579
Medium
1,819
https://leetcode.com/problems/single-number-ii/discuss/2010775/Simple-Python-Solution-using-sum()-and-set()
class Solution: def singleNumber(self, nums: List[int]) -> int: s_nums = sum(set(nums)) diff = (sum(nums) - s_nums) // 2 return s_nums - diff
single-number-ii
Simple Python Solution - using sum() and set()
iamamirhossein
0
94
single number ii
137
0.579
Medium
1,820
https://leetcode.com/problems/single-number-ii/discuss/1545593/Python-Using-Bit-Manipulation-Extra-Space-O(1)-and-Time-O(n)
class Solution: def singleNumber(self, nums: List[int]) -> int: #using bit manipulation with constant extra space elementAppearence, bitLength = 3, 32 #Define constants bit, bitCount = 1, [0 for i in range(bitLength)] for i in range(len(bitCount)): for n in nums: if bit&amp;n==bit: bitCount[i]+=1 bit<<=1 ifNegetive = sum(1 if i<-1 else 0 for i in nums)%elementAppearence == 1 # Also bitCount[-1]%elementAppearence==1 gives the value of ifNegetive #print(bitCount) #debug #Generate Output bit, output = 1, 0 if ifNegetive: #Negetive Number, so find one's complement for i in range(len(bitCount)): bitCount[i] = 1 if bitCount[i]%elementAppearence==0 else 0 for b in bitCount: if b%elementAppearence==1: output+=bit bit<<=1 return -(output+1) if ifNegetive else output
single-number-ii
Python Using Bit Manipulation Extra Space O(1) and Time O(n)
abrarjahin
0
217
single number ii
137
0.579
Medium
1,821
https://leetcode.com/problems/single-number-ii/discuss/498343/Python3-both-bitwise-and-hash-table
class Solution: def singleNumber(self, nums: List[int]) -> int: """ ~x that means bitwise NOT x &amp; y that means bitwise AND x ⊕ y that means bitwise XOR The idea is to change seen_once only if seen_twice is unchanged change seen_twice only if seen_once is unchanged This way bitmask seen_once will keep only the number which appears once and not the numbers which appear three times. """ seen_once=seen_twice=0 for num in nums: seen_once=~seen_twice&amp;(seen_once^num) seen_twice=~seen_once&amp;(seen_twice^num) return seen_once def singleNumber1(self, nums: List[int]) -> int: ht={} for num in nums: ht[num]=ht.get(num,0)+1 for k in ht: if ht[k]!=3: return k
single-number-ii
Python3 both bitwise and hash table
jb07
0
291
single number ii
137
0.579
Medium
1,822
https://leetcode.com/problems/single-number-ii/discuss/1723580/Simple-solution-using-python3
class Solution: def singleNumber(self, nums: List[int]) -> int: dic = dict() for item in nums: if dic.get(item): dic[item] += 1 else: dic[item] = 1 for item in dic.items(): if item[1] == 1: return item[0]
single-number-ii
Simple solution using python3
shakilbabu
-1
46
single number ii
137
0.579
Medium
1,823
https://leetcode.com/problems/single-number-ii/discuss/1666702/Python-Soln
class Solution: def singleNumber(self, nums: List[int]) -> int: nums.sort() if len(nums)==1: return nums[0] i=1#If left element is equal to the middle one then fine else return jumpstep=3#Leave the right el of curr and first el of the next while i<len(nums): if nums[i]==nums[i-1]: i+=jumpstep if i>=len(nums):#Means we are out of array and last element is the single return nums[-1] else: return nums[i-1]
single-number-ii
Python Soln
heckt27
-1
81
single number ii
137
0.579
Medium
1,824
https://leetcode.com/problems/single-number-ii/discuss/993707/python3-soluion
class Solution: def singleNumber(self, nums: List[int]) -> int: nums.sort() prev = nums[0] count = 1 for i in range(1,len(nums)): if nums[i] == prev: count += 1 else: if count == 3: count = 1 prev = nums[i] else: return prev return prev
single-number-ii
python3 soluion
swap2001
-1
166
single number ii
137
0.579
Medium
1,825
https://leetcode.com/problems/single-number-ii/discuss/1602843/Python-one-line-solution
class Solution: def singleNumber(self, nums: List[int]) -> int: return (sum(set(nums))*3-sum(nums))//2
single-number-ii
Python one line solution
earlliaomango
-2
146
single number ii
137
0.579
Medium
1,826
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1841010/Python3-JUST-TWO-STEPS-()-Explained
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': hm, zero = dict(), Node(0) cur, copy = head, zero while cur: copy.next = Node(cur.val) hm[cur] = copy.next cur, copy = cur.next, copy.next cur, copy = head, zero.next while cur: copy.random = hm[cur.random] if cur.random else None cur, copy = cur.next, copy.next return zero.next
copy-list-with-random-pointer
✔️ [Python3] JUST TWO STEPS ヾ(´▽`;)ゝ, Explained
artod
43
1,700
copy list with random pointer
138
0.506
Medium
1,827
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/614624/Python-O(n)-by-mirror-node-85%2B-w-Visualization
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': # -------------------------------------------------------- # Create mirror node for each node in linked list cur = head while cur: # backup original next node of input linkied list original_next_hop = cur.next # create mirror node with original order cur.next = Node( x = cur.val, next = original_next_hop, random = None) # move to next position cur = original_next_hop # -------------------------------------------------------- # Let mirror node get the random pointer cur = head while cur: if cur.random: # assign random pointer to mirror node cur.next.random = cur.random.next try: # move to next position cur = cur.next.next except AttributeError: break # -------------------------------------------------------- # Separate copy linked list from original linked list try: # locate the head node of copy linked list head_of_copy_list = head.next cur = head_of_copy_list except AttributeError: # original input is an empty linked list return None while cur: try: # link mirror node to copy linked list cur.next = cur.next.next except AttributeError: break # move to next position cur = cur.next return head_of_copy_list
copy-list-with-random-pointer
Python O(n) by mirror node 85%+ [w/ Visualization]
brianchiang_tw
31
1,300
copy list with random pointer
138
0.506
Medium
1,828
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/864305/Python-3-or-Two-Methods-(Recursive-Iterative)-or-Explanation
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': d = {None:None} dummy = Node(-1) cur, new_cur = head, dummy while cur: new_cur.next = d[cur] = Node(cur.val) cur, new_cur = cur.next, new_cur.next cur, new_cur = head, dummy.next while cur: new_cur.random = d[cur.random] cur, new_cur = cur.next, new_cur.next return dummy.next
copy-list-with-random-pointer
Python 3 | Two Methods (Recursive, Iterative) | Explanation
idontknoooo
14
914
copy list with random pointer
138
0.506
Medium
1,829
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/864305/Python-3-or-Two-Methods-(Recursive-Iterative)-or-Explanation
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': d = dict() def deep_copy(node): if not node: return if node in d: return d[node] d[node] = n = Node(node.val) n.next = deep_copy(node.next) n.random = deep_copy(node.random) return n return deep_copy(head)
copy-list-with-random-pointer
Python 3 | Two Methods (Recursive, Iterative) | Explanation
idontknoooo
14
914
copy list with random pointer
138
0.506
Medium
1,830
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1059384/Python-Optimal-2-pass-O(1)-space-w-diagram-%2B-explanation
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': copy = preroot = Node(-1, head, None) while head: orig_next = head.next head.next = copy.next = Node(head.val, None, head.random) head, copy = orig_next, copy.next copy = preroot.next while copy: copy.random = copy.random.next if copy.random else None copy = copy.next return preroot.next
copy-list-with-random-pointer
[Python] Optimal 2 pass, O(1) space w/ diagram + explanation
geordgez
13
814
copy list with random pointer
138
0.506
Medium
1,831
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1059384/Python-Optimal-2-pass-O(1)-space-w-diagram-%2B-explanation
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': copy = preroot = Node(-1, head, None) # first pass: create a copy of linked list while head: orig_next = head.next # keep RANDOM pointing to original random node new_node = Node(head.val, None, head.random) # set NEXT to point to copied node head.next = copy.next = new_node # head pointer should move forward in the original linked list head = orig_next copy = copy.next # second pass: resolve RANDOM pointers in copies copy = preroot.next while copy: # set RANDOM pointers to nodes in the copied linked list if copy.random: copy.random = copy.random.next copy = copy.next return preroot.next
copy-list-with-random-pointer
[Python] Optimal 2 pass, O(1) space w/ diagram + explanation
geordgez
13
814
copy list with random pointer
138
0.506
Medium
1,832
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1177657/Python-list-interweaving-with-explanation-O(n)-time-and-O(1)-space-complexity
class Solution(object): def copyRandomList(self, head): """ :type head: Node :rtype: Node """ if head is None: return None current = head # copy nodes inside the original list -------------------------------------------------------------------------- while current is not None: # create new copied node new_node = Node(x=current.val, next=current.next) # change current.next pointer to the new_node current.next = new_node # move current to the next after the copied node current = current.next.next # add random pointers -------------------------------------------------------------------------------------- # we have to replicate the random pointers for the copied nodes # also we have to break pointers of the copied nodes to the original nodes current = head while current is not None: # go to the next copied node - copy is always the node after the current copy = current.next # random pointer will point to the random node after the original random if current.random is not None: copy.random = current.random.next else: copy.random = None # go to he next original node current = current.next.next # break connections of the copied nodes to the original nodes -------------------------------------------------- # this could probably be done inside previous loop, but it complicates the code # second node is the head node of the new copied list inside the original list copied_head = head.next current = head.next # another pointer to return the list to its original state current_old = head while current is not None: # Return original list to its original state # pointers for the original list if current_old.next is not None: current_old.next = current_old.next.next current_old = current_old.next else: current_old.next = None current_old = None # Separate new list from the original list # pointers for the new list if current.next is not None: current.next = current.next.next current = current.next else: current.next = None current = None return copied_head
copy-list-with-random-pointer
Python list interweaving - with explanation O(n) time and O(1) space complexity
jiriVFX
7
273
copy list with random pointer
138
0.506
Medium
1,833
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1059515/Python.-faster-than-96.65.-Cool-and-easy-understanding-solution.
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': helper = {} def buildList(head: Node) -> Node: nonlocal helper if not head: return None if helper.get(head): return helper[head] helper[head] = Node( head.val ) helper[head].random = buildList(head.random) helper[head].next = buildList(head.next) return helper[head] return buildList(head)
copy-list-with-random-pointer
Python. faster than 96.65%. Cool & easy-understanding solution.
m-d-f
5
232
copy list with random pointer
138
0.506
Medium
1,834
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1842854/Python-Very-Easy-Solutions-or-Explained-or-O(1)-space
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': dic, itr = {}, head # dic: to store each original node pointing to its copy node, itr: iterator to travese the original list copy_head = prev = Node(-1) # copy_head: head of copy List (not exactly head, but head will be at next to it), prev: this will point to previous node of Copy list, used for linking the next while itr: # traverse the Original list and make the copy, we will leave the random to None as of now prev.next = prev = dic[itr] = Node(x = itr.val) # make a New node with original value, link the prev.next to new node, then update the prev pointer to this new Node itr = itr.next # update the itr to next, so we can move to the next node of original list copy_itr, itr = copy_head.next, head # copy_itr: iterator to traverse the copy list, itr: to traverse the original list while itr: # since both are of same length, we can take while itr or while copy_itr as well if itr.random: copy_itr.random = dic[itr.random] # if original has random pointer(ie not None) then update the random of copy node. Every original node is pointing to copy node in our dictionary, we will get the copy Node. itr, copy_itr = itr.next, copy_itr.next # update both iterator to its next in order to move further. return copy_head.next
copy-list-with-random-pointer
✅ Python Very Easy Solutions | Explained | O(1) space
dhananjay79
2
97
copy list with random pointer
138
0.506
Medium
1,835
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1842854/Python-Very-Easy-Solutions-or-Explained-or-O(1)-space
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': itr = head # itr: iterator to iterate the original while itr: # iterate the original list itr.next = Node(x = itr.val, next = itr.next) # create the copy node (with original node's value and original node's next so as chain would not break) and add this to original.next (ie. adding a copy in between the two original nodes) itr = itr.next.next # since we have added a copy in between, so have to skip that to get next original node copy_head = prev = Node(-1) # copy_head: head of copy List (not exactly head, but head will be at next to it), prev: this will point to previous node of Copy list, used for linking the next itr = head # itr: we will iterate again from head while itr: prev.next = prev = itr.next # each orginal node's next will have the copy Node, point prev to it , and update the prev to itr.next as well if itr.random: prev.random = itr.random.next # if any original node has random, we can go to the random node and grab its next bcoz we know any original node's next is their copy node. itr = itr.next.next # again we have skip the copy to get the next original node return copy_head.next
copy-list-with-random-pointer
✅ Python Very Easy Solutions | Explained | O(1) space
dhananjay79
2
97
copy list with random pointer
138
0.506
Medium
1,836
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1889878/Python-Easy-Solution-with-O(n)-and-Proper-Comments
class Solution: # __main__ def copyRandomList(self, head): if not head: return None dataset = {None:None} # None:None because of end None pointer for list cur = head # Creating and Store new node; while(cur): node = Node(cur.val) dataset[cur] = node cur = cur.next cur = head while(cur): node = dataset[cur] node.next = dataset[cur.next] node.random = dataset[cur.random] cur = cur.next return dataset[head]
copy-list-with-random-pointer
Python Easy Solution with O(n) and Proper Comments
neeraj-singh-jr
1
130
copy list with random pointer
138
0.506
Medium
1,837
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1842040/Python-Simple-Python-Solution-Using-Hashmap-and-Iterative-Approach
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': copy_store = {None: None} current_node = head while current_node != None: copy_node = Node(current_node.val) copy_store[current_node] = copy_node current_node = current_node.next current_node = head while current_node != None: copy_node = copy_store[current_node] copy_node.next = copy_store[current_node.next] copy_node.random = copy_store[current_node.random] current_node = current_node.next return copy_store[head]
copy-list-with-random-pointer
[ Python ] ✔✔ Simple Python Solution Using Hashmap and Iterative Approach 🔥✌
ASHOK_KUMAR_MEGHVANSHI
1
38
copy list with random pointer
138
0.506
Medium
1,838
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1841118/PythonorEasyorDict
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': nodeMap = {} curr = head prev = None while curr: temp = nodeMap.get(curr, Node(curr.val) ) nodeMap[curr] = temp if curr.random: random = nodeMap.get(curr.random, Node(curr.random.val)) nodeMap[curr.random] = random temp.random = random if prev: prev.next = temp prev = temp curr = curr.next return nodeMap.get(head)
copy-list-with-random-pointer
Python|Easy|Dict
mshanker
1
33
copy list with random pointer
138
0.506
Medium
1,839
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/742039/easy-to-understand-python-solution-O(N)
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if not head: return None p1 = head dic = {} while p1 != None: newNode = Node(p1.val, None, None) dic[p1] = newNode p1 = p1.next p2 = head while p2 != None: new_p2 = dic[p2] if p2.next != None: new_p2.next = dic[p2.next] if p2.random != None: new_p2.random = dic[p2.random] p2 = p2.next return dic[head]
copy-list-with-random-pointer
easy to understand python solution O(N)
mrpositron
1
203
copy list with random pointer
138
0.506
Medium
1,840
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/2798051/python-solution
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': oldlists = [] newlists = [] if not head: return None while head: newNode = Node(head.val) oldlists.append(head) newlists.append(newNode) head = head.next for i in range(len(oldlists)): if i + 1 == len(oldlists): newlists[i].next = None else: newlists[i].next = newlists[i+1] r = oldlists[i].random if r == None: newlists[i].random = None else: p = oldlists.index(r) newlists[i].random = newlists[p] return newlists[0]
copy-list-with-random-pointer
python solution
maomao1010
0
6
copy list with random pointer
138
0.506
Medium
1,841
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/2795137/Python-and-JavaScript-Detailed-Explanation-90-Faster-Solution
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': #first step: creating the deep copy of every node, and place it right after the original node iter = head front = head while iter: front = iter.next copyNode = Node(iter.val) iter.next = copyNode copyNode.next = front iter = front print(copyNode.val) #second step: establishing the random pointer connection iter = head while iter: if iter.random: iter.next.random = iter.random.next iter = iter.next.next #third step: establishing the next pointer separately for original linked list and deeply copied linked list. pseudoNode = Node(0) copy = pseudoNode iter = head while iter: front = iter.next.next copy.next = iter.next iter.next = front copy = copy.next iter = iter.next return pseudoNode.next
copy-list-with-random-pointer
[ Python & JavaScript ] Detailed Explanation - 90% Faster Solution
mdfaisalabdullah
0
2
copy list with random pointer
138
0.506
Medium
1,842
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/2636305/Python3-Easy-to-Read-two-pass-solution-with-comments
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return None newHead = Node(head.val) newNode = newHead node = head.next oldToNew = { head: newHead } # first pass, have a copy of the original list # and build up the map while node != None: # create a new copy node n = Node(node.val) newNode.next = n # register in the map oldToNew[node] = n # next node = node.next newNode = newNode.next # second pass, link new list random field based on the map newNode = newHead node = head while newNode != None: if node.random: randomPointsTo = oldToNew[node.random] newNode.random = randomPointsTo newNode = newNode.next node = node.next return newHead
copy-list-with-random-pointer
Python3 Easy to Read two pass solution with comments
kodrevol
0
16
copy list with random pointer
138
0.506
Medium
1,843
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/2497943/Python-runtime-54.70-memory-12..21
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': # old_node -> copied_node # only iterate through next, establish the nodes first if not head: return None d = {head:Node(head.val)} prev = d[head] cur = head.next while cur: # start iteration from the second node d[cur] = Node(cur.val) prev.next = d[cur] prev = d[cur] cur = cur.next # then duplicate random pointers for old in d.keys(): if old.random: d[old].random = d[old.random] return d[head]
copy-list-with-random-pointer
Python, runtime 54.70%, memory 12..21%
tsai00150
0
21
copy list with random pointer
138
0.506
Medium
1,844
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/2497943/Python-runtime-54.70-memory-12..21
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': def recur(node, visited): if not node: return None if node in visited: return visited[node] visited[node] = Node(node.val) visited[node].next = recur(node.next, visited) visited[node].random = recur(node.random, visited) return visited[node] return recur(head, {})
copy-list-with-random-pointer
Python, runtime 54.70%, memory 12..21%
tsai00150
0
21
copy list with random pointer
138
0.506
Medium
1,845
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/2271760/Python3-Simple-solution-2-pass-w-comments
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': hash_mp = {} temp = head # 1. In pass one, create a map of old -> new node while temp: hash_mp[temp] = Node(temp.val, None, None) temp = temp.next temp2 = head # head of new linked list head2 = hash_mp.get(temp2) # 2. In pass two, use map value and connect the nodes in map while temp2: curr = hash_mp.get(temp2) curr.next = hash_mp.get(temp2.next) curr.random = hash_mp.get(temp2.random) temp2 = temp2.next return head2
copy-list-with-random-pointer
[Python3] Simple solution - 2 pass w comments
Gp05
0
26
copy list with random pointer
138
0.506
Medium
1,846
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/2058505/Python
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return head nodes = {} self.deepcopy(head, nodes) return nodes[id(head)] def deepcopy(self, cur, nodes): if cur: node = nodes.setdefault(id(cur), Node(cur.val)) if cur.next: node.next = nodes.setdefault(id(cur.next), Node(cur.next.val)) if cur.random: node.random = nodes.setdefault(id(cur.random), Node(cur.random.val)) self.deepcopy(cur.next, nodes)
copy-list-with-random-pointer
Python
Takahiro_Yokoyama
0
34
copy list with random pointer
138
0.506
Medium
1,847
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/2000815/Python3-Built-In-Solution
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': return deepcopy(head)
copy-list-with-random-pointer
✅[Python3] Built-In Solution
vscala
0
42
copy list with random pointer
138
0.506
Medium
1,848
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1990202/Python-Hash-Map
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': old_new = dict() cur = head while cur: old_new[cur] = Node(cur.val) cur = cur.next old_new[None] = None cur = head while cur: old_new[cur].next = old_new[cur.next] old_new[cur].random = old_new[cur.random] cur = cur.next return old_new[head]
copy-list-with-random-pointer
Python Hash Map
oim8
0
32
copy list with random pointer
138
0.506
Medium
1,849
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1989121/Python-oror-Straight-Forward
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return head def find(rand): for i in range(len(nodes)): if nodes[i][0] == rand: return i return inf root, nodes = head, [] while head: nodes.append((head,head.random)) head = head.next new_nodes, rand_index, prev = [], [], None for node, rand in nodes: copy = Node(node.val) new_nodes.append(copy) if prev: prev.next = copy prev = copy rand_index.append( find(rand) ) for i in range(len(new_nodes)): if rand_index[i] != inf: new_nodes[i].random = new_nodes[rand_index[i]] return new_nodes[0]
copy-list-with-random-pointer
Python || Straight Forward
morpheusdurden
0
35
copy list with random pointer
138
0.506
Medium
1,850
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1889138/Python-simple-O(n)-time-O(n)-space-solution
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return None cnt = 0 # cnt >= 1 h = head nodes = [] randoms = [] # Null, 0, 4, 2, 0 node2idx = {} while h: nodes.append(Node(h.val)) node2idx[h] = cnt h = h.next cnt += 1 h = head while h: try: randoms.append(node2idx[h.random]) except: randoms.append(-1) h = h.next for i in range(1, cnt): nodes[i-1].next = nodes[i] for i in range(cnt): if randoms[i] >= 0: nodes[i].random = nodes[randoms[i]] return nodes[0]
copy-list-with-random-pointer
Python simple O(n) time, O(n) space solution
byuns9334
0
57
copy list with random pointer
138
0.506
Medium
1,851
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1844008/O(n)-Time-and-O(1)-Space-Solution-in-Python
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': # Iteration 1: Creating New Nodes as the immidiate Next nodes of all the Original Nodes pointer = head while pointer: nextNode = pointer.next pointer.next = Node(pointer.val) pointer.next.next = nextNode pointer = nextNode # Iteration 2: Assigning Randoms pointer = head while pointer: if pointer.random: pointer.next.random = pointer.random.next pointer = pointer.next.next # Iteration 3: Extracting Copy Linkedlist from the Main Linkedlist copyHead = Node(0) copyPointer = copyHead pointer = head while pointer: copyPointer.next = pointer.next pointer.next = pointer.next.next copyPointer = copyPointer.next pointer = pointer.next return copyHead.next
copy-list-with-random-pointer
O(n) Time & O(1) Space Solution in Python
jayshukla0034
0
9
copy list with random pointer
138
0.506
Medium
1,852
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1843592/Python3-Solution-with-using-hashmap
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': cur = head dummy = Node(0) prev = dummy origin2clone = {} while cur: node = Node(cur.val) prev.next = node origin2clone[cur] = node prev = prev.next cur = cur.next cur = head cur2 = dummy.next while cur: random = cur.random clone_random = None if random: clone_random = origin2clone[random] cur2.random = clone_random cur = cur.next cur2 = cur2.next return dummy.next
copy-list-with-random-pointer
[Python3] Solution with using hashmap
maosipov11
0
13
copy list with random pointer
138
0.506
Medium
1,853
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1843186/Simple-Python3-Solution
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': node = head tmp_head = tmp = Node(0) memory = {None:None} # clone content, keep a 'translation' table while node: tmp.next = Node(node.val) tmp = tmp.next memory[node] = tmp node = node.next # second pass update the random pointers node = head tmp = tmp_head.next while node: tmp.random = memory[node.random] tmp = tmp.next node = node.next return tmp_head.next
copy-list-with-random-pointer
Simple Python3 Solution
user6774u
0
14
copy list with random pointer
138
0.506
Medium
1,854
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1842913/PYTHON-TWO-RECURSIVE-runs-with-explanation-(36ms)
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': #Edgecase if head is None: return None; #A sentinel for the copy copySentinel = Node( -1 ); #Dictionary mapping ORIGINAL nodes to its index nodeToIndex = {}; #Dictionary mapping indices to COPY nodes indexToNode = {}; #First run, pass in the head and the copy sentinel self.firstRun( head, copySentinel, nodeToIndex,indexToNode, 0); #Second run, pass in both heads self.secondRun( head, copySentinel.next, nodeToIndex, indexToNode,0 ) #Return the copied head return copySentinel.next; #In the first run, we do three things simultaneuously #1. We construct new nodes for the copy ignoring the random values #2. We fill nodeToIndex using the current ORIGINAL node to the index we are at #3. We fill indexToNode as we construct the COPY # Which maps the current index to the COPY node itself def firstRun (self, orig, copy , nodeToIndex , indexToNode ,index ): #Capture the ORIGINAL and map to index nodeToIndex[ id( orig ) ] = index; #Base case; we are at the tail if orig is None: #Be sure to capture the index of the tail and map it to None indexToNode[ index ] = None; return; #Copy the ORIGINAL value and make a new COPY node value = orig.val; copy.next = Node( value ); #Map the current index to the COPY node indexToNode[ index ] = copy.next; #Continue to the next node self.firstRun( orig.next , copy.next , nodeToIndex, indexToNode , index + 1); #In the second run, we update the random pointers def secondRun (self, orig , copy, nodeToIndex ,indexToNode, index): #Base case, we simply return if orig is None: return; #Capture the random node from the ORIGINAL randomNode = id( orig.random ); #Convert the random node to the index randomIndex = nodeToIndex[ randomNode ]; #Use that index to find the COPY node copyRandom = indexToNode[ randomIndex ]; #Assign the random pointer to the COPY node copy.random = copyRandom; #Continue to the next node self.secondRun( orig.next, copy.next, nodeToIndex, indexToNode, index + 1 ); #Note we needed to do this in two runs #Because we needed to find out when a random pointer pointed to a node #What index that node was at #Node that we looked at the id( node ) to capture the memory address #As the key and not the value
copy-list-with-random-pointer
PYTHON TWO RECURSIVE runs with explanation (36ms)
greg_savage
0
16
copy list with random pointer
138
0.506
Medium
1,855
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1842181/Python3-one-pass-with-dict
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': create = {id(head): Node(head.val) if head else None} ret = mod = create[id(head)] while head: mod.val = head.val mod.next = create.setdefault(id(head.next), Node(head.next.val) if head.next else None) mod.random = create.setdefault(id(head.random), Node(head.random.val) if head.random else None) head = head.next mod = mod.next return ret
copy-list-with-random-pointer
Python3 one pass with dict
dibery
0
9
copy list with random pointer
138
0.506
Medium
1,856
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1842156/Self-Understandable-Python-%3A
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return temp=Node(0) l=temp cemp=head d={} while cemp: l.next=Node(cemp.val) l=l.next d[cemp]=l cemp=cemp.next cemp=head l=temp while cemp: if cemp.random: l.next.random=d[cemp.random] cemp=cemp.next l=l.next return temp.next
copy-list-with-random-pointer
Self Understandable Python :
goxy_coder
0
17
copy list with random pointer
138
0.506
Medium
1,857
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1841928/Python-Dumbest-Solution-using-deepcopy()-function
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': ll = deepcopy(head) return ll
copy-list-with-random-pointer
Python Dumbest Solution [ using deepcopy() function ]
sayantanis23
0
17
copy list with random pointer
138
0.506
Medium
1,858
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1841753/Python3-Single-pass-solution-using-while-loop-and-a-Hashmap(python-dictionary)
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return head new_head = Node(head.val) cur1 = head cur2 = new_head node_map = {head : new_head} while cur1: if cur1.next and cur1.next in node_map: cur2.next = node_map[cur1.next] else: new_node = Node(cur1.next.val) if cur1.next else None cur2.next = new_node node_map[cur1.next] = new_node if cur1.random and cur1.random in node_map: cur2.random = node_map[cur1.random] else: new_node = Node(cur1.random.val) if cur1.random else None cur2.random = new_node node_map[cur1.random] = new_node cur1 = cur1.next cur2 = cur2.next return new_head
copy-list-with-random-pointer
[Python3] Single pass solution using while loop and a Hashmap(python dictionary)
nandhakiran366
0
8
copy list with random pointer
138
0.506
Medium
1,859
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1841753/Python3-Single-pass-solution-using-while-loop-and-a-Hashmap(python-dictionary)
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return head new_head = Node(head.val) cur1 = head cur2 = new_head node_map = {head : new_head} while cur1: cur2.next = node_map[cur1.next] if cur1.next and cur1.next in node_map else (Node(cur1.next.val) if cur1.next else None) node_map[cur1.next] = cur2.next cur2.random = node_map[cur1.random] if cur1.random and cur1.random in node_map else (Node(cur1.random.val) if cur1.random else None) node_map[cur1.random] = cur2.random cur1 = cur1.next cur2 = cur2.next return new_head
copy-list-with-random-pointer
[Python3] Single pass solution using while loop and a Hashmap(python dictionary)
nandhakiran366
0
8
copy list with random pointer
138
0.506
Medium
1,860
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1816834/Simple-solution-with-explaination-using-dictionary
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': dic={} temp=head dummy=Node(-1) ans=dummy while temp: ans.next=Node(temp.val) dic[temp]=ans.next ans=ans.next temp=temp.next temp=head ans=dummy.next while temp and ans: if temp.random in dic: ans.random=dic[temp.random] temp=temp.next ans=ans.next return dummy.next
copy-list-with-random-pointer
Simple solution with explaination using dictionary
amit_upadhyay
0
20
copy list with random pointer
138
0.506
Medium
1,861
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1737540/Python-storing-nodes-in-a-dict
class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': def copyList(node): if not node: return node newNode = Node(node.val) newNodes[node] = newNode newNode.next = copyList(node.next) newNode.random = newNodes[node.random] return newNode newNodes = {None: None} return copyList(head)
copy-list-with-random-pointer
Python, storing nodes in a dict
blue_sky5
0
55
copy list with random pointer
138
0.506
Medium
1,862
https://leetcode.com/problems/word-break/discuss/748479/Python3-Solution-with-a-Detailed-Explanation-Word-Break
class Solution: def wordBreak(self, s, wordDict): dp = [False]*(len(s)+1) dp[0] = True for i in range(1, len(s)+1): for j in range(i): if dp[j] and s[j:i] in wordDict: dp[i] = True break return dp[-1]
word-break
Python3 Solution with a Detailed Explanation - Word Break
peyman_np
51
4,600
word break
139
0.455
Medium
1,863
https://leetcode.com/problems/word-break/discuss/870388/Python-Simple-Solution-Explained-(video-%2B-code)-(Fastest)
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [True] + [False] * len(s) for indx in range(1, len(s) + 1): for word in wordDict: if dp[indx - len(word)] and s[:indx].endswith(word): dp[indx] = True return dp[-1]
word-break
Python Simple Solution Explained (video + code) (Fastest)
spec_he123
18
1,500
word break
139
0.455
Medium
1,864
https://leetcode.com/problems/word-break/discuss/1480275/Well-Explained-oror-Clean-and-Concise-oror-98-faster
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: n=len(s) dp = [False for _ in range(n+1)] dp[0]=True for i in range(n): if dp[i]: for w in wordDict: if s[i:i+len(w)]==w: dp[i+len(w)]=True return dp[-1]
word-break
📌📌 [Well-Explained] || Clean & Concise || 98% faster 🐍
abhi9Rai
5
325
word break
139
0.455
Medium
1,865
https://leetcode.com/problems/word-break/discuss/2159064/Python-DP-top-down-approach
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: wordDict = set(wordDict) dp = {} def getResult(s,index): if not s: return True if index in dp: return dp[index] for i in range(len(s)+1): k = s[:i] if k in wordDict: if getResult(s[i:],index+i): dp[index] = True return dp[index] dp[index] = False return dp[index] return getResult(s,0)
word-break
📌 Python DP, top down approach
Dark_wolf_jss
4
64
word break
139
0.455
Medium
1,866
https://leetcode.com/problems/word-break/discuss/1483038/Python3-recursive-with-memoization-or-faster-than-99
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: memo = {} def can_construct(target, strings_bank, memo): if target in memo: return memo[target] if target == "": return True for element in strings_bank: # for every element in our dict we check if we can start constructing the string "s" if element == target[0:len(element)]: # the remaining of the string "s" (which is the suffix) is the new target suffix = target[len(element):] if can_construct(suffix, strings_bank, memo): memo[target] = True return True memo[target] = False return False return can_construct(s, wordDict, memo)
word-break
Python3 recursive with memoization | faster than 99%
FlorinnC1
4
286
word break
139
0.455
Medium
1,867
https://leetcode.com/problems/word-break/discuss/980088/Clean-Trie-%2B-DP-Optimal-Solution-O(N*K)-O(N%2BM)
class Trie: def __init__(self): self.next = defaultdict(Trie) self.isEnd = False def add(self, word): cur = self for c in word: if c not in cur.next: cur.next[c] = Trie() cur = cur.next[c] cur.isEnd = True class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: words = Trie() for word in wordDict: words.add(word) @cache def recurse(index, trie): if index == len(s): return trie.isEnd if trie.isEnd: if recurse(index, words): return True if s[index] in trie.next: return recurse(index + 1, trie.next[s[index]]) return False return recurse(0, words)
word-break
Clean Trie + DP Optimal Solution O(N*K), O(N+M)
KJKim
3
275
word break
139
0.455
Medium
1,868
https://leetcode.com/problems/word-break/discuss/980088/Clean-Trie-%2B-DP-Optimal-Solution-O(N*K)-O(N%2BM)
class Trie: def __init__(self): self.next = defaultdict(str) def add(self, word): cur = self.next for c in word: if c not in cur: cur[c] = defaultdict(str) cur = cur[c] cur['$'] = True class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: words = Trie() dp = [False] * len(s) # O(N) space for word in wordDict: # O(M) space words.add(word) for i in reversed(range(len(s))): # O(N) time trie = words.next j = i while trie and j < len(s) and not (dp[j] and '$' in trie): # O(K) time trie = trie[s[j]] j += 1 dp[i] = '$' in trie return dp[0]
word-break
Clean Trie + DP Optimal Solution O(N*K), O(N+M)
KJKim
3
275
word break
139
0.455
Medium
1,869
https://leetcode.com/problems/word-break/discuss/1863365/5-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-60
class Solution: def wordBreak(self, s: str, words: List[str]) -> bool: dp=[False]*(len(s)+1) ; dp[0]=True for i in range(1, len(s)+1): for j in range(i): if dp[j] and s[j:i] in words: dp[i]=True ; break return dp[-1]
word-break
5-Lines Python Solution || 70% Faster || Memory less than 60%
Taha-C
2
217
word break
139
0.455
Medium
1,870
https://leetcode.com/problems/word-break/discuss/1863365/5-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-60
class Solution: def wordBreak(self, s: str, words: List[str]) -> bool: dp=[True] for i in range(1, len(s)+1): dp.append(any(dp[j] and s[j:i] in words for j in range(i))) return dp[-1]
word-break
5-Lines Python Solution || 70% Faster || Memory less than 60%
Taha-C
2
217
word break
139
0.455
Medium
1,871
https://leetcode.com/problems/word-break/discuss/1609592/Python-or-Recursion-or-LRU-Cache
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: @lru_cache def travel(index): result = False if index >= len(s): return True for word in wordDict: if s[index: index + len(word)] == word: result = result or travel(index + len(word)) return result return travel(0)
word-break
Python | Recursion | LRU Cache
Call-Me-AJ
2
219
word break
139
0.455
Medium
1,872
https://leetcode.com/problems/word-break/discuss/1467629/Python-BFS-and-thorough-space-and-time-complexity-analysis-explained
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: queue = deque([0]) wordDict = set(wordDict) # T.C: O(M) S.C: O(M*L) seen = set() while len(queue) != 0: for _ in range(len(queue)): # T.C: O(N) S.C: O(N) index = queue.popleft() if index == len(s): return True for i in range(index, len(s)+1): # T.C O(n^2) for loop and slice. S.C: O(N) check = s[index: i] if check in wordDict and index+len(check) not in seen: # O(1) queue.append(index+len(check)) seen.add(index+len(check)) return False
word-break
[Python] BFS and thorough space and time complexity analysis explained
asbefu
2
190
word break
139
0.455
Medium
1,873
https://leetcode.com/problems/word-break/discuss/1062460/Python-or-With-Comments
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: global result result = False # Build a graph of "sorts" graph = collections.defaultdict(set) for word in wordDict: graph[word[0]].add(word) # Recursive function @functools.lru_cache(maxsize=None) def recurse(s): global result # Termination condition 1) if result == True: return # Termination condition 2) c = s[0:1] if c == "": result = True return # Termination condition 3) if len(graph[c]) == 0: return # See which words are in here for word in graph[c]: if s[0:len(word)] == word: recurse(s[len(word):]) recurse(s) return result
word-break
Python | With Comments
dev-josh
2
273
word break
139
0.455
Medium
1,874
https://leetcode.com/problems/word-break/discuss/723335/Python3-Simple-DP-Solution-with-detailed-description-%2B-example-walkthrough
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: n = len(s) dp = [False] * n # set all to False to begin with # look at each possible substring of s and set dp[i] to True # if s[:i+1] can be built from words in wordDict for i in range(n): for j in range(i + 1): # if this substring, s[j:i+1], is in wordDict and we're able to # build s[:j] from words in wordDict (dp[j - 1] is True), # then we're also able to build s[:i+1] from words in wordDict if (j == 0 or dp[j - 1] is True) and s[j:i+1] in wordDict: dp[i] = True # no need to continue if dp[i] is already true break # only the last value in dp tells us if the full word s # can be built from words in wordDict return dp[n - 1]
word-break
[Python3] Simple DP Solution with detailed description + example walkthrough
changled123
2
206
word break
139
0.455
Medium
1,875
https://leetcode.com/problems/word-break/discuss/673995/Python-DP-93-%2B-Easy-Understand
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: # dp[i] indicates s[0:i] is whether true or false, i = 1->len-1 dp = [False for _ in range(len(s)+1)] for i in range(1,len(s)+1): if s[0:i] in wordDict: dp[i] = True else: for j in range(i-1,-1,-1): if dp[j] and s[j:i] in wordDict: dp[i] = True return dp[len(s)]
word-break
Python DP 93% + Easy Understand
vector_long_long
2
606
word break
139
0.455
Medium
1,876
https://leetcode.com/problems/word-break/discuss/274536/python-trie-%2B-bfs-solution.-O(N)-on-english-dictionary
class Trie: def __init__(self): self.arr = [None] * 26 self.word = False def add_chr(self, c): if self.arr[ord(c) - ord('a')] is None: self.arr[ord(c) - ord('a')] = Trie() return self.arr[ord(c) - ord('a')] def get_chr(self, c): return self.arr[ord(c) - ord('a')] def is_word(self): return self.word def make_word(self): self.word = True def add_word(self, word): node = self for c in word: node = node.add_chr(c) node.make_word() class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: trie = Trie() for word in wordDict: trie.add_word(word) nodes = set([0]) tmp_nodes = set() visited = set() while nodes: #print(nodes) for node in nodes: rem = s[node:] if not rem: return True trie_node = trie for i, c in enumerate(rem): trie_node = trie_node.get_chr(c) if not trie_node: break if trie_node.is_word(): tmp_nodes.add(node + i + 1) nodes = tmp_nodes - visited visited |= tmp_nodes tmp_nodes = set() return False
word-break
python trie + bfs solution. O(N) on english dictionary
theowalton1997
2
326
word break
139
0.455
Medium
1,877
https://leetcode.com/problems/word-break/discuss/2593364/Python-or-Simple-Dynamic-Programming-or-Recursion-and-Memoization
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: memo = {} def check(s, wordDict): if s in memo: return memo[s] if s == '': return True for word in wordDict: if s.startswith(word): suffix = s[len(word):] if check(suffix, wordDict): memo[word] = True return True memo[s] = False return False return check(s, wordDict)
word-break
Python | Simple Dynamic Programming | Recursion and Memoization
prameshbajra
1
177
word break
139
0.455
Medium
1,878
https://leetcode.com/problems/word-break/discuss/2271904/Python-Beats-99.32-with-full-working-explanation
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: # Time: O(n*m*n) and Space: O(n) dp = [False] * (len(s) + 1) # creating a dp list with one extra index dp[len(s)] = True # 0-8: to store true in case of we have to check the string for empty wordDict for i in range(len(s) - 1, -1, -1): # we will take 1, 2, 3, 4, .. characters at time from string for w in wordDict: # and check if the words in wordDict matches with the characters # current index in string + words length should be less than the total string length and # string from current index till the length of the word should with match the actual word from wordDict if i + len(w) <= len(s) and s[i:i + len(w)] == w: # when it's true we will store the boolean value # in dp's current index from the index in dp[current index + length of the word] # this will make sure that we are not taking any matching characters from in between the string that # will disturb the equivalent of the string i.e. s = |leet|code|code|r &amp; w = leet, code, coder? # that we are taking from one end of an array i.e. s = |leet|code|coder| &amp; w = leet, code, coder dp[i] = dp[i + len(w)] if dp[i]: # after the current index is set to True, we cannot continue to check the rest of the words from wordDict break return dp[0] # if every subsequence in string in found in wordDict then index 0 will be set to True else False
word-break
Python Beats 99.32% with full working explanation
DanishKhanbx
1
252
word break
139
0.455
Medium
1,879
https://leetcode.com/problems/word-break/discuss/2194022/DP-Solution-oror-Simplest-Approach-and-Clean-Code
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: n = len(s) dpArray = [False]*(n + 1) wordDictSet = set(wordDict) for i in range(n): if i == 0: dpArray[i] = True if dpArray[i]: for word in wordDictSet: wordLen = len(word) if s[i : i + wordLen] == word: dpArray[i + wordLen] = True return dpArray[n]
word-break
DP Solution || Simplest Approach and Clean Code
Vaibhav7860
1
129
word break
139
0.455
Medium
1,880
https://leetcode.com/problems/word-break/discuss/2093865/Python-DP-solution-runtime-less-69.77-and-memory-less-95.23
class Solution: def wordBreak(self, s, wordDict): dp = [True] + [ False for i in range(len(s)) ] for end in range(1, len(s)+1): for word in wordDict: if dp[end-len(word)] and s[end-len(word):end] == word: dp[end] = True return dp[-1]
word-break
Python DP solution runtime < 69.77% and memory < 95.23%
fatmakahveci
1
85
word break
139
0.455
Medium
1,881
https://leetcode.com/problems/word-break/discuss/1944719/Python-Dynamic-Programming-oror-100-Fast
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [False] * (len(s) + 1) dp[len(s)] = True for i in range(len(s) - 1, -1, -1): for w in wordDict: if (i + len(w)) <= len(s) and s[i: i + len(w)] == w: dp[i] = dp[i + len(w)] if dp[i]: break return dp[0]
word-break
Python - Dynamic Programming || 100% Fast
dayaniravi123
1
69
word break
139
0.455
Medium
1,882
https://leetcode.com/problems/word-break/discuss/1835214/Python-simple-top-down-prefixes-DFS-w-memoization-beats-94
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: def helper(text: str, words: List[str], memo): if text in memo: return memo[text] ans = False for word in words: if text.startswith(word): ans = helper(text[len(word):], words, memo) if ans: break memo[text] = ans return ans memo = {"":True} return helper(s, wordDict, memo)
word-break
Python simple top down prefixes DFS w/ memoization beats 94%
gjfrazar
1
148
word break
139
0.455
Medium
1,883
https://leetcode.com/problems/word-break/discuss/1764658/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: @lru_cache(None) def dp(s: str): if s in wordDict: return True for i in range(1, len(s)): if dp(s[:i]) and dp(s[i:]): return True return False return dp(s)
word-break
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
1
135
word break
139
0.455
Medium
1,884
https://leetcode.com/problems/word-break/discuss/1764658/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [False]*len(s) for i in range(len(s)): for word in wordDict: if i >= len(word)-1 and (i == len(word)-1 or dp[i-len(word)]): if s[i-len(word)+1:i+1] == word: dp[i] = True break return dp[len(s)-1]
word-break
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
1
135
word break
139
0.455
Medium
1,885
https://leetcode.com/problems/word-break/discuss/1704293/Python-memoization-soln
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp={} return self.recur(s,wordDict,0,"",dp) def recur(self,s,words,l,d,dp): if l>len(s): return False if d[:l+1] in dp: return dp[d[:l+1]] if d!="" and d[:l+1]!=s[:l]: return False if l==len(s): return True e=False for i in words: e=e or self.recur(s,words,l+len(i),d+i,dp) dp[(d+i)[:l+len(i)]]=e if e: return e return e
word-break
Python memoization soln
Adolf988
1
228
word break
139
0.455
Medium
1,886
https://leetcode.com/problems/word-break/discuss/1669014/Python-or-2-approaches-or-DP-or-recursion-or-with-comments
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: hsh = {} # recursion approach def helper(str): if len(str)==0: return True # below is to use the result that's already computed if str in hsh: return hsh[str] out = False # at every index, if a word from 0 to index is present in wordDict # we have 2 choices, we can either choose the word or not # run both the possibilities and store the result in hsh for i in range(1,len(str)+1): if str[:i] in wordDict: out = helper(str[i:]) if out: hsh[str[i:]]=True return hsh[str[i:]] hsh[str] = False return hsh[str] return helper(s)
word-break
Python | 2 approaches | DP | recursion | with comments
vishyarjun1991
1
218
word break
139
0.455
Medium
1,887
https://leetcode.com/problems/word-break/discuss/1068797/Python-iterative-solution-with-memoization-98
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: self.wordDict = wordDict return self.bfs(s) def bfs(self, s): mem = set() q = [s] while q rem = q.pop(0) if not rem: return True if rem not in mem: mem.add(rem) for word in self.wordDict: l = len(word) if rem[:l] == word: q.append(rem[l:]) return False
word-break
Python iterative solution with memoization [98%]
arnav3
1
337
word break
139
0.455
Medium
1,888
https://leetcode.com/problems/word-break/discuss/706635/Python3-dp-(top-down-and-bottom-up)
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: @lru_cache(None) def fn(i): "Return True if s[i:] can be segmented" if i == len(s): return True return any(s[i:].startswith(word) and fn(i + len(word)) for word in wordDict) return fn(0)
word-break
[Python3] dp (top-down & bottom-up)
ye15
1
164
word break
139
0.455
Medium
1,889
https://leetcode.com/problems/word-break/discuss/706635/Python3-dp-(top-down-and-bottom-up)
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [False]*(1 + len(s)) dp[0] = True for i in range(len(s)): if dp[i]: for word in wordDict: if s[i:i+len(word)] == word: dp[i+len(word)] = True return dp[-1]
word-break
[Python3] dp (top-down & bottom-up)
ye15
1
164
word break
139
0.455
Medium
1,890
https://leetcode.com/problems/word-break/discuss/706635/Python3-dp-(top-down-and-bottom-up)
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [False]*len(s) + [True] for i in reversed(range(len(s))): for word in wordDict: if s[i:i+len(word)] == word and dp[i+len(word)]: dp[i] = True return dp[0]
word-break
[Python3] dp (top-down & bottom-up)
ye15
1
164
word break
139
0.455
Medium
1,891
https://leetcode.com/problems/word-break/discuss/706635/Python3-dp-(top-down-and-bottom-up)
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: trie = {} for word in wordDict: node = trie for ch in word: node = node.setdefault(ch, {}) node['$'] = word dp = [False] * (len(s) + 1) dp[0] = True for i in range(len(s)): if dp[i]: node = trie for ii in range(i, len(s)): if s[ii] not in node: break node = node[s[ii]] if '$' in node: dp[ii+1] = True return dp[-1]
word-break
[Python3] dp (top-down & bottom-up)
ye15
1
164
word break
139
0.455
Medium
1,892
https://leetcode.com/problems/word-break/discuss/2767350/Python-DP-solution
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: ## DP dp = [False]* (len(s)+1) dp[0] = True for i in range(1,len(s)+1): for w in wordDict: if s[i-len(w):i]==w: dp[i] = dp[i-len(w)] if dp[i]: break return dp[-1]
word-break
Python DP solution
babli_5
0
7
word break
139
0.455
Medium
1,893
https://leetcode.com/problems/word-break/discuss/2757705/Easy-to-Understand-Python3-Implementation
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: # Cache will keep track of the indices that are unable to be segmented from cache = set() def segment(i): # Base Case 1) Entire s has been segmented if i == len(s): return True # Base Case 2) Not possible from index i if i in cache: return False # Try to segement s from index i with all words int he wordDict for word in wordDict: # If we can segement s from index i and reach the end -> True if s.startswith(word, i) and segment(i + len(word)): return True # tried all words and not possible to segment s from index i cache.add(i) return False return segment(0)
word-break
Easy to Understand Python3 Implementation
PartialButton5
0
9
word break
139
0.455
Medium
1,894
https://leetcode.com/problems/word-break/discuss/2750566/Python-3-easy-bottom-up-Tabulation-DP-solution
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dic=defaultdict(list) for word in wordDict: dic[len(word)].append(word) # Bucket by length LEN=len(s) dp=[True]+[False]*LEN # dp[i]: substring from 1st to ith characters of s is True for i in range(LEN): for wordlen in dic: # enumerate lengths of words pre=i-wordlen+1 # previous substring # only if substring is 1.legal and 2.True and 3.current word is in dictionary if pre>-1 and dp[pre] and s[pre:i+1] in dic[wordlen]: dp[i+1]=True break return dp[-1]
word-break
[Python] 3 easy bottom up Tabulation DP solution
evergreenyoung
0
12
word break
139
0.455
Medium
1,895
https://leetcode.com/problems/word-break/discuss/2730022/Python3-DP-Understandable-4-Lines
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: # A[i] true if s[:i+1] (s_0..s_i) can be segmented # # Base Case: A[0] is true becuase "" can be segmented # Inductive Case: A[i] is true if there is some word such that # s[:i+1] ends with it AND the rest can be segmented # A = [True] * len(s) for i in range(len(s)): A[i] = any(s[:i+1].endswith(w) and A[i - len(w)] for w in wordDict) return A[-1]
word-break
Python3 DP Understandable 4 Lines
jbradleyglenn
0
20
word break
139
0.455
Medium
1,896
https://leetcode.com/problems/word-break/discuss/2726282/Python3-Simple-1D-DP-(Bottom-up)
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [False] * (len(s)+1) dp[-1] = True for i in range(len(s)-1, -1, -1): for w in wordDict: if s[i:].startswith(w): dp[i] |= dp[i+len(w)] return dp[0]
word-break
Python3 Simple 1D DP (Bottom-up)
jonathanbrophy47
0
10
word break
139
0.455
Medium
1,897
https://leetcode.com/problems/word-break/discuss/2722114/Python-or-Trie-Solution-or-Beats-80-or-Simple-or-Recursive
class TrieNode: def __init__(self): self.children, self.end = {}, False class Trie: def __init__(self): self.root = TrieNode() self.memo = {} # Time O(K) - where K is the length of the word def insert(self, word): curr = self.root for char in word: if char not in curr.children: curr.children[char] = TrieNode() curr = curr.children[char] curr.end = True # Time O(K) - where K is the length of the word def find(self, word): curr = self.root for i, char in enumerate(word): if char not in curr.children: return False if curr.children[char].end: remaining_word = word[i+1:] if remaining_word not in self.memo: self.memo[remaining_word] = self.find(remaining_word) if self.memo[remaining_word]: return True curr = curr.children[char] return curr.end class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: trie = Trie() for word in wordDict: trie.insert(word) return trie.find(s)
word-break
Python | Trie Solution | Beats 80% | Simple | Recursive
david-cobbina
0
9
word break
139
0.455
Medium
1,898
https://leetcode.com/problems/word-break/discuss/2692781/O(n2)-DP-with-Trie-(no-substring-generation)
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: N = len(s) word_set = set(wordDict) dp = [False] * (N + 1) dp[0] = True for i in range(0, N): if not dp[i]: continue for j in range(i+1, N+1): if s[i:j] in word_set: # See? They all start at "i" now. dp[j] = True return dp[N]
word-break
O(n^2) DP with Trie (no substring generation)
oblivion95
0
4
word break
139
0.455
Medium
1,899