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/find-pivot-index/discuss/2789321/Runtime-164-ms-Beats-87.88-Python-Solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
totalSum , leftSum = sum(nums), 0
for idx, val in enumerate(nums):
if leftSum == totalSum - val - leftSum:
return idx
leftSum += val
return -1 | find-pivot-index | Runtime 164 ms Beats 87.88%; Python Solution | ratva0717 | 0 | 4 | find pivot index | 724 | 0.535 | Easy | 11,900 |
https://leetcode.com/problems/find-pivot-index/discuss/2783711/Python-Straightforward-solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
for i in range(0,len(nums)-1):
if sum(nums[:i])==sum(nums[i+1:]):
return i
if sum(nums[1:])==0:
return 0
if sum(nums[:len(nums)-1])==0:
return len(nums)-1
return -1 | find-pivot-index | Python Straightforward solution | SnehaGanesh | 0 | 3 | find pivot index | 724 | 0.535 | Easy | 11,901 |
https://leetcode.com/problems/find-pivot-index/discuss/2782049/Find-Pivot-Index-or-Easy-python-soluion | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
totalSum,leftSum = sum(nums),0
for i in range(len(nums)):
if i > 0:
leftSum = leftSum + nums[i-1]
rightSum = totalSum - (leftSum + nums[i])
if leftSum == rightSum:
return i
return -1 | find-pivot-index | Find Pivot Index | Easy python soluion | nishanrahman1994 | 0 | 2 | find pivot index | 724 | 0.535 | Easy | 11,902 |
https://leetcode.com/problems/find-pivot-index/discuss/2779686/Python-3 | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left_sum = 0
for index,num in enumerate(nums):
if left_sum == sum(nums)-left_sum-num:
return index
left_sum = left_sum + num
return -1 | find-pivot-index | Python 3 | YaoYuanxin | 0 | 5 | find pivot index | 724 | 0.535 | Easy | 11,903 |
https://leetcode.com/problems/find-pivot-index/discuss/2777509/Python-Solution-or-Clean-Code-or-Prefix-Sum-Based | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
# Prefix Sum
currSum = 0
fullSum = sum(nums)
for index, num in enumerate(nums):
currSum += num
if currSum == fullSum:
return index
fullSum -= num
return -1 | find-pivot-index | Python Solution | Clean Code | Prefix Sum Based | Gautam_ProMax | 0 | 4 | find pivot index | 724 | 0.535 | Easy | 11,904 |
https://leetcode.com/problems/find-pivot-index/discuss/2776262/Python-O(n)-Time-Complexity-Easy-to-understand | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
sum = 0
currSum = 0
for num in nums:
sum += num
for i in range(len(nums)):
if (sum - nums[i])/2 == currSum:
return i
currSum += nums[i]
return -1 | find-pivot-index | Python - O(n) Time Complexity - Easy to understand | SuryaSekhar14 | 0 | 2 | find pivot index | 724 | 0.535 | Easy | 11,905 |
https://leetcode.com/problems/find-pivot-index/discuss/2772043/Python-Easy-Prefix-Sum-Approach-oror-Beats-92-of-the-solutions-oror | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
preSum = 0
postSum = 0
for i in nums:
postSum += i
for i in range(len(nums)):
postSum -= nums[i]
if(preSum == postSum):
return i
preSum += nums[i]
return -1 | find-pivot-index | Python Easy Prefix Sum Approach || Beats 92% of the solutions || | vedanthvbaliga | 0 | 3 | find pivot index | 724 | 0.535 | Easy | 11,906 |
https://leetcode.com/problems/find-pivot-index/discuss/2764841/Generate-a-list-of-cumulative-sums-first-then-do-a-minus-calculation. | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
if sum(nums[1:]) == 0:
return 0
cum_sum = [nums[0]]
for i in range(1, len(nums)):
prefix_sum = cum_sum[i-1] + nums[i]
cum_sum.append(prefix_sum)
for i in range(1,len(cum_sum)):
if cum_sum[i-1] == cum_sum[-1] - cum_sum[i]:
return i
return -1 | find-pivot-index | Generate a list of cumulative sums first, then do a minus calculation. | zhuoya-li | 0 | 2 | find pivot index | 724 | 0.535 | Easy | 11,907 |
https://leetcode.com/problems/find-pivot-index/discuss/2758783/Pivot-index | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
runningsum = []
sumval = 0
for i in nums:
sumval += i
runningsum.append(sumval)
lenval = len(nums)
sumarr = runningsum[lenval - 1]
for i in range(0,lenval):
if runningsum[i] - nums[i] == sumarr - runningsum[i]:
return i
return -1 | find-pivot-index | Pivot index | keerthikrishnakumar93 | 0 | 2 | find pivot index | 724 | 0.535 | Easy | 11,908 |
https://leetcode.com/problems/find-pivot-index/discuss/2751382/Python-Solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
n = len(nums)
running_sum = [0 for _ in range(n)]
for i in range(n):
running_sum[i] = running_sum[i - 1] + nums[i] if i > 0 else nums[i]
for i in range(n):
left = running_sum[i] - nums[i]
right = running_sum[n - 1] - running_sum[i]
if left == right:
return i
return -1 | find-pivot-index | Python Solution | mansoorafzal | 0 | 6 | find pivot index | 724 | 0.535 | Easy | 11,909 |
https://leetcode.com/problems/find-pivot-index/discuss/2730172/Python-Simple-Solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
rightSum = sum(nums)
leftSum = 0
for i in range(len(nums)):
if leftSum == rightSum - leftSum - nums[i]:
return i
leftSum += nums[i]
return -1 | find-pivot-index | Python Simple Solution | vbrunell | 0 | 5 | find pivot index | 724 | 0.535 | Easy | 11,910 |
https://leetcode.com/problems/find-pivot-index/discuss/2725825/Python-Simple-Solution | class Solution:
def pivotIndex(self, n: List[int]) -> int:
s=sum(n)
for i in range(len(n)):
t=sum(n[:i])
if t == s-t-n[i]:
return i
return -1 | find-pivot-index | Python Simple Solution | SouravSingh49 | 0 | 9 | find pivot index | 724 | 0.535 | Easy | 11,911 |
https://leetcode.com/problems/find-pivot-index/discuss/2722344/Python-simple-solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
tot_sum=sum(nums)
right=0
for i in range(len(nums)):
tot_sum-=nums[i]
if right==tot_sum:
return i
tot_sum-=nums[i]
return -1 | find-pivot-index | Python simple solution | madhan51 | 0 | 4 | find pivot index | 724 | 0.535 | Easy | 11,912 |
https://leetcode.com/problems/find-pivot-index/discuss/2718576/Approach-explained-step-by-step-oror-Python3 | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
sum_to_the_left = 0
sum_to_the_right = sum(nums)
for i in range(len(nums)):
sum_to_the_right -= nums[i]
if sum_to_the_left == sum_to_the_right:
return i
sum_to_the_left += nums[i]
return -1 | find-pivot-index | Approach explained step-by-step || Python3 | aaalex_lit | 0 | 1 | find pivot index | 724 | 0.535 | Easy | 11,913 |
https://leetcode.com/problems/find-pivot-index/discuss/2714835/Very-easy-python-solution-explained | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
#imagine you are at index before 0, so all array is to the right and 0 is to the left
sum_l, sum_r, prev = 0, sum(nums), 0
# we shall remember the previous element of the array (at imaginable index before 0 it is 0)
for i, n in enumerate(nums):
sum_l += prev
sum_r -= n
prev = n
# print(i, n, sum_l, sum_r, prev)
if sum_l == sum_r: return i
return(-1) | find-pivot-index | Very easy python solution, explained | tatiana_ospv | 0 | 1 | find pivot index | 724 | 0.535 | Easy | 11,914 |
https://leetcode.com/problems/find-pivot-index/discuss/2687256/(Python)Runtime%3A-243-ms-beats-67 | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
nums=nums+[0]
left_sum=0
right_sum=sum(nums)-nums[0]
for i in range(0,len(nums)-1):
if(left_sum==right_sum):
return i
else:
left_sum=left_sum+nums[i]
right_sum=right_sum-nums[i+1]
return -1 | find-pivot-index | (Python)Runtime: 243 ms beats 67% | VishalAgarwal | 0 | 2 | find pivot index | 724 | 0.535 | Easy | 11,915 |
https://leetcode.com/problems/find-pivot-index/discuss/2680954/Easy-Python-Solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
nums = nums + [0]
left, right = 0, sum(nums) - nums[0]
for i in range(len(nums)-1):
if left == right:
return i
left += nums[i]
right -= nums[i+1]
return -1 | find-pivot-index | Easy Python Solution | lluB | 0 | 87 | find pivot index | 724 | 0.535 | Easy | 11,916 |
https://leetcode.com/problems/find-pivot-index/discuss/2675011/Find-Pivot-Index | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
s = sum(nums)
i = 0
n = len(nums)
temp = 0
while i < n:
s -= nums[i]
if temp == s:
return i
temp += nums[i]
i += 1
return -1 | find-pivot-index | Find Pivot Index | jashii96 | 0 | 1 | find pivot index | 724 | 0.535 | Easy | 11,917 |
https://leetcode.com/problems/find-pivot-index/discuss/2664005/Python-or-Prefix-Sum | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
if(len(nums) <= 1):
return 0
s = sum(nums)
c = 0
for i in range(len(nums)):
if (s - nums[i]) / 2 == c:
return i
c += nums[i]
return -1 | find-pivot-index | Python | Prefix Sum | jaisalShah | 0 | 6 | find pivot index | 724 | 0.535 | Easy | 11,918 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/1322974/Clean-Python-and-Java | class Solution:
def splitListToParts(self, head: ListNode, k: int) -> List[ListNode]:
size = self.get_size(head)
min_len, one_more = divmod(size, k)
res = []
current = ListNode()
current.next = head
for i in range(k):
ans = current
for _ in range(min_len + int(i < one_more)):
current = current.next
res.append(ans.next)
ans.next = None
return res
def get_size(self, head: ListNode) -> int:
size = 0
while head is not None:
size += 1
head = head.next
return size | split-linked-list-in-parts | Clean Python and Java | aquafie | 4 | 456 | split linked list in parts | 725 | 0.572 | Medium | 11,919 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/469189/Python-3-(ten-lines)-(36-ms) | class Solution:
def splitListToParts(self, H: ListNode, k: int) -> List[ListNode]:
A, B, i = [], [], 0
while H != None: H, _ = H.next, A.append(H.val)
LA = len(A)
(n, r) = divmod(LA,k) if k < LA else (1,0)
A.extend([0]*(k-LA))
for s in range(k):
L = LH = ListNode(A[i])
for j in range(i+1,i+n+(r>0)): L.next = ListNode(A[j]); L = L.next
i, r, _ = i + n + (r>0), r - 1, B.append(LH if s<LA else None)
return B
- Junaid Mansuri
- Chicago, IL | split-linked-list-in-parts | Python 3 (ten lines) (36 ms) | junaidmansuri | 1 | 533 | split linked list in parts | 725 | 0.572 | Medium | 11,920 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/2628797/Python3-or-Clean-Code-or-O(max(nk)) | class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
tmp=head
n,ans=0,[]
while tmp:
n+=1
tmp=tmp.next
count=[0 for i in range(k)]
div,rem=n//k,n%k
for i in range(k):
count[i]=div+min(rem,1)
if rem>0:
rem-=1
tmp=head
for ind,c in enumerate(count):
curr=dummy=ListNode(-1)
while c>0:
newNode=ListNode(tmp.val)
dummy.next=newNode
dummy=newNode
tmp=tmp.next
c-=1
ans.append(curr.next)
return ans | split-linked-list-in-parts | [Python3] | Clean Code | O(max(n,k)) | swapnilsingh421 | 0 | 7 | split linked list in parts | 725 | 0.572 | Medium | 11,921 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/1850421/Clean-2-pass-solution-in-Python | class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
def gen():
nonlocal k
length, cur = 0, head
while cur:
length += 1
cur = cur.next
prev, cur, q, r = None, head, *divmod(length, k)
for _ in range(k):
# yield head of current partition
yield cur
# move to the next part
for _ in range(q + (r > 0)):
prev = cur
if cur:
cur = cur.next
# split from previous part
if prev:
prev.next = None
r -= 1
return list(gen()) | split-linked-list-in-parts | Clean 2-pass solution in Python | mousun224 | 0 | 75 | split linked list in parts | 725 | 0.572 | Medium | 11,922 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/1841950/725)-Split-Linked-List-In-Parts-or-Easy-Try-Dry-Run-or-Python | class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
arr = []
cur, n = head, 0
prev = None
while cur:
n += 1
cur = cur.next
cur = head
part = n // k
extra = n % k
for _ in range(k):
arr.append(cur)
for _ in range(part):
prev = cur
cur = cur.next
if extra and cur:
extra -= 1
prev = cur
cur = cur.next
if prev:
prev.next = None
return arr | split-linked-list-in-parts | 725) Split Linked List In Parts | Easy, Try Dry Run | Python | akshattrivedi9 | 0 | 45 | split linked list in parts | 725 | 0.572 | Medium | 11,923 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/1838760/Self-Understandable-Python-%3A | class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
if not head:
return [None]*k
temp=head
height=0
while temp:
height+=1
temp=temp.next
ans=[]
if k>=height:
temp=head
while temp:
x=temp
ans.append(x)
temp=temp.next
x.next=None
while len(ans)<k:
ans.append(None)
return ans
remainder=height%k
quotient=height//k
temp=head
for i in range(k):
j=1
if remainder>0:
length=quotient+1
remainder-=1
else:
length=quotient
x=temp
ans.append(x)
while j<=length:
x=temp
temp=temp.next
j+=1
x.next=None
return ans | split-linked-list-in-parts | Self Understandable Python : | goxy_coder | 0 | 67 | split linked list in parts | 725 | 0.572 | Medium | 11,924 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/1597531/Python-3-iterative-solution | class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
size = 0
cur = head
while cur:
size += 1
cur = cur.next
group_size, extra = divmod(size, k)
i = 1
cur = head
res = []
while cur:
if i == group_size + (extra > 0):
res.append(head)
head, cur.next = cur.next, None
cur = head
i = 1
extra -= 1
else:
cur = cur.next
i += 1
if group_size == 0:
res.extend([None] * (k - len(res)))
return res | split-linked-list-in-parts | Python 3 iterative solution | dereky4 | 0 | 93 | split linked list in parts | 725 | 0.572 | Medium | 11,925 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/1494008/Python3-Two-passes-solution | class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
cnt = 0
cur_ptr = head
while cur_ptr:
cnt += 1
cur_ptr = cur_ptr.next
mod = cnt % k
width = cnt // k
res = [None] * k
for sublist_idx in range(k):
cur_node_cnt = 1
res[sublist_idx] = head
while cur_node_cnt < width + (mod > 0):
head = head.next
cur_node_cnt += 1
if head:
mod -= 1
prev = head
head = head.next
prev.next = None
return res | split-linked-list-in-parts | [Python3] Two passes solution | maosipov11 | 0 | 30 | split linked list in parts | 725 | 0.572 | Medium | 11,926 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/1493572/Split-Linked-List-in-Parts-or-Python-3-or-Simple | class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
temp = head
cnt = 0
while temp != None:
cnt += 1
temp = temp.next
out = []
if k >= cnt:
temp = head
for i in range(0, cnt):
head = temp.next
temp.next = None
out.append(temp)
temp = head
for i in range(cnt, k):
out.append(None)
return out
base, add1_runs = divmod(cnt, k)
for i in range(0, add1_runs):
temp = head
out.append(head)
for j in range(0, base):
temp = temp.next
head = temp.next
temp.next = None
for i in range(add1_runs, k):
temp = head
out.append(head)
for j in range(0, base - 1):
temp = temp.next
head = temp.next
temp.next = None
return out | split-linked-list-in-parts | Split Linked List in Parts | Python 3 | Simple | manuel_lemos | 0 | 195 | split linked list in parts | 725 | 0.572 | Medium | 11,927 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/1026734/python-0(N)-solution-with-explanation.-Beats-100-of-Submissions | class Solution(object):
def splitListToParts(self, root, k):
"""
:type root: ListNode
:type k: int
:rtype: List[ListNode]
"""
size = self.getSize(root)
if size > k:
#this is how many sub linked list that will have an extra node
extraNodes = size % k
# this is how much we want to split by initially
bigNum = (size/k) + 1
else:
#in this case right here, we will be partitioning our linkedList by one node
extraNodes = 0
# in my code below, it will go into the else statement that will extract 1 node
bigNum = 2
finalList = []
temp = root
while k and temp:
if extraNodes:
#extract linked list with size bigNum
newHead, tail = self.getTwoPoint(temp, bigNum)
extraNodes -=1
else:
#extract linkedlist with size bigNum-1
newHead,tail = self.getTwoPoint(temp, bigNum-1)
temp = tail.next
tail.next = None
finalList.append(newHead)
k-=1
#finish the rest of the partition with appending empty list
while k:
finalList.append(None)
k-=1
return finalList
def getTwoPoint(self, root, count):
tail = root
count-=1
while count:
tail = tail.next
count -= 1
return (root,tail)
def getSize(self, root):
count = 0
temp = root
while temp:
count+=1
temp = temp.next
return count | split-linked-list-in-parts | python 0(N) solution with explanation. Beats 100% of Submissions | daveavi | 0 | 173 | split linked list in parts | 725 | 0.572 | Medium | 11,928 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/916663/Python3-breaking-linked-list-in-place | class Solution:
def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
n, node = 0, root # length of linked list
while node: n, node = n+1, node.next
ans = []
node = root
q, r = divmod(n, k) # quotient & residual
q += 1
for i in range(k):
ans.append(node)
if i == r: q -= 1
prev = None
for _ in range(q):
prev = node
if node: node = node.next
if prev: prev.next = None # break list into parts
return ans | split-linked-list-in-parts | [Python3] breaking linked list in place | ye15 | 0 | 67 | split linked list in parts | 725 | 0.572 | Medium | 11,929 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/341717/Python3-simple-and-efficient-solution | class Solution:
def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
res=[]
division=[0]*k
i=root
l=0
while i:
l+=1
i=i.next
for i in range(l):
division[i%k]+=1
i=h2=root
j=0
while j<len(division) and division[j]!=0:
p=0
while p<division[j]-1:
i=i.next
p+=1
res.append(h2)
h2=i.next
i.next=None
i=h2
j+=1
for i in range(k-j):
res.append(None)
return res | split-linked-list-in-parts | Python3 simple and efficient solution | ketan35 | 0 | 200 | split linked list in parts | 725 | 0.572 | Medium | 11,930 |
https://leetcode.com/problems/split-linked-list-in-parts/discuss/1493531/Python3-Simple-Two-Pass | class Solution:
def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
n = 0
current = head
while (current):
n += 1
current = current.next
parts = []
for k in range(k, 0, -1):
partSize = ceil(n / k)
nextNode = head
for _ in range(partSize - 1):
if (not nextNode): break
nextNode = nextNode.next
parts.append(head)
if (nextNode):
head = nextNode.next
nextNode.next = None
n -= partSize
return parts | split-linked-list-in-parts | Python3 - Simple Two Pass ✅ | Bruception | -1 | 45 | split linked list in parts | 725 | 0.572 | Medium | 11,931 |
https://leetcode.com/problems/number-of-atoms/discuss/1335787/efficient-O(N)-python3-solution-using-stack-of-stacks-with-explanation-of-code-and-approach | class Solution:
def countOfAtoms(self, formula: str) -> str:
# constant declarations
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower=upper.lower()
digits = "0123456789"
# variables
count=defaultdict(int)
element_name = None
element_name_parse_start=False
element_count =""
bracket_stacks = [[]]
buffer = []
# function to parse out the complete number if a digit is seen,
# the function takes the character, that was seen as a digit and
# the generator object to get the remaining (yet to be read) part of formula
def parseout_number(ch,gen):
nonlocal buffer
num=""
try:
while ch in digits:
num += ch
ch = next(gen)
# after number is parsed out and a non-number character is seen,
# add that non-number character to the buffer to be read next, dont miss parsing it
buffer.append(ch)
except StopIteration:
# while iterating to find the end digit of the number, we have reached the end of the formula,
# meaning the digit ch and subsequent characters were numbers and were the last thing in the formula
# the code, outside of try-catch handles all the possible scenerios of parsing the number out,
# so do nothing here. move along
pass
# if we saw a number, return it as integer, else return empty string
if num != "":
return int(num)
else:
return ""
#generator expression
formula_chars = (ch for ch in formula)
# iterate over all characters
for char in formula_chars:
# add the character emitted by generator into buffer for processing
buffer.append(char)
# process what ever is in the buffer queue
while buffer:
ch = buffer.pop(0)
# if the character is an upper case character
# set the a flag to indicate start of a new element name
# check if the previous elementname was added to the processing_stack (bracket_stacks)
# if not then add it, noting one atom for that element
# set the character to element_name variable
if ch in upper:
element_name_parse_start=True
if element_name is not None and element_count == "":
bracket_stacks[-1].append([element_name,1])
element_name = ch
# if character is lowercase, just concat it to the element_name
elif ch in lower:
element_name += ch
# if character is a numerical digit, then parse that number out completely as integer
# set the flag to indicate the reading the element name is done
# store the element name and it's corresponding count into the processing_stack
# reset the variables element_name and element_count, ready for next element
elif ch in digits:
element_name_parse_start=False
element_count = parseout_number(ch,formula_chars)
bracket_stacks[-1].append([element_name,element_count])
element_count = ""
element_name = None
# if open bracket is seen, check if reading the element_name flag is still True
# if it is then that element has one atom only
# add it to the processing stack
# set the flag to indicate that reading the 'element_name' is done and
# add another processing stack top the top of the 'bracket_stacks'
# this new processing stack will have the atom details within the bracket
# finally, reset all other variables to ensure
# clean slate for the new child 'processing-stack' before exiting the code-block
elif ch == "(":
if element_name_parse_start:
bracket_stacks[-1].append([element_name,1])
element_name_parse_start=False
element_count = ""
bracket_stacks.append([]) # new processing stack
element_name = None
# if a bracket is closed
# make sure we account for one atom of element, if a number was not seen before closing the bracket
# set the flag to indicate we are done reading element_name
# check what is the next character after the bracket close char.
# if it's a digit, then parse that number out
# that number is the multiplier for the current processing stack
# which means we will need to multiply every atom/element count by the multiplier
# at this point the current processing stack
# which was created as part of opening the bracket is processed
# so, merge what we found into the parent processing stack by
# extending the parent processing stack with the results of the child stack
elif ch == ")":
if element_name_parse_start:
bracket_stacks[-1].append([element_name,1])
element_name = None
element_name_parse_start=False
braket_multiplier = ""
try:
next_ch= next(formula_chars)
braket_multiplier = parseout_number(next_ch,formula_chars)
except StopIteration:
pass
if braket_multiplier == "":
braket_multiplier = 1
# pop the child processing - stack to be processed
process_this = bracket_stacks.pop()
#processing
for idx,_ in enumerate(process_this):
process_this[idx][1] = process_this[idx][1]*braket_multiplier
#merging processed child stack with the parent stack
bracket_stacks[-1].extend(process_this)
# if the new element name seen flag is set then process that
# atom by adding it's element-name and atom count to the current processing stack
if element_name_parse_start:
if element_name is not None:
if element_count != "":
bracket_stacks[-1].append([element_name,int(element_count)])
else:
bracket_stacks[-1].append([element_name,1])
# pop the top-level processing-stack, this should contain a 'flattened' version of the atoms and their counts
# note that the counts of elements are not aggregated yet,
# eg:If Oxygen was seen within a bracket and also seen outside that bracket,
# then we'll have two entries for Oxygen. We'll aggregate them next...
count_pairs = bracket_stacks.pop()
# aggregate all the 'flattened' data in 'count_pairs' variable, using a dictionary
for element_name,element_count in count_pairs:
count[element_name]+= element_count
# preparing the output string...
# create a list meant to hold the 'words' of the output string, based on the description
output=[]
# fetch the keylist
elements_list = list(count.keys())
#sort it
elements_list.sort()
# for each element in the sorted keylist, if the element has more
# than 1 atom, append the atom and it's count
# if element has only 1 atom only append the atom name,
# but don't append the atom's count (which is 1)
for element in elements_list:
if count[element] > 1:
output.append(element)
output.append(str(count[element]))
else:
output.append(element)
# output will now have an list of words representation of what we need. turn the list into a string and return it
return "".join(output) | number-of-atoms | efficient O(N) python3 solution, using stack of stacks with explanation of code and approach | anupamkumar | 2 | 258 | number of atoms | 726 | 0.522 | Hard | 11,932 |
https://leetcode.com/problems/number-of-atoms/discuss/1349342/Python3-recursive-implementation | class Solution:
def countOfAtoms(self, formula: str) -> str:
mp = {}
stack = []
for i, x in enumerate(formula):
if x == "(": stack.append(i)
elif x == ")": mp[stack.pop()] = i
def fn(lo, hi):
"""Return count of atom in a freq table."""
k = lo
ans = defaultdict(int)
while k < hi:
cnt = 0
if formula[k] == "(":
freq = fn(k+1, mp[k])
k = mp[k] + 1
while k < hi and formula[k].isdigit():
cnt = 10*cnt + int(formula[k])
k += 1
for key, val in freq.items(): ans[key] += val * max(1, cnt)
else:
atom = formula[k]
k += 1
while k < hi and formula[k] != "(" and not formula[k].isupper():
if formula[k].isalpha(): atom += formula[k]
else: cnt = 10*cnt + int(formula[k])
k += 1
ans[atom] += max(1, cnt)
return ans
ans = []
for k, v in sorted(fn(0, len(formula)).items()):
ans.append(k)
if v > 1: ans.append(str(v))
return "".join(ans) | number-of-atoms | [Python3] recursive implementation | ye15 | 0 | 64 | number of atoms | 726 | 0.522 | Hard | 11,933 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1233710/WEEB-DOES-PYTHON(BEATS-91.49) | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
result = []
for i in range(left, right+ 1):
if "0" in str(i): continue
val = i
while val > 0:
n = val % 10
if i % n != 0:
val = -1
val = val // 10
if val != -1: result.append(i)
return result | self-dividing-numbers | WEEB DOES PYTHON(BEATS 91.49%) | Skywalker5423 | 4 | 278 | self dividing numbers | 728 | 0.776 | Easy | 11,934 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2840839/PYTHON-With-Comments-or-Simple | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
v = []
for x in range(left, right+1):
# iterate thru every number left-right
a = [*str(x)]
# basically splits the str version of the number
# ex: 22 -> ['2','2']
d = True
# bool variable to validate every number is self dividing
for r in a:
if int(r) != 0:
# making sure r is not something like '0' in something like 10 for example
if x%int(r)!=0:
# if there is a number thats remainder is not 0
d = False
else:
d = False
# falsing when there is a number such as 10, 20
if d:
v.append(x)
# if d ends up being true, it appends x to v
return v | self-dividing-numbers | [PYTHON] With Comments | Simple | omkarxpatel | 2 | 15 | self dividing numbers | 728 | 0.776 | Easy | 11,935 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2657873/Python-oror-Runtime%3A-54-ms-faster-than-90.82-less-than-98.22-oror | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
ans = []
for i in range(left,right+1):
val = i
res = True
if "0" not in str(i):
while val != 0:
val1 = val % 10
if i%val1!=0:
res = False
val = val // 10
if res: ans.append(i)
return ans | self-dividing-numbers | 🔥 Python || Runtime: 54 ms, faster than 90.82%, less than 98.22% || | rajukommula | 1 | 128 | self dividing numbers | 728 | 0.776 | Easy | 11,936 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2166758/Python3-Runtime%3A-45ms-94.99-Memory%3A-14.1mb-22.45 | class Solution:
# Runtime: 45ms 94.99% Memory: 14.1mb 22.45%
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
if not left and not right:
return []
numberRange = list(range(left, right + 1))
result = []
for i in numberRange:
flag = True
copy = i
while copy != 0:
num = copy % 10
if num == 0 or i % num != 0:
flag = False
break
copy //= 10
if flag:
result.append(i)
return result | self-dividing-numbers | Python3 Runtime: 45ms 94.99% Memory: 14.1mb 22.45% | arshergon | 1 | 89 | self dividing numbers | 728 | 0.776 | Easy | 11,937 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2005760/Python-Clean-and-Simple! | class Solution:
def selfDividingNumbers(self, left, right):
return list(filter(self.isSelfDividing, range(left,right+1)))
def isSelfDividing(self, num):
digits = {int(c) for c in str(num)}
if 0 in digits: return False
else: return all(num % d == 0 for d in digits) | self-dividing-numbers | Python - Clean and Simple! | domthedeveloper | 1 | 99 | self dividing numbers | 728 | 0.776 | Easy | 11,938 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1597446/Python-Easy-Solution-or-Faster-than-99 | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
res = []
for num in range(left, right+1):
if num < 10:
res.append(num)
else:
temp = num
while temp != 0:
div = temp % 10
if div != 0 and num % div == 0:
temp //= 10
else:
break
if temp == 0:
res.append(num)
return res | self-dividing-numbers | Python Easy Solution | Faster than 99% | leet_satyam | 1 | 171 | self dividing numbers | 728 | 0.776 | Easy | 11,939 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2838545/Fast-and-Easy-python-solution-oror-faster-than-83-oror-Create-nested-function | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def divide(num): # initiate my own divide function
res = list(map(int, str(num))) # turn the number into a list of digits
for i in res:
if i == 0: # return false if there is a 0
return False
if num % i == 0: # return false if there is a remainder for one of the digits
continue
else:
return False
return True # else return true
templist = [] # create our results list
for i in range(left, right + 1): # take the range from left to right
if divide(i) == True: # apply our divide function to each number, and append it to a list if true
templist.append(i)
return templist # return our results list | self-dividing-numbers | Fast & Easy python solution || faster than 83% || Create nested function | inusyd | 0 | 2 | self dividing numbers | 728 | 0.776 | Easy | 11,940 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2818813/Simple-and-Fast-Python-Solution | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
values = []
for i in range(left, right + 1):
number = str(i)
if '0' not in number:
value = True
j = 0
while value == True and j < len(number):
value = i % int(number[j]) == 0
j += 1
if value:
values += [i]
return values | self-dividing-numbers | Simple and Fast Python Solution | PranavBhatt | 0 | 2 | self dividing numbers | 728 | 0.776 | Easy | 11,941 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2783045/Python-solution-converting-the-number-to-string | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
list_dividing_num = []
for num in range(left, right + 1):
if "0" not in str(num):
count = 0
for n in str(num):
if num % int(n) == 0:
count += 1
if count == len(str(num)):
list_dividing_num.append(num)
return list_dividing_num | self-dividing-numbers | Python solution converting the number to string | samanehghafouri | 0 | 3 | self dividing numbers | 728 | 0.776 | Easy | 11,942 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2779482/Python3-easy-to-understand-66-ms-faster-than-83.85-of-Python3 | class Solution:
def selfDividingNumbers(self, left: int, right: int):
list = [] # list to append elements to it
for i in range(left, right+1): # loop over all numbers
if '0' in str(i): continue # check for numbers have zeros
count = 0 # used as a flag
for j in str(i): # iterate over each digit in the number
if i % int(j) == 0:
count += 1 # +1 if the reminder is 0
if count == len(str(i)): # check if the count is increment at all digits in the number
list.append(i)
return list | self-dividing-numbers | Python3 - easy to understand -66 ms, faster than 83.85% of Python3 | Muhammed_Shoeib | 0 | 4 | self dividing numbers | 728 | 0.776 | Easy | 11,943 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2757239/Python-Div-Mod-Solution | class Solution:
def selfDividingNumbers(self, L: int, R: int) -> List[int]:
out = []
for num in range(L,R+1):
temp = num
while temp %10 != 0 and num % (temp%10) == 0: temp //= 10
if temp==0: out.append(num)
return out | self-dividing-numbers | [Python] Div-Mod Solution✔ | keioon | 0 | 6 | self dividing numbers | 728 | 0.776 | Easy | 11,944 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2730242/Python-oror-Short-Solution-oror-98.5-Faster | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def find_divided(nums):
numlist = list(str(nums))
for idx in numlist:
if(int(idx)==0):return False
if(nums%int(idx)!=0): return False
return True
res=[]
for element in range(left,right+1):
if(find_divided(element)):
res.append(element)
return res | self-dividing-numbers | Python || Short Solution || 98.5% Faster | hasan2599 | 0 | 5 | self dividing numbers | 728 | 0.776 | Easy | 11,945 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2465800/Python-(Simple-and-Beginner-Friendly-Solution) | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
output = []
for i in range(left, right+1):
count = 0
lst = list(str(i))
if "0" not in lst:
for j in lst:
if (i % int(j) == 0):
count+=1
if count == len(lst):
output.append(i)
count = 0
return output | self-dividing-numbers | Python (Simple and Beginner-Friendly Solution) | vishvavariya | 0 | 48 | self dividing numbers | 728 | 0.776 | Easy | 11,946 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2252430/Easy-and-clean-python-solution-(no-string-conversion) | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def divide(n):
divisor = n
while divisor:
tmp = divisor%10
if not tmp or n%tmp:
return False
divisor //= 10
return True
return [n for n in range(left, right+1) if divide(n)] | self-dividing-numbers | Easy and clean python solution (no string conversion) | yhc22593 | 0 | 33 | self dividing numbers | 728 | 0.776 | Easy | 11,947 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2102710/python-or-easy-solution-or-100-working | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
l=[]
for i in range(left,right+1):
if '0' in str(i):
continue
elif i<10:
l.append(i)
elif check(i):
l.append(i)
return l
def check(i):
f=0
n=i
while(i!=0):
r=i%10
i=i//10
if n%r==0:
f=1
else:
f=0
break
if f==0:
return False
else:
return True | self-dividing-numbers | python | easy solution | 100% working | T1n1_B0x1 | 0 | 94 | self dividing numbers | 728 | 0.776 | Easy | 11,948 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2045768/Easy-Python-Solution | class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
y=[]
y=[]
for i in range(left,right+1):
x=list(str(i))
if len([j for j in x if "0" not in x and i%int(j)==0])==len(x):
y.append(i)
return y | self-dividing-numbers | Easy Python Solution | glimloop | 0 | 118 | self dividing numbers | 728 | 0.776 | Easy | 11,949 |
https://leetcode.com/problems/self-dividing-numbers/discuss/2031353/Python-solution | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
ans = []
for i in range(left, right+1):
if '0' in str(i):
continue
for j in str(i):
if i%int(j) == 0:
continue
else:
break
else:
ans += [i]
return ans | self-dividing-numbers | Python solution | StikS32 | 0 | 76 | self dividing numbers | 728 | 0.776 | Easy | 11,950 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1902223/Python-beginner-friendly-solution-with-memory-less-than-77 | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
res = []
flag = 0
for i in range(left, right+1):
dig = [int(x) for x in str(i)]
for j in dig:
if j == 0 or i % j != 0:
flag = 1
break
if flag == 0:
res.append(i)
flag = 0
return res | self-dividing-numbers | Python beginner friendly solution with memory less than 77% | alishak1999 | 0 | 56 | self dividing numbers | 728 | 0.776 | Easy | 11,951 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1881064/Simple-Python%3A-Faster-than-99.91-Of-Python3-Submissions | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
lst = []
def check(num):
temp = str(num)
if '0' in temp:
return False
for i in temp:
if num % int(i) != 0:
return False
return True
for i in range(left, right + 1):
if check(i) == True:
lst.append(i)
else:
pass
return lst | self-dividing-numbers | Simple Python: Faster than 99.91% Of Python3 Submissions | James-Kosinar | 0 | 41 | self dividing numbers | 728 | 0.776 | Easy | 11,952 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1839326/5-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-90 | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
ans=[]
for num in range(left,right+1):
if '0' in str(num): continue
if all([num%int(d)==0 for d in str(num)]): ans.append(num)
return ans | self-dividing-numbers | 5-Lines Python Solution || 50% Faster || Memory less than 90% | Taha-C | 0 | 74 | self dividing numbers | 728 | 0.776 | Easy | 11,953 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1839326/5-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-90 | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
return [x for x in range(left, right+1) if all(i and (x%i==0) for i in map(int,str(x)))] | self-dividing-numbers | 5-Lines Python Solution || 50% Faster || Memory less than 90% | Taha-C | 0 | 74 | self dividing numbers | 728 | 0.776 | Easy | 11,954 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1824902/Ez-to-Understand-oror-Neat-oror-Explained | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
c=[]
for i in range(left, right+1):
if i<10:
c.append(i)
continue
v=str(i)
l=len(v)
for ch in v:
ch=int(ch)
if ch!=0 and (i%ch)==0:
l-=1
continue
break
if l==0:
c.append(i)
return c | self-dividing-numbers | Ez to Understand || Neat || Explained | ashu_py22 | 0 | 23 | self dividing numbers | 728 | 0.776 | Easy | 11,955 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1737367/Python-with-methods | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
self_dividing = []
for num in range(left, right+1):
if self.isSelfDividing(num):
self_dividing.append(num)
return self_dividing
def isSelfDividing(self, number: int) -> int:
for s in str(number):
if int(s) == 0:
return False
if number % int(s) != 0:
return False
return True | self-dividing-numbers | Python with methods | CleverUzbek | 0 | 36 | self dividing numbers | 728 | 0.776 | Easy | 11,956 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1555867/Python-beats-99 | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
return [n for n in range(left, right + 1) if self.is_self_dividing(n)]
def is_self_dividing(self, n):
i = 1
while n >= i:
digit = n // i % 10
if digit != 0 and n % digit == 0:
i *= 10
else:
return False
return True | self-dividing-numbers | Python beats 99% | dereky4 | 0 | 85 | self dividing numbers | 728 | 0.776 | Easy | 11,957 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1546753/Python3-Simple-Solution | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
result = []
for num in range(left, right + 1):
divide = num
while divide % 10:
if num % (divide % 10):
break
divide //= 10
if divide == 0:
result += [num]
return result | self-dividing-numbers | [Python3] Simple Solution | JingMing_Chen | 0 | 98 | self dividing numbers | 728 | 0.776 | Easy | 11,958 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1434989/Runtime%3A-32-ms-faster-than-99.57-of-Python3-online-submissions | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
l=[]
for i in range(left,right+1):
a=i
flag=0
while(a):
c=a%10
if c==0 or i%c!=0:
flag=1
break
a//=10
if not flag:
l.append(i)
return l | self-dividing-numbers | Runtime: 32 ms, faster than 99.57% of Python3 online submissions | harshmalviya7 | 0 | 86 | self dividing numbers | 728 | 0.776 | Easy | 11,959 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1315566/Python3-dollarolution-(98-faster-and-80-better-memory-usage) | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
v, c = [], 0
for i in range(left,right+1):
f = i
while f > 0:
x = f % 10
if x != 0 and i % x == 0:
c = 1
f = f // 10
else:
c = 0
break
if c == 1:
v.append(i)
return v | self-dividing-numbers | Python3 $olution (98% faster and 80% better memory usage) | AakRay | 0 | 187 | self dividing numbers | 728 | 0.776 | Easy | 11,960 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1222963/Python-Easy-and-Simple-Solution | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
ans = []
for i in range(left,right+1):
flag = 1
if '0' not in str(i):
for digit in str(i):
if i%int(digit)!=0:
flag = 0
break
if flag==1: ans.append(i)
return ans | self-dividing-numbers | [Python] Easy and Simple Solution | arkumari2000 | 0 | 158 | self dividing numbers | 728 | 0.776 | Easy | 11,961 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1144660/Python-Simple-and-Easy-To-Understand-Solution-or-Beats-90 | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
ans = []
for k in range(left,right+1):
i=k
flag=0
while i>0:
r = i%10
if r!=0 and k%r == 0:
i=i//10
flag=1
else:
flag=0
break
if flag == 1:
ans.append(k)
return ans | self-dividing-numbers | Python Simple & Easy To Understand Solution | Beats 90% | saurabhkhurpe | 0 | 156 | self dividing numbers | 728 | 0.776 | Easy | 11,962 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1114084/No-String-python-solution | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
out = []
for i in range(left, right+1):
if i <= 9:
out.append(i)
elif i%10 == 0:
continue
elif self.is_self_dividing(i):
out.append(i)
return out
def is_self_dividing(self, x):
temp = x
while temp != 0:
if temp%10 == 0:
return False
if x%(temp%10) != 0:
return False
temp //= 10
return True | self-dividing-numbers | No String python solution | EH1 | 0 | 87 | self dividing numbers | 728 | 0.776 | Easy | 11,963 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1082059/easysimplefater-python-code | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
count=0
res=[]
for i in range(left,right+1):
if '0' in list(str(i)):
pass
else:
for j in range(len(list(str(i)))):
if i%int(list(str(i))[j])==0:
count +=1
if count==len(list(str(i))):
res.append(i)
count=0
elif count>0 and j==(len(list(str(i)))-1):
count=0
else:
count=0
return res | self-dividing-numbers | easy,simple,fater python code | yashwanthreddz | 0 | 82 | self dividing numbers | 728 | 0.776 | Easy | 11,964 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1028840/Python3-easy-to-understand-solution | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
l = []
for i in range(left,right+1):
if '0' in str(i):
continue
else:
flag = True
for j in str(i):
if i%int(j) != 0:
flag = False
break
if flag:
l.append(i)
return l | self-dividing-numbers | Python3 easy to understand solution | EklavyaJoshi | 0 | 49 | self dividing numbers | 728 | 0.776 | Easy | 11,965 |
https://leetcode.com/problems/self-dividing-numbers/discuss/1024594/or-Python-3-or-Easy-to-understand | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
result = []
for i in range(left, right+1):
if i > 0 and i < 10:
result.append(i)
elif i >= 10:
for j in str(i):
if int(j) == 0 or i % int(j) != 0:
break
else:
result.append(i)
return result | self-dividing-numbers | | Python 3 | Easy to understand | bruadarach | 0 | 64 | self dividing numbers | 728 | 0.776 | Easy | 11,966 |
https://leetcode.com/problems/self-dividing-numbers/discuss/778981/Easy-Python-Faster-than-90-Submits | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
out = []
for num in range(left, right+1):
if '0' not in str(num):
for i in str(num):
if num % int(i) != 0:
break
else:
out.append(num)
return out | self-dividing-numbers | Easy Python Faster than 90% Submits | Venezsia1573 | 0 | 42 | self dividing numbers | 728 | 0.776 | Easy | 11,967 |
https://leetcode.com/problems/self-dividing-numbers/discuss/332124/Python-3-Solution | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
L = []
for i in range(left,right+1):
d = list(str(i))
m = len(d)
if '0' in d:
continue
j = 0
while j < m and i%int(d[j]) == 0:
j += 1
if j == m:
L.append(i)
return(L)
- Python 3
- Junaid Mansuri | self-dividing-numbers | Python 3 Solution | junaidmansuri | 0 | 491 | self dividing numbers | 728 | 0.776 | Easy | 11,968 |
https://leetcode.com/problems/my-calendar-i/discuss/2731671/Fastest-Python-solution-greater-Create-a-Binary-Search-Tree | # Binary Search Tree Solution -> If exact matching of intervals found then return False
# Else you can add this interval to that particular node's left or right
class Node:
def __init__(self, s, e):
self.s = s
self.e = e
self.left = None
self.right = None
class MyCalendar:
def __init__(self):
self.head = None
def insert(self, s, e, node):
if s >= node.e:
if node.right: return self.insert(s, e, node.right)
else:
nn = Node(s, e)
node.right = nn
return True
elif e <= node.s:
if node.left: return self.insert(s, e, node.left)
else:
nn = Node(s, e)
node.left = nn
return True
else: return False
def book(self, s: int, e: int) -> bool:
if self.head == None:
nn = Node(s, e)
self.head = nn
return True
return self.insert(s, e, self.head) | my-calendar-i | Fastest Python solution -> Create a Binary Search Tree🥶 | shiv-codes | 0 | 17 | my calendar i | 729 | 0.572 | Medium | 11,969 |
https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/1612723/DP-Python | class Solution:
def countPalindromicSubsequences(self, s:str) -> int:
@cache
def fn(ch, i, j):
if i > j:
return 0
if i == j and s[i] == ch:
return 1
if s[i] == s[j] == ch:
return 2 + fn('a', i+1, j-1) + fn('b', i+1, j-1) + fn('c', i+1, j-1) + fn('d', i+1, j-1)
elif s[i] != ch:
return fn(ch, i+1, j)
elif s[j] != ch:
return fn(ch, i, j-1)
n = len(s)
return (fn('a', 0, n-1) + fn('b', 0, n-1) + fn('c', 0, n-1) + fn('d', 0, n-1)) % (10**9+7) | count-different-palindromic-subsequences | DP Python | yshawn | 2 | 469 | count different palindromic subsequences | 730 | 0.445 | Hard | 11,970 |
https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/299714/python3-O(N2)-solution | class Solution:
def countPalindromicSubsequences(self, S: str) -> int:
n = len(S)
pos = dict()
nexts = [n]*n
prev = [-1]*n
for i, c in enumerate(S):
if c in pos: prev[i] = pos[c]
pos[c] = i
pos = dict()
for j in range(n-1, -1, -1):
if S[j] in pos: nexts[j] = pos[S[j]]
pos[S[j]] = j
dp = [[0]*n for _ in range(n)]
for i in range(n):
dp[i][i] = 1
for D in range(1, n):
for i in range(n-D):
j = i + D
if S[i] != S[j]:
dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1]
else:
if nexts[i] > prev[j]: # a...a
dp[i][j] = dp[i+1][j-1] * 2 + 2
elif nexts[i] == prev[j]: # a..a...a
dp[i][j] = dp[i+1][j-1] * 2 + 1
else: # a...a....a....a
dp[i][j] = dp[i+1][j-1] * 2 - dp[nexts[i]+1][prev[j]-1]
return dp[0][n-1] % (10**9+7) | count-different-palindromic-subsequences | python3 O(N^2) solution | dengl11 | 1 | 519 | count different palindromic subsequences | 730 | 0.445 | Hard | 11,971 |
https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/2775629/Python3-O(N2)-DP-beat-95 | class Solution:
def countPalindromicSubsequences(self, s: str) -> int:
n, MOD = len(s), 10 ** 9 + 7
s = [ord(c) - ord('a') for c in s]
charcnt, first, last = [[0] * n for _ in range(n)], [-1] * 4, [-1] * 4
for i in range(n):
if first[s[i]] == -1: first[s[i]] = i
last[s[i]] = i
cs = set()
for j in range(i, n):
cs.add(s[j])
charcnt[i][j] = len(cs)
left, right = [[-1] * 4 for _ in range(n)], [[-1] * 4 for _ in range(n)]
for i in range(1, n):
left[i] = left[i - 1][:]
left[i][s[i - 1]] = i - 1
for i in range(n - 2, -1, -1):
right[i] = right[i + 1][:]
right[i][s[i + 1]] = i + 1
ans, dp = charcnt[0][n - 1], [[0] * n for _ in range(n)]
for l, r in zip(first, last): dp[l][r] = 1
for step in range(1, n):
for l in range(step):
r = l + n - step
if not dp[l][r]: continue
for nk in range(4):
nl, nr = right[l][nk], left[r][nk]
if nr < r and nl > l and nl < nr:
dp[nl][nr] = (dp[nl][nr] + dp[l][r]) % MOD
ans = (ans + dp[l][r] * (1 + charcnt[l + 1][r - 1])) % MOD
return ans | count-different-palindromic-subsequences | [Python3] O(N^2) DP beat 95% | cava | 0 | 32 | count different palindromic subsequences | 730 | 0.445 | Hard | 11,972 |
https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/1469588/Python3-dp | class Solution:
def countPalindromicSubsequences(self, s: str) -> int:
locs = defaultdict(list)
for i, ch in enumerate(s): locs[ch].append(i)
@cache
def fn(lo, hi):
"""Return count of palindromic subsequences in s[lo:hi]."""
if lo == hi: return 0
ans = 0
for ch in "abcd":
i = bisect_left(locs[ch], lo)
j = bisect_left(locs[ch], hi) - 1
if i <= j < len(locs[ch]) and lo <= locs[ch][i] <= locs[ch][j] < hi:
ans += 1
if i < j: ans += 1 + fn(locs[ch][i]+1, locs[ch][j])
return ans % 1_000_000_007
return fn(0, len(s)) | count-different-palindromic-subsequences | [Python3] dp | ye15 | 0 | 415 | count different palindromic subsequences | 730 | 0.445 | Hard | 11,973 |
https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/1807666/Python-easy-to-read-and-understand-or-DP | class Solution:
def countPalindromicSubsequences(self, s: str) -> int:
n = len(s)
t = [[0 for _ in range(n)] for _ in range(n)]
for g in range(n):
i = 0
for j in range(g, n):
if g == 0:
t[i][j] = 1
elif g == 1:
t[i][j] = 2
else:
if s[i] != s[j]:
t[i][j] = t[i][j-1] + t[i+1][j] - t[i+1][j-1]
else:
if s[i:j+1].count(s[i]) == 2:
t[i][j] = 2*t[i+1][j-1] + 2
elif s[i:j+1].count(s[i]) == 3:
t[i][j] = 2*t[i+1][j-1] + 1
else:
temp = s[i+1:j]
x = i + temp.index(s[i]) + 2
y = j - temp[::-1].index(s[i]) - 2
t[i][j] = 2*t[i+1][j-1] - t[x][y]
i = i+1
return t[0][n-1]% (10**9 + 7) | count-different-palindromic-subsequences | Python easy to read and understand | DP | sanial2001 | -2 | 581 | count different palindromic subsequences | 730 | 0.445 | Hard | 11,974 |
https://leetcode.com/problems/flood-fill/discuss/626424/PythonJSGoC%2B%2B-sol-by-DFS-w-Comment | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
h, w = len(image), len(image[0])
def dfs( r, c, src_color):
if r < 0 or c < 0 or r >= h or c >= w or image[r][c] == newColor or image[r][c] != src_color:
# Reject for invalid coordination, repeated traversal, or different color
return
# update color
image[r][c] = newColor
# DFS to 4-connected neighbors
dfs( r-1, c, src_color )
dfs( r+1, c, src_color )
dfs( r, c-1, src_color )
dfs( r, c+1, src_color )
# ---------------------------------------------------------------------------
dfs(sr, sc, src_color = image[sr][sc] )
return image | flood-fill | Python/JS/Go/C++ sol by DFS [w/ Comment] | brianchiang_tw | 17 | 4,300 | flood fill | 733 | 0.607 | Easy | 11,975 |
https://leetcode.com/problems/flood-fill/discuss/2707985/Python-Flood-Fill-Algorithm-or-98-Faster | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
start_color = image[sr][sc]
def flood_fill(x, y):
if x < 0 or x >= len(image): return
if y < 0 or y >= len(image[0]): return
if image[x][y] == color: return
if image[x][y] != start_color: return
image[x][y] = color
flood_fill(x-1, y)
flood_fill(x+1, y)
flood_fill(x, y+1)
flood_fill(x, y-1)
flood_fill(sr, sc)
return image | flood-fill | ✔️ Python Flood Fill Algorithm | 98% Faster 🔥 | pniraj657 | 16 | 1,200 | flood fill | 733 | 0.607 | Easy | 11,976 |
https://leetcode.com/problems/flood-fill/discuss/1772478/Python-3-(150ms)-or-Clean-DFS-Solution-or-Easy-to-Understand | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
rows = len(image)
cols = len(image[0])
a = image[sr][sc]
def dfs(r, c):
nonlocal rows, cols, newColor, image
if r < 0 or c < 0 or r>rows-1 or c>cols-1 or image[r][c]==newColor or image[r][c]!=a:
return
image[r][c] = newColor
dfs(r+1,c)
dfs(r-1,c)
dfs(r,c+1)
dfs(r,c-1)
dfs(sr, sc)
return image | flood-fill | Python 3 (150ms) | Clean DFS Solution | Easy to Understand | MrShobhit | 7 | 733 | flood fill | 733 | 0.607 | Easy | 11,977 |
https://leetcode.com/problems/flood-fill/discuss/2285314/Python-3-Beginner-friendly-DFS-solution-explained-step-by-step | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
r,c = len(image), len(image[0])
start_color = image[sr][sc] #Since we are replacing the value in the matrix, we MUST record our start color prior to any operation
def paint_dfs(i,j): #here we set up our dfs function
#for dfs function, I'd set up our boundaries first, so here comes boundaries for i and j
if 0 <= i < r and 0 <= j < c and image[i][j] == start_color: #image[i][j]==start_color here because of the contraint of problem
image[i][j] = color #paint new color
return paint_dfs(i+1,j) and paint_dfs(i-1,j) and paint_dfs(i,j+1) and paint_dfs(i,j-1) #conduct our painting in adjacent square
# [paint_dfs(i+x,j+y) for (x,y) in ((0,1),(1,0),(0,-1),(-1,0))] -----the alternative line of return, for your reference
return image #else case, we simply return image without any operation, so image remains image
if start_color != color: # we must exclude the case that start_color and color are the same, or it will turn out to be a infinite loop
image = paint_dfs(sr,sc) #call the dfs function to start the operation
return image # return image here because we change our color in image, without establishing any new matrix | flood-fill | [Python 3] Beginner friendly DFS solution, explained step by step | AustinHuang823 | 6 | 127 | flood fill | 733 | 0.607 | Easy | 11,978 |
https://leetcode.com/problems/flood-fill/discuss/1655758/Python-Simple-recursive-DFS-explained | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
row = len(image)
col = len(image[0])
startingColor = image[sr][sc]
visited = [[0 for x in range(col)] for y in range(row)]
def dfs(i, j):
# if the current node is not of the starting color
# or is not a valid cell, return, we don't have work here
if i < 0 or i > row - 1 or j < 0 or j > col - 1 or image[i][j] != startingColor:
return
# return if current node is visited
# mark it as visited otherwise
if visited[i][j]:
return
visited[i][j] = 1
# update the color on this node
image[i][j] = newColor
# recursively try all adjacent cells of the current node
return dfs(i-1, j) or dfs(i+1, j) or dfs(i, j-1) or dfs(i, j+1)
dfs(sr, sc)
return image | flood-fill | [Python] Simple recursive DFS explained | buccatini | 4 | 245 | flood fill | 733 | 0.607 | Easy | 11,979 |
https://leetcode.com/problems/flood-fill/discuss/480901/Python-DFS-and-BFS | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
neis = [[0,1],[1,0],[-1,0],[0,-1]]
m = len(image)
n = len(image[0])
def dfs(row,col,oldColor):
for nei in neis:
x = row+nei[0]
y = col+nei[1]
if x<m and x>=0 and y<n and y>=0 and image[x][y]==oldColor:
image[x][y]=newColor
dfs(x,y,oldColor)
if image[sr][sc]==newColor:
return image
else:
oldColor = image[sr][sc]
image[sr][sc]=newColor
dfs(sr,sc,oldColor)
return image | flood-fill | Python DFS and BFS | user8307e | 3 | 832 | flood fill | 733 | 0.607 | Easy | 11,980 |
https://leetcode.com/problems/flood-fill/discuss/480901/Python-DFS-and-BFS | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
neis = [[0,1],[1,0],[-1,0],[0,-1]]
m = len(image)
n = len(image[0])
def bfs(row,col,oldColor):
q = [[row,col]]
while q:
x_,y_ = q.pop(0)
for nei in neis:
x = x_+nei[0]
y = y_+nei[1]
if x<m and x>=0 and y<n and y>=0 and image[x][y]==oldColor:
image[x][y]=newColor
q.append([x,y])
if image[sr][sc]==newColor:
return image
else:
oldColor = image[sr][sc]
image[sr][sc]=newColor
bfs(sr,sc,oldColor)
return image | flood-fill | Python DFS and BFS | user8307e | 3 | 832 | flood fill | 733 | 0.607 | Easy | 11,981 |
https://leetcode.com/problems/flood-fill/discuss/2510508/Python-Elegant-and-Short-or-DFS-or-98.62-faster | class Solution:
"""
Time: O(n*m)
Memory: O(n*m)
"""
def floodFill(self, image: List[List[int]], row: int, col: int, new_color: int) -> List[List[int]]:
if image[row][col] != new_color:
self.populate_color(image, row, col, new_color, image[row][col])
return image
@classmethod
def populate_color(cls, image: List[List[int]], row: int, col: int, new_color: int, old_color: int):
if 0 <= row < len(image) and 0 <= col < len(image[0]) and image[row][col] == old_color:
image[row][col] = new_color
cls.populate_color(image, row - 1, col, new_color, old_color)
cls.populate_color(image, row + 1, col, new_color, old_color)
cls.populate_color(image, row, col - 1, new_color, old_color)
cls.populate_color(image, row, col + 1, new_color, old_color) | flood-fill | Python Elegant & Short | DFS | 98.62% faster | Kyrylo-Ktl | 2 | 152 | flood fill | 733 | 0.607 | Easy | 11,982 |
https://leetcode.com/problems/flood-fill/discuss/1920577/Python-BFS-simple | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
m, n = len(image), len(image[0])
origColor = image[sr][sc]
q = deque([[sr, sc]])
visited = set()
visited.add((sr, sc))
while q:
r, c = q.popleft()
image[r][c] = newColor
for dr, dc in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
row, col = r + dr, c + dc
if 0 <= row < m and 0 <= col < n and image[row][col] == origColor and (row, col) not in visited:
q.append([row, col])
visited.add((row, col))
return image | flood-fill | Python BFS simple | gulugulugulugulu | 2 | 134 | flood fill | 733 | 0.607 | Easy | 11,983 |
https://leetcode.com/problems/flood-fill/discuss/1424588/Python-3-oror-Recursion-oror-Self-Explanatory | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
visited=[]
def recurse(i,j,color):
if i<0 or j<0 or i>=len(image) or j>=len(image[0]) or [i,j] in visited:
return
if i==sr and j==sc:
pass
elif image[i][j]!=color:
return
visited.append([i,j])
image[i][j]=newColor
recurse(i-1,j,color)
recurse(i,j-1,color)
recurse(i+1,j,color)
recurse(i,j+1,color)
val=image[sr][sc]
image[sr][sc]=newColor
recurse(sr,sc,val)
return image | flood-fill | Python 3 || Recursion || Self-Explanatory | bug_buster | 2 | 267 | flood fill | 733 | 0.607 | Easy | 11,984 |
https://leetcode.com/problems/flood-fill/discuss/719022/Easy-to-Understand-or-Simple-or-DFS-or-Faster-or-Python-Solution | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
def rec(image, row, col, color):
if row < 0 or row >= len(image) or col < 0 or col >= len(image[0]):
return
elif image[row][col] != color: return
else:
directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]
image[row][col] = -1
for r, c in directions:
rec(image, row+r, col+c, color)
image[row][col] = newColor
return image
return rec(image, sr, sc, image[sr][sc]) | flood-fill | Easy to Understand | Simple | DFS | Faster | Python Solution | Mrmagician | 2 | 406 | flood fill | 733 | 0.607 | Easy | 11,985 |
https://leetcode.com/problems/flood-fill/discuss/2474359/Concise-readable-python-DFS-or-76ms-(beats-96) | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
n, m = len(image), len(image[0])
source = image[sr][sc]
directions = ((-1,0), (1,0), (0,-1), (0,1))
def dfs(x,y):
if not 0 <= x < n or not 0 <= y < m:
return
if image[x][y] != source or image[x][y] == color:
return
image[x][y] = color
for (dx, dy) in directions:
dfs(x + dx, y + dy)
dfs(sr,sc)
return image | flood-fill | Concise, readable python DFS | 76ms (beats 96%) | 06berrydan | 1 | 100 | flood fill | 733 | 0.607 | Easy | 11,986 |
https://leetcode.com/problems/flood-fill/discuss/2265783/Python3-BFS-solution-faster-than-96 | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
visited = {}
queue = [(sr,sc)]
rowLength, columnLength = len(image[0]), len(image)
while len(queue) != 0:
i,j = queue.pop(0)
visited[(i,j)] = True
if(i-1 >= 0 and image[i-1][j] == image[i][j] and (i-1,j) not in visited):
queue.append((i-1,j))
if(i+1 < columnLength and image[i+1][j] == image[i][j] and (i+1,j) not in visited):
queue.append((i+1,j))
if(j-1 >= 0 and image[i][j-1] == image[i][j] and (i,j-1) not in visited):
queue.append((i,j-1))
if(j+1 < rowLength and image[i][j+1] == image[i][j] and (i,j+1) not in visited):
queue.append((i,j+1))
image[i][j] = newColor
return image | flood-fill | 📌 Python3 BFS solution faster than 96% | Dark_wolf_jss | 1 | 51 | flood fill | 733 | 0.607 | Easy | 11,987 |
https://leetcode.com/problems/flood-fill/discuss/2171226/Flood-Fill | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
s = [(sr,sc)]
while s:
r,c = s.pop()
if image[r][c] != color:
if c-1 >= 0 and image[r][c] == image[r][c-1]:
s.append((r,c-1))
if r+1 < len(image) and image[r][c] == image[r+1][c]:
s.append((r+1,c))
if c+1 < len(image[0]) and image[r][c] == image[r][c+1]:
s.append((r,c+1))
if r-1 >= 0 and image[r][c] == image[r-1][c]:
s.append((r-1,c))
image[r][c] = color
return image
``` | flood-fill | Flood Fill | vaibhav0077 | 1 | 70 | flood fill | 733 | 0.607 | Easy | 11,988 |
https://leetcode.com/problems/flood-fill/discuss/1943915/Easy-to-understand-Python-with-comments-(faster-than-93) | class Solution:
def floodFill(self, image, sr, sc, newColor) -> List[List[int]]:
ROWS = len(image)
COLS = len(image[0])
v = []
base = image[sr][sc]
def dfs(r,c):
#base case
if(r>=ROWS or c>=COLS or r<0 or c<0 or ((r,c) in v) or image[r][c]!=base):
return
#mark that cell visited
v.append((r,c))
#function reaches here means that cell is of same colour as base and not visited
image[r][c] = newColor
#repeat for on all adjacent cells
dfs(r+1,c)
dfs(r,c+1)
dfs(r-1,c)
dfs(r,c-1)
dfs(sr,sc)
return image | flood-fill | Easy to understand Python with comments (faster than 93%) | shvmsnju | 1 | 126 | flood fill | 733 | 0.607 | Easy | 11,989 |
https://leetcode.com/problems/flood-fill/discuss/1818935/My-very-first-recursive-solution-in-python | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
def refill(row, col, val):
if row not in range(len(image)) or col not in range(len(image[0])): return
if image[row][col] == newColor or image[row][col] != val: return
image[row][col] = newColor
refill(row, col - 1, val)
refill(row, col + 1, val)
refill(row + 1, col, val)
refill(row - 1, col, val)
return
refill(sr, sc, image[sr][sc])
return image | flood-fill | My very first recursive solution in python | deVamshi | 1 | 51 | flood fill | 733 | 0.607 | Easy | 11,990 |
https://leetcode.com/problems/flood-fill/discuss/1801148/Python3-simple-BFS-easy-to-understand | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
# BFS using a deque
N, M = len(image), len(image[0])
adj = deque()
color = image[sr][sc]
adj.append((sr,sc)) # insert pixel position as a tuple of indices
if color == newColor:
return image
while adj: # keep expanding until no pixels are left to fill
x, y = adj.popleft()
if image[x][y] == color: # prevent duplicates
image[x][y] = newColor
for p in [(x-1, y), (x+1, y), (x,y-1),(x,y+1)]:
if 0 <= p[0] < N and 0 <= p[1] < M and image[p[0]][p[1]] == color:
# valid range and the color is the same
adj.append(p)
return image | flood-fill | Python3 simple BFS easy to understand | naubull2 | 1 | 71 | flood fill | 733 | 0.607 | Easy | 11,991 |
https://leetcode.com/problems/flood-fill/discuss/1705886/Python3-or-Faster-than-90.64-or-Code-for-better-branch-prediction | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
point_queue = [(sr, sc)]
source_val = image[sr][sc]
visited = {}
max_r, max_c = len(image) - 1, len(image[0]) - 1
while len(point_queue) > 0:
r, c = point_queue.pop(0)
if (r,c) in visited:
continue
if image[r][c] == source_val:
image[r][c] = newColor
if r > 0:
point_queue.append((r-1, c))
if r < max_r:
point_queue.append((r+1, c))
if c > 0:
point_queue.append((r, c-1))
if c < max_c:
point_queue.append((r, c+1))
visited[(r,c)] = None
return image | flood-fill | Python3 | Faster than 90.64% | Code for better branch prediction | tkdals9082 | 1 | 120 | flood fill | 733 | 0.607 | Easy | 11,992 |
https://leetcode.com/problems/flood-fill/discuss/1592945/Iterative-and-in-place-DFS-in-Python | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
if newColor == image[sr][sc]:
return image
init_color = image[sr][sc]
stack = [(sr, sc)]
dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
def valid_pixel(c):
cx, cy = c
m, n = len(image), len(image[0])
return 0 <= cx < m and 0 <= cy < n and image[cx][cy] == init_color
# main()
while stack:
i, j = stack.pop()
image[i][j] = newColor
stack += filter(valid_pixel, ((i + dx, j + dy) for dx, dy in dirs))
return image | flood-fill | Iterative and in-place DFS in Python | mousun224 | 1 | 100 | flood fill | 733 | 0.607 | Easy | 11,993 |
https://leetcode.com/problems/flood-fill/discuss/1115823/Python3-simple-solution-using-recursion | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
val = image[sr][sc]
def dfs(row, col):
if row < 0 or row >= len(image):
return
elif col < 0 or col >= len(image[0]):
return
elif image[row][col] != val:
return
elif image[row][col] == newColor:
return
image[row][col] = newColor
dfs(row - 1, col)
dfs(row + 1, col)
dfs(row, col + 1)
dfs(row, col - 1)
dfs(sr, sc)
return image | flood-fill | Python3 simple solution using recursion | EklavyaJoshi | 1 | 84 | flood fill | 733 | 0.607 | Easy | 11,994 |
https://leetcode.com/problems/flood-fill/discuss/626678/Python3-iterative-and-recursive-dfs | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
m, n = len(image), len(image[0])
oldColor = image[sr][sc]
if oldColor != newColor:
stack = [(sr, sc)]
while stack:
i, j = stack.pop()
image[i][j] = newColor
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and image[ii][jj] == oldColor:
stack.append((ii, jj))
return image | flood-fill | [Python3] iterative & recursive dfs | ye15 | 1 | 76 | flood fill | 733 | 0.607 | Easy | 11,995 |
https://leetcode.com/problems/flood-fill/discuss/626678/Python3-iterative-and-recursive-dfs | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
def fn(i, j):
if 0 <= i < len(image) and 0 <= j < len(image[0]) and image[i][j] == color:
image[i][j] = newColor
for ii, jj in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)):
fn(ii, jj)
color = image[sr][sc]
if color != newColor: fn(sr, sc)
return image | flood-fill | [Python3] iterative & recursive dfs | ye15 | 1 | 76 | flood fill | 733 | 0.607 | Easy | 11,996 |
https://leetcode.com/problems/flood-fill/discuss/2840761/recursive | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
def_color = image[sr][sc]
def flood_fill(x, y):
if x < 0 or x >= len(image): return
if y < 0 or y >= len(image[0]): return
if image[x][y] == color: return
if image[x][y] != def_color: return
image[x][y] = color
flood_fill(x-1, y)
flood_fill(x+1, y)
flood_fill(x, y+1)
flood_fill(x, y-1)
flood_fill(sr, sc)
return image | flood-fill | recursive | roger880327 | 0 | 2 | flood fill | 733 | 0.607 | Easy | 11,997 |
https://leetcode.com/problems/flood-fill/discuss/2828367/Python-4-directions-check-within-bounds-unvisited-target-color | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
R, C, target = len(image), len(image[0]), image[sr][sc]
visited = set()
def dfs(r, c):
# If out of bounds or already visited or current != target, then return
if r < 0 or r == R or c < 0 or c == C or (r, c) in visited or image[r][c] != target:
return
# Otherwise update target color to new color + add to visited
image[r][c] = color
visited.add((r, c))
# Continue search in all 4 directions this updated cell
dfs(r - 1, c) # up
dfs(r, c + 1) # right
dfs(r + 1, c) # down
dfs(r, c - 1) # left
dfs(sr, sc)
return image | flood-fill | [Python] 4 directions - check within bounds, unvisited, target color | graceiscoding | 0 | 8 | flood fill | 733 | 0.607 | Easy | 11,998 |
https://leetcode.com/problems/flood-fill/discuss/2811702/Flood-fill-or-Easy-python-solution | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
def dfs(image,sr,sc,color,rows,cols,source):
if sr < 0 or sr >= rows or sc < 0 or sc >= cols:
return
elif image[sr][sc] != source:
return
image[sr][sc] = color
dfs(image,sr+1,sc,color,rows,cols,source)
dfs(image,sr-1,sc,color,rows,cols,source)
dfs(image,sr,sc+1,color,rows,cols,source)
dfs(image,sr,sc-1,color,rows,cols,source)
if color == image[sr][sc]:
return image
rows = len(image)
cols = len(image[0])
source = image[sr][sc]
dfs(image,sr,sc,color,rows,cols,source)
return image | flood-fill | Flood fill | Easy python solution | nishanrahman1994 | 0 | 5 | flood fill | 733 | 0.607 | Easy | 11,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.