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/check-if-numbers-are-ascending-in-a-sentence/discuss/1534539/Python-O(n)-time-and-O(1)-space-easy-to-understand | class Solution:
def areNumbersAscending(self, s: str) -> bool:
n = len(s)
i = 0
maxint = float('-inf')
while i <= n-1:
if not s[i].isdigit():
i += 1
else: # is digit
j = i
while j <= n-1 and s[j].isdigit():
j += 1
m = int(s[i:j])
if m <= maxint:
return False
else:
maxint = m
i = j
return True | check-if-numbers-are-ascending-in-a-sentence | Python O(n) time and O(1) space, easy to understand | byuns9334 | 0 | 78 | check if numbers are ascending in a sentence | 2,042 | 0.661 | Easy | 28,400 |
https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/discuss/1532256/Intuitive-approach-by-using-filtermap | class Solution:
def areNumbersAscending(self, s: str) -> bool:
numbers = map(lambda t: int(t), filter(lambda t: t.isnumeric(), s.split()))
n = -1
for next_n in numbers:
if n < 0 or next_n > n:
n = next_n
else:
return False
return True | check-if-numbers-are-ascending-in-a-sentence | Intuitive approach by using filter/map | puremonkey2001 | 0 | 19 | check if numbers are ascending in a sentence | 2,042 | 0.661 | Easy | 28,401 |
https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/discuss/1526599/Python-faster-than-100.00 | class Solution:
def areNumbersAscending(self, s: str) -> bool:
last, cur, flag = -1, 0, False
for c in s:
if c.isdigit():
cur = cur * 10 + int(c)
flag = True
elif flag:
if last >= cur:
return False
last = cur
cur = 0
flag = False
return not flag or cur > last | check-if-numbers-are-ascending-in-a-sentence | Python faster than 100.00% | dereky4 | 0 | 35 | check if numbers are ascending in a sentence | 2,042 | 0.661 | Easy | 28,402 |
https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/discuss/1525620/Fastest-Python-Solutions-or-Faster-than-100-or-2-Approaches-(28-ms-28-ms) | class Solution:
def areNumbersAscending(self, s: str) -> bool:
tmp = []
s = s.split()
for ch in s:
if ch.isdigit():
if tmp:
a = tmp[-1]
if int(ch) > a:
tmp.append(int(ch))
else:
return False
else:
tmp.append(int(ch))
return True | check-if-numbers-are-ascending-in-a-sentence | Fastest Python Solutions | Faster than 100% | 2 Approaches (28 ms, 28 ms) | the_sky_high | 0 | 63 | check if numbers are ascending in a sentence | 2,042 | 0.661 | Easy | 28,403 |
https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/discuss/1525620/Fastest-Python-Solutions-or-Faster-than-100-or-2-Approaches-(28-ms-28-ms) | class Solution:
def areNumbersAscending(self, s: str) -> bool:
tmp = -1
s = s.split()
for ch in s:
if ch.isdigit():
if int(ch) > tmp:
tmp = int(ch)
else:
return False
return True | check-if-numbers-are-ascending-in-a-sentence | Fastest Python Solutions | Faster than 100% | 2 Approaches (28 ms, 28 ms) | the_sky_high | 0 | 63 | check if numbers are ascending in a sentence | 2,042 | 0.661 | Easy | 28,404 |
https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/discuss/1525198/Python-simple-solution | class Solution:
def areNumbersAscending(self, s: str) -> bool:
s = s.split(' ')
last = float('-inf')
for char in s:
if char.isnumeric():
if int(char) <= last:
return False
else:
last = int(char)
return True | check-if-numbers-are-ascending-in-a-sentence | Python simple solution | abkc1221 | 0 | 43 | check if numbers are ascending in a sentence | 2,042 | 0.661 | Easy | 28,405 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1525225/Python3-top-down-dp | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
target = reduce(or_, nums)
@cache
def fn(i, mask):
"""Return number of subsets to get target."""
if mask == target: return 2**(len(nums)-i)
if i == len(nums): return 0
return fn(i+1, mask | nums[i]) + fn(i+1, mask)
return fn(0, 0) | count-number-of-maximum-bitwise-or-subsets | [Python3] top-down dp | ye15 | 8 | 729 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,406 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1575826/Python3-Solution | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
def dfs(i,val):
if maxBit == val : return 1<<(len(nums)-i)
if i == len(nums): return 0
return dfs(i+1,val|nums[i]) + dfs(i+1,val)
maxBit = 0
for i in nums: maxBit |= i
return dfs(0,0) | count-number-of-maximum-bitwise-or-subsets | Python3 Solution | satyam2001 | 2 | 244 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,407 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1525686/Python3-bitmask-or-dp | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
N = len(nums)
dp = [-1] * (1<<N)
dp[0] = 0
for mask in range(1<<N):
for j in range(N):
if mask & (1<<j):
neib = dp[mask ^ (1<<j)]
dp[mask] = neib|nums[j]
return dp.count(max(dp)) | count-number-of-maximum-bitwise-or-subsets | Python3 - bitmask | dp | zhuzhengyuan824 | 2 | 111 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,408 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1525455/Python3-Beats-100-Solution-or-Easy-to-understand | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
ans = {}
subSet = [[]]
max_or = 0
for i in range(len(nums)):
for j in range(len(subSet)):
new = [nums[i]] + subSet[j]
# print(new)
x = new[0]
for k in range(1, len(new)):
x |= new[k]
x = max(max_or, x)
if x in ans:
ans[x] += 1
else:
ans[x] = 1
subSet.append(new)
return ans[x] | count-number-of-maximum-bitwise-or-subsets | [Python3] Beats 100% Solution | Easy to understand | leefycode | 1 | 121 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,409 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/2660561/Python3-or-Bitmask | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
hmap=defaultdict(int)
l=len(nums)
for i in range(2**l):
subset=0
for j in range(l):
if i&(1<<j):
subset|=nums[j]
hmap[subset]+=1
return hmap[max(hmap)] | count-number-of-maximum-bitwise-or-subsets | [Python3] | Bitmask | swapnilsingh421 | 0 | 7 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,410 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/2446761/Python3-or-Solved-using-Recursion-%2B-Backtracking | class Solution:
#Let n = len(nums) array!
#Time-Complexity: O(n * 2^n), since we make 2^n rec. calls to generate
#all 2^n different subsets and for each rec. call, we call helper function that
#computes Bitwise Or Lienarly!
#Space-Complexity: O(n), since max stack depth is n!
def countMaxOrSubsets(self, nums: List[int]) -> int:
#helper function!
def calculate_BWOR(arr):
if(len(arr) == 1):
return arr[0]
else:
n = len(arr)
res = arr[0]
for i in range(1, n):
#take the bitwise or operation on two integers: ans and i!
res = res | arr[i]
return res
#Approach: Utilize backtracking to generate all possible subsets!
#Even if two sets contain same elements, it can be considered different
#if we choose elements of differing indices!
#I can keep track in answer all of the subset(s) that posseses the maximum
#bitwise or!
#At the end, I simply have to return number of subsets in answer!
ans = []
n = len(nums)
#since the range of integers in input array nums is at least 1,
#I will initialize maximum bitwise or value to 1!
maximum = 1
#parameters: i -> index that we are considering from
#cur -> array of elements in current subset we built up so far!
def helper(i, cur):
nonlocal nums, ans, maximum, n
#base case -> if index i == n and current subset is not None, we know we made #decision to include or not include for each and every of the n elements!
if(i == n):
if(not cur):
return
#once we hit base case, get the bitwise or of cur and compare
#against max!
#1. If it matches max, add it to ans!
#2. If it beats current max, update maximum and update ans to
#have only cur element!
#3. Otherwise, ignore!
current = calculate_BWOR(cur)
if(current > maximum):
maximum = current
#make sure to add deep copy!
ans = [cur[::]]
return
elif(current == maximum):
#make sure to add deep copy! Contents of cur might change
#as we return to parent rec. call from current call to helper!
ans.append(cur[::])
return
else:
return
#if it's not the base case, we have to make 2 rec. calls!
cur.append(nums[i])
helper(i+1, cur)
#once the prev. rec.call finishes, we generated all subsets that
#does contain nums[i]!
cur.pop()
#this rec. call generates all subsets that do not contain nums[i]
helper(i+1, cur)
helper(0, [])
return len(ans) | count-number-of-maximum-bitwise-or-subsets | Python3 | Solved using Recursion + Backtracking | JOON1234 | 0 | 23 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,411 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1552499/WEEB-DOES-PYTHON-BFS | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
queue = deque([])
for i in range(len(nums)):
queue.append((nums[i], [nums[i]], i))
return self.bfs(queue, nums)
def bfs(self, queue, nums):
maxBit = 0
result = 0
while queue:
curBit, curPath, idx = queue.popleft()
if curBit > maxBit:
maxBit = curBit
result = 1
elif curBit == maxBit:
result += 1
for i in range(idx+1, len(nums)):
queue.append((curBit | nums[i], curPath + [nums[i]], i))
return result | count-number-of-maximum-bitwise-or-subsets | WEEB DOES PYTHON BFS | Skywalker5423 | 0 | 74 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,412 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1525273/Python-DP-solution | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
n = len(nums)
maxOR = 0
for num in nums:
maxOR = max(maxOR, maxOR | num)
dp = [[0]*(maxOR+1) for _ in range(n+1)]
v = [[0]*(maxOR+1) for _ in range(n+1)]
def findCnt(i, curr, m):
if i == n:
return curr == m
if v[i][curr]:
return dp[i][curr]
v[i][curr] = 1
dp[i][curr] = findCnt(i + 1, curr, m) + findCnt(i + 1, (curr | nums[i]), m)
return dp[i][curr]
return int(findCnt(0, 0, maxOR)) | count-number-of-maximum-bitwise-or-subsets | Python DP solution | abkc1221 | 0 | 70 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,413 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1525191/Easy-to-understand-oror-Map-oror-Knapsack | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
maor = 0
for n in nums:
maor = max(maor, maor|n)
nums.sort(reverse = True)
dp = dict()
def count(ind,local):
if local==maor:
return 2**(len(nums)-ind)
if ind==len(nums):
return 0
if (ind,local) in dp:
return dp[(ind,local)]
dp[(ind,local)] = count(ind+1,local|nums[ind]) + count(ind+1,local)
return dp[(ind,local)]
return count(0,0) | count-number-of-maximum-bitwise-or-subsets | ππ Easy-to-understand || Map || Knapsack π | abhi9Rai | 0 | 77 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,414 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1525153/Python-code-with-comments-!-(Breaking-into-functions) | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
sub = []
#function to find all the possible subarrays
def helper(arr, index, subarr):
if index == len(arr):
if len(subarr) != 0:
sub.append(subarr)
else:
helper(arr, index + 1, subarr)
helper(arr, index + 1,subarr+[arr[index]])
return
#function to check if the OR of a array is equal to a given value
def checker(arr,maxOR):
OR = arr[0]
for i in range(1, len(arr)):
OR = OR|arr[i]
return OR == maxOR
helper(nums,0,[])
#calculating maximum possible OR of an array
maxOR = nums[0]
for i in range(1, len(nums)):
maxOR = maxOR|nums[i]
#traverse the list "sub" generated by calling "helper" and checking if the value is equal to maxOR
count = 0
for arr in sub :
if checker(arr,maxOR) :
count+=1
return count | count-number-of-maximum-bitwise-or-subsets | Python code with comments ! (Breaking into functions) | abhijeetgupto | 0 | 75 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,415 |
https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1527945/Using-Combinations-100-speed | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
len_nums = len(nums)
max_val = 0
count_max = 0
for len_c in range(1, len_nums + 1):
for comb in combinations(nums, len_c):
val = 0
for n in comb:
val |= n
if val > max_val:
count_max = 1
max_val = val
elif val == max_val:
count_max += 1
return count_max | count-number-of-maximum-bitwise-or-subsets | Using Combinations, 100% speed | EvgenySH | -1 | 82 | count number of maximum bitwise or subsets | 2,044 | 0.748 | Medium | 28,416 |
https://leetcode.com/problems/second-minimum-time-to-reach-destination/discuss/1525227/Python3-Dijkstra-and-BFS | class Solution:
def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u-1].append(v-1)
graph[v-1].append(u-1)
pq = [(0, 0)]
seen = [[] for _ in range(n)]
least = None
while pq:
t, u = heappop(pq)
if u == n-1:
if least is None: least = t
elif least < t: return t
if (t//change) & 1: t = (t//change+1)*change # waiting for green
t += time
for v in graph[u]:
if not seen[v] or len(seen[v]) == 1 and seen[v][0] != t:
seen[v].append(t)
heappush(pq, (t, v)) | second-minimum-time-to-reach-destination | [Python3] Dijkstra & BFS | ye15 | 6 | 462 | second minimum time to reach destination | 2,045 | 0.389 | Hard | 28,417 |
https://leetcode.com/problems/second-minimum-time-to-reach-destination/discuss/1525227/Python3-Dijkstra-and-BFS | class Solution:
def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u-1].append(v-1)
graph[v-1].append(u-1)
least = None
queue = deque([(0, 0)])
seen = [[] for _ in range(n)]
while queue:
t, u = queue.popleft()
if u == n-1:
if least is None: least = t
elif least < t: return t
if (t//change) & 1: t = (t//change+1)*change # waiting for green
t += time
for v in graph[u]:
if not seen[v] or len(seen[v]) == 1 and seen[v][0] != t:
seen[v].append(t)
queue.append((t, v)) | second-minimum-time-to-reach-destination | [Python3] Dijkstra & BFS | ye15 | 6 | 462 | second minimum time to reach destination | 2,045 | 0.389 | Hard | 28,418 |
https://leetcode.com/problems/second-minimum-time-to-reach-destination/discuss/1526306/Python-3-BFS-keep-last-two-minimum-step-counts | class Solution:
def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
g = defaultdict(set)
for u, v in edges:
g[u].add(v)
g[v].add(u)
q = deque([(1, 0)])
# to store the two minimum node counts for each visited node
vis = defaultdict(set, {0: {0}})
minval = set()
while q:
node, cnt = q.popleft()
if node == n:
minval.add(cnt)
if len(minval) == 2: break
for nei in g[node]:
if len(vis[nei]) > 1 and cnt + 1 >= max(vis[nei]): continue
vis[nei] = {min(vis[nei])} | {cnt + 1} if vis[nei] else {cnt + 1}
q.append((nei, cnt + 1))
minval = sorted(minval)
def helper(nodes):
t = 0
while nodes > 0:
t += time
nodes -= 1
if nodes == 0: break
# if current time exceeds change and change frequency is odd
if t >= change and (t // change) % 2:
t = (t // change + 1) * change
return t
if len(minval) == 1:
return helper(minval[0] + 2)
# either use the 2nd minimum path or the 1st path add two more nodes (like example 2)
return min(helper(minval[0]+2), helper(minval[1])) | second-minimum-time-to-reach-destination | [Python 3] BFS keep last two minimum step counts | chestnut890123 | 0 | 89 | second minimum time to reach destination | 2,045 | 0.389 | Hard | 28,419 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1537625/Python3-check-words | class Solution:
def countValidWords(self, sentence: str) -> int:
def fn(word):
"""Return true if word is valid."""
seen = False
for i, ch in enumerate(word):
if ch.isdigit() or ch in "!.," and i != len(word)-1: return False
elif ch == '-':
if seen or i == 0 or i == len(word)-1 or not word[i+1].isalpha(): return False
seen = True
return True
return sum(fn(word) for word in sentence.split()) | number-of-valid-words-in-a-sentence | [Python3] check words | ye15 | 20 | 1,200 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,420 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1537625/Python3-check-words | class Solution:
def countValidWords(self, sentence: str) -> int:
pattern = re.compile(r'(^[a-z]+(-[a-z]+)?)?[,.!]?$')
return sum(bool(pattern.match(word)) for word in sentence.split()) | number-of-valid-words-in-a-sentence | [Python3] check words | ye15 | 20 | 1,200 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,421 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/2213181/PYTHON-oror-EXPLAINED-oror-CORNER-CASE | class Solution:
def countValidWords(self, sentence: str) -> int:
a = list(sentence.split())
res=0
punc = ['!','.',',']
for s in a:
if s!="":
num=0
for i in range(0,10):
num+=s.count(str(i))
if num==0:
k=s.count('-')
if k==0 or (k==1 and s.index('-')!=0 and s.index('-')!=len(s)-1):
num=0
for i in punc:
num+=s.count(i)
if num==0 or (num==1 and s[-1] in punc and (len(s)==1 or s[-2]!='-')):
res+=1
return res | number-of-valid-words-in-a-sentence | βοΈ PYTHON || EXPLAINED || ;] CORNER CASE | karan_8082 | 5 | 150 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,422 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1538539/Fastest-Python-Solution-or-100-35ms | class Solution:
def countValidWords(self, sentence: str) -> int:
sen = sentence.split()
r, m = 0, 0
_digits = re.compile('\d')
def increment(s):
a, b, c = 0, 0, 0
a = s.count('!')
b = s.count(',')
c = s.count('.')
if (a+b+c) == 0:
return 1
elif (a+b+c) == 1:
if s[-1] in ['!',',','.']:
return 1
return 0
for s in sen:
if not bool(_digits.search(s)):
m = s.count('-')
if m == 1:
a = s.index('-')
if a != 0 and a != len(s)-1 and s[a+1].isalpha():
r += increment(s)
elif m == 0:
r += increment(s)
return r | number-of-valid-words-in-a-sentence | Fastest Python Solution | 100%, 35ms | the_sky_high | 4 | 537 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,423 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/2398230/Python-or-REGEX-pattern-matching-Explained-or-Faster-than-98.86 | class Solution:
def countValidWords(self, sentence: str) -> int:
pattern = re.compile(r'(^[a-z]+(-[a-z]+)?)?[,.!]?$')
count = 0
for token in sentence.split():
if pattern.match(token):
count += 1
return count | number-of-valid-words-in-a-sentence | Python | REGEX pattern matching Explained | Faster than 98.86% | ahmadheshamzaki | 2 | 101 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,424 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1591338/Linear-check-in-each-word-91-speed | class Solution:
punctuation = {"!", ".", ","}
digits = set("0123456789")
def countValidWords(self, sentence: str) -> int:
count = 0
for w in sentence.split():
if w[0] == "-" or w[0] in Solution.punctuation and len(w) > 1:
continue
valid = True
hyphens = 0
for i, c in enumerate(w):
if c in Solution.digits:
valid = False
break
if c == "-":
if hyphens == 0 and 0 < i < len(w) - 1 and w[i + 1].isalpha():
hyphens += 1
else:
valid = False
break
if c in Solution.punctuation and i != len(w) - 1:
valid = False
break
if valid:
count += 1
return count | number-of-valid-words-in-a-sentence | Linear check in each word, 91% speed | EvgenySH | 1 | 264 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,425 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/2840380/Only-1-iteration-solution-in-Python3 | class Solution:
def countValidWords(self, sentence: str) -> int:
l1 = sentence.split(" ")
result = len([k for k in l1
if k != "" and k.count("0") + k.count("1") + k.count("2") + k.count("3") + k.count("4") + k.count("5") + k.count("6") + k.count("7") + k.count("8") + k.count("9") == 0
and k.startswith("-") == False and k.endswith("-") == False
and k[:len(k)-1].count("!") == 0 and k[:len(k)-1].count(".") == 0 and k[:len(k)-1].count(",") == 0
and (k.count("-") == 0 or (k.count("-") == 1 and k[k.index("-")-1] not in (",", "!", ".") and k[k.index("-")+1] not in (",", "!", ".")) )
and k.count("!") in (1,0) and k.count(".") in (1,0) and k.count(",") in (1,0)
])
return result | number-of-valid-words-in-a-sentence | Only 1 iteration solution in Python3 | DNST | 0 | 1 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,426 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/2597521/python3-or-explanation-in-comments | class Solution:
punctuations = set(["!", ".", ","])
def countValidWords(self, sentence: str) -> int:
def is_valid(word):
length = len(word)
hyphen_count = 0
for i in range(length):
# case: punctuation
if word[i] in Solution.punctuations:
if i != length - 1: return 0
# case: hyphen
elif word[i] == "-" and not hyphen_count:
if i in set([0, length - 1]):
return 0
orders = [ord(word[i + idx]) for idx in [-1, 1]]
if any(order < 97 or order > 122 for order in orders):
return 0
hyphen_count += 1
# case: valid char
elif not (97 <= ord(word[i]) <= 122):
return 0
return 1
res = sum([is_valid(w) for w in sentence.split(" ") if w != ""])
return res | number-of-valid-words-in-a-sentence | python3 | explanation in comments | sproq | 0 | 34 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,427 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1916228/Python3-or-using-dict-simple | class Solution:
def countValidWords(self, sentence: str) -> int:
hold=sentence.split()
res=0
for i in range(len(hold)):
w=hold[i]
w_stat=self.find(w)
if w_stat['dig'] or len(w_stat['hyp'])>1 or len(w_stat['puc'])>1:
continue
if w_stat['hyp']:
idx=w_stat['hyp'][0]
if idx-1 not in w_stat['alp'] or idx+1 not in w_stat['alp']:
continue
if w_stat['puc']:
idx=w_stat['puc'][0]
if idx!=len(w)-1:
continue
res+=1
return res
def find(self,w):
stat={'alp':[], 'dig':[], 'hyp':[],'puc':[]}
for i,c in enumerate(w):
if c.isdigit():
stat['dig'].append(i)
elif c.isalpha():
stat['alp'].append(i)
elif c in ['!','.',',']:
stat['puc'].append(i)
else:
stat['hyp'].append(i)
return stat | number-of-valid-words-in-a-sentence | Python3 | using dict, simple | ginaaunchat | 0 | 162 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,428 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1886617/Python-dollarolution-(85-faster-and-99-better-mem-use) | class Solution:
def countValidWords(self, sentence: str) -> int:
sentence, f, count = sentence.split(), True, 0
for i in sentence:
for j in range(len(i)):
if i[j] == '-':
if i.count('-') > 1:
f = False
break
elif j == 0 or j == len(i)-1:
f = False
break
elif not i[j-1].isalpha() or not i[j+1].isalpha():
f = False
break
elif i[j].isnumeric():
f = False
break
elif i[j] in '!.,':
if j != len(i)-1:
f = False
break
if f:
count += 1
f = True
return count | number-of-valid-words-in-a-sentence | Python $olution (85% faster and 99% better mem use) | AakRay | 0 | 211 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,429 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1666309/Too-many-conditions-to-check | class Solution:
def countValidWords(self, sentence: str) -> int:
sen=sentence.split()
# print(sen)
count=0
for i in sen:
for j in range(len(i)):
if i[j].isdigit():
break
if (i[j] in ('!', ',','.') and j!=len(i)-1) or (i[j]=='-' and j==len(i)-1) or (i[j-1]=='-' and i[j] in ('!',',','.')) or i.count('-')>1 or (j==0 and i[j]=='-'):
break
if j==len(i)-1:
count+=1
# print(i,count)
return count | number-of-valid-words-in-a-sentence | Too many conditions to check | Naresh_danthala | 0 | 140 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,430 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1645492/Succinct-Python-solution-(not-that-fast) | class Solution:
def countValidWords(self, sentence: str) -> int:
pattern = re.compile(r'^([a-z\-]+[a-z].?|[a-z]*.?)$')
def match(s):
if any(v.isnumeric() for v in s):
return False
if s.count('-') > 1:
return False
if s.startswith('-') or s.endswith('-'):
return False
if sum(s.count(p) for p in ('!', '.', ',')) > 1:
return False
return re.match(pattern, s) is not None
return sum(map(match, sentence.split())) | number-of-valid-words-in-a-sentence | Succinct Python solution (not that fast) | emwalker | 0 | 97 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,431 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1548035/python-easy-solution | class Solution:
def countValidWords(self, sentence: str) -> int:
ans = 0
split = sentence.split(" ")
def is_lower(c):
if ord('a')<=ord(c)<= ord('z'):
return True
return False
def valid(w):
count = 0
for i, c in enumerate(w):
if c.isdigit():
return False
if c == '-':
if i == 0 or i == len(w)-1:
return False
if not is_lower(w[i-1]) or not is_lower(w[i+1]):
return False
if count != 0:
return False
count += 1
if c in '!.,' and not i == len(w)-1:
return False
return True
for w in split:
if w and valid(w):
ans += 1
return ans | number-of-valid-words-in-a-sentence | [python] easy solution | nightybear | 0 | 353 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,432 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1537950/Python3-One-line-code-or-Beats-100-Solution-or-Regex | class Solution:
def countValidWords(self, sentence: str) -> int:
return len(list(filter(lambda x: re.match('^[a-z]*([a-z]-[a-z])?[a-z]*[!\.,]?$', x), sentence.split()))) | number-of-valid-words-in-a-sentence | [Python3] One-line code | Beats 100% Solution | Regex | leefycode | 0 | 124 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,433 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1537885/Python-simple-solution | class Solution:
# function to check if word satisfies given condition
def isValid(self, word: str) -> bool:
num = '0123456789'
punct = '.,!'
lower = string.ascii_lowercase
hyphen_count = punct_count = 0
for i in range(len(word)):
ch = word[i]
if ch in num or (ch in punct and i != len(word)-1) or hyphen_count > 1 or punct_count > 1:
return False
elif ch == '-':
hyphen_count += 1
if (ch in (word[0], word[-1]) or word[i-1] not in lower or word[i+1] not in lower):
return False
elif ch in punct: punct_count += 1
return True
def countValidWords(self, sentence: str) -> int:
arr = sentence.split(' ')
count = 0
for word in arr:
if word != '' and self.isValid(word):
count += 1
return count | number-of-valid-words-in-a-sentence | Python simple solution | abkc1221 | 0 | 129 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,434 |
https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1538550/Python | class Solution:
def countValidWords(self, sentence: str) -> int:
valid = 0
digits = set(string.digits)
punctuation = set(['!', '.', ','])
for token in sentence.split():
ts = set(token)
if digits & ts:
continue
if p := punctuation & set(ts):
if len(p) > 1 or token[-1] not in punctuation:
continue
if max(token.count(c) for c in punctuation) > 1:
continue
if token.count('-') > 1:
continue
if token.count('-') == 1:
idx = token.find('-')
if idx == 0 or idx == len(token) - 1 or not token[idx-1].islower() or not token[idx+1].islower():
continue
valid += 1
return valid | number-of-valid-words-in-a-sentence | Python | blue_sky5 | -1 | 94 | number of valid words in a sentence | 2,047 | 0.295 | Easy | 28,435 |
https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/1537537/Python3-brute-force | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
while True:
n += 1
nn = n
freq = defaultdict(int)
while nn:
nn, d = divmod(nn, 10)
freq[d] += 1
if all(k == v for k, v in freq.items()): return n | next-greater-numerically-balanced-number | [Python3] brute-force | ye15 | 3 | 151 | next greater numerically balanced number | 2,048 | 0.471 | Medium | 28,436 |
https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/1537537/Python3-brute-force | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
def fn(i, x):
if i == k:
if all(d == v for d, v in freq.items() if v): yield x
else:
for d in range(1, k+1):
if freq[d] < d <= freq[d] + k - i:
freq[d] += 1
yield from fn(i+1, 10*x+d)
freq[d] -= 1
for k in (len(str(n)), len(str(n))+1):
freq = Counter()
for val in fn(0, 0):
if val > n: return val | next-greater-numerically-balanced-number | [Python3] brute-force | ye15 | 3 | 151 | next greater numerically balanced number | 2,048 | 0.471 | Medium | 28,437 |
https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/1538579/Python-3-All-combinations-(46ms) | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
n_digits = len(str(n))
next_max = {
1: [1],
2: [22],
3: [122, 333],
4: [1333, 4444],
5: [14444, 22333, 55555],
6: [122333, 224444, 666666, 155555],
7: [1224444, 2255555, 3334444, 1666666, 7777777]
}
if n >= int(str(n_digits) * n_digits):
n_digits += 1
return min(next_max[n_digits])
ans = float('inf')
for num in sorted(next_max[n_digits]):
cands = set(permutations(str(num)))
cands = sorted(map(lambda x: int("".join(x)), cands))
loc = bisect.bisect(cands, n)
if loc < len(cands):
ans = min(ans, cands[loc])
return ans | next-greater-numerically-balanced-number | [Python 3] All combinations (46ms) | chestnut890123 | 2 | 154 | next greater numerically balanced number | 2,048 | 0.471 | Medium | 28,438 |
https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/2703554/Python-Using-permutations-(very-simple-solution)-greater96-Faster | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
from itertools import permutations
mylist = [1, 22, 122, 333, 1333, 4444, 14444, 22333, 55555, 122333, 155555, 224444, 666666,1224444]
res=[]
def digit_combination(a,length):
a = list(str(a))
comb = permutations(a, length)
for each in comb:
s = [str(i) for i in each]
result = int("".join(s))
res.append(result)
for every in mylist:
digit_combination(every,len(str(every)))
res.sort()
print(res)
for idx in res:
if(idx>n):
return idx | next-greater-numerically-balanced-number | Python Using permutations (very simple solution)-->96% Faster | hasan2599 | 1 | 17 | next greater numerically balanced number | 2,048 | 0.471 | Medium | 28,439 |
https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/1537567/Python-3-or-Bitmask-Clean-or-Explanation | class Solution:
def __init__(self):
base = ['1', '22', '333', '4444', '55555', '666666']
nums = set()
for comb in itertools.product([0,1], repeat=6): # 64 combinations
cur = ''
for i, val in enumerate(comb):
cur += base[i] if val else ''
if len(cur) > 7: # max `n` is 10^6, which is 7 digits
continue
if cur: # permute all valid combinations
nums |= set(itertools.permutations(cur, len(cur))) # about 10^4
nums = sorted([int(''.join(num)) for num in nums|set(base)]) # convert tuple to integer and sort
self.nums = nums
def nextBeautifulNumber(self, n: int) -> int:
idx = bisect.bisect_right(self.nums, n) # binary search
return self.nums[idx] # return answer | next-greater-numerically-balanced-number | Python 3 | Bitmask, Clean | Explanation | idontknoooo | 1 | 179 | next greater numerically balanced number | 2,048 | 0.471 | Medium | 28,440 |
https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/2841279/python-solution-using-normal-for-loop | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
if(n==0):return 1
for x in range(n+1,1000000000):
l=[]
count=0
for y in str(x):
l.append(int(y))
l1=set(l)
for z in l1:
a=l.count(z)
if(a==z and x>9):
count+=1
if(count==len(list(l1))):
return x | next-greater-numerically-balanced-number | python solution using normal for loop | VIKASHVAR_R | 0 | 1 | next greater numerically balanced number | 2,048 | 0.471 | Medium | 28,441 |
https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/1736391/python3-brute-force-solution | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
from collections import Counter
for val in range(n+1,1224445):
counter=Counter(str(val))
if all(counter[ch]==int(ch) for ch in str(val)):
return val | next-greater-numerically-balanced-number | python3 brute force solution | Karna61814 | 0 | 77 | next greater numerically balanced number | 2,048 | 0.471 | Medium | 28,442 |
https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/1548038/Python-Simple-Brute-Force-solution | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
def count(n):
cnt = [0]*10
while n:
cnt[n%10] += 1
n //= 10
return cnt
def valid(cnt):
for i, c in enumerate(cnt):
if c > 0 and c != i:
return False
return True
x = n+1
while True:
cnt = count(x)
if valid(cnt):
return x
x += 1 | next-greater-numerically-balanced-number | [Python] Simple Brute Force solution | nightybear | 0 | 100 | next greater numerically balanced number | 2,048 | 0.471 | Medium | 28,443 |
https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/1537603/Python-3-or-Graph-DFS-Post-order-Traversal-O(N)-or-Explanation | class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
graph = collections.defaultdict(list)
for node, parent in enumerate(parents): # build graph
graph[parent].append(node)
n = len(parents) # total number of nodes
d = collections.Counter()
def count_nodes(node): # number of children node + self
p, s = 1, 0 # p: product, s: sum
for child in graph[node]: # for each child (only 2 at maximum)
res = count_nodes(child) # get its nodes count
p *= res # take the product
s += res # take the sum
p *= max(1, n - 1 - s) # times up-branch (number of nodes other than left, right children ans itself)
d[p] += 1 # count the product
return s + 1 # return number of children node + 1 (self)
count_nodes(0) # starting from root (0)
return d[max(d.keys())] # return max count | count-nodes-with-the-highest-score | Python 3 | Graph, DFS, Post-order Traversal, O(N) | Explanation | idontknoooo | 63 | 3,300 | count nodes with the highest score | 2,049 | 0.471 | Medium | 28,444 |
https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/1537511/Python3-post-order-dfs | class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
tree = [[] for _ in parents]
for i, x in enumerate(parents):
if x >= 0: tree[x].append(i)
freq = defaultdict(int)
def fn(x):
"""Return count of tree nodes."""
left = right = 0
if tree[x]: left = fn(tree[x][0])
if len(tree[x]) > 1: right = fn(tree[x][1])
score = (left or 1) * (right or 1) * (len(parents) - 1 - left - right or 1)
freq[score] += 1
return 1 + left + right
fn(0)
return freq[max(freq)] | count-nodes-with-the-highest-score | [Python3] post-order dfs | ye15 | 15 | 1,100 | count nodes with the highest score | 2,049 | 0.471 | Medium | 28,445 |
https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/1537511/Python3-post-order-dfs | class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
tree = [[] for _ in parents]
for i, x in enumerate(parents):
if x >= 0: tree[x].append(i)
def fn(x):
"""Return count of tree nodes."""
count = score = 1
for xx in tree[x]:
cc = fn(xx)
count += cc
score *= cc
score *= len(parents) - count or 1
freq[score] += 1
return count
freq = defaultdict(int)
fn(0)
return freq[max(freq)] | count-nodes-with-the-highest-score | [Python3] post-order dfs | ye15 | 15 | 1,100 | count nodes with the highest score | 2,049 | 0.471 | Medium | 28,446 |
https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/2213105/PYTHON-oror-EXPLAINED-oror | class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
def fin(n):
k=1
for i in child[n]:
k += fin(i)
nums[n]=k
return k
child = {}
for i in range(len(parents)):
child[i]=[]
for i in range(1,len(parents)):
child[parents[i]].append(i)
nums={}
fin(0)
k=1
for i in child[0]:
k*=nums[i]
score=[k]
for i in range(1,len(nums)):
k=1
k*=(nums[0]-nums[i])
for j in child[i]:
k*=nums[j]
score.append(k)
return score.count(max(score)) | count-nodes-with-the-highest-score | βοΈ PYTHON || EXPLAINED || ;] | karan_8082 | 5 | 87 | count nodes with the highest score | 2,049 | 0.471 | Medium | 28,447 |
https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/2730814/Python-DFS-Solution-with-Dictionary-Straightforward-No-Zip | class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
n = len(parents)
dic = {} # parent : sons
for i in range(n):
if parents[i] not in dic:
dic[parents[i]] = []
dic[parents[i]].append(i)
# dfs search the size of each node (number of subtrees + node itself)
# save the result in tree_size
tree_size = [0 for i in range(n)]
def search(root: int):
root_size = 1
if root in dic: # if root is a parent
for son in dic[root]:
son_size = search(son)
root_size += son_size
tree_size[root] = root_size
return root_size
# search the root
search(0)
max_score = 0
freq = {}
for i in range(n):
# initialization: if i is not a parent
left_size = 0
right_size = 0
if i in dic: # if i is a parent
if len(dic[i]) > 0:
left_size = tree_size[dic[i][0]] # size of its left subtree
if len(dic[i]) > 1:
right_size = tree_size[dic[i][1]] # size of its right subtree
# score = size of left subtree * size of right subtree * size the other trees (except i which is removed)
score = max(left_size, 1) * max(right_size, 1) * max(n - 1 - left_size - right_size, 1)
if score not in freq:
freq[score] = 0
freq[score] += 1
max_score = max(max_score, score)
return freq[max_score] | count-nodes-with-the-highest-score | [Python] DFS Solution with Dictionary, Straightforward, No Zip | bbshark | 0 | 3 | count nodes with the highest score | 2,049 | 0.471 | Medium | 28,448 |
https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/2717219/Python-easy-to-read-and-understand-or-dfs-map | class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
n = len(parents)
g = {i:[] for i in range(n)}
for u, v in enumerate(parents):
if v != -1:
g[v].append(u)
#print(g.items())
d = {i:1 for i in range(n)}
def dfs(node):
for nei in g[node]:
dfs(nei)
d[node] += d[nei]
dfs(0)
#print(d.items())
res = []
for node in range(n):
if d[node] == 1:
res.append(n-1)
else:
cnt = 1
for nei in g[node]:
cnt *= d[nei]
if parents[node] != -1:
cnt *= (n-d[node])
res.append(cnt)
#print(res)
return res.count(max(res)) | count-nodes-with-the-highest-score | Python easy to read and understand | dfs-map | sanial2001 | 0 | 2 | count nodes with the highest score | 2,049 | 0.471 | Medium | 28,449 |
https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/2478361/python-easy-recursive-solution | class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
graph = defaultdict(set)
for i, a in enumerate(parents):
if i != 0:
graph[a].add(i)
tot = len(parents)
maxv = float('-inf')
points = {}
@lru_cache
def dfs(node):
nonlocal maxv
if node and len(graph[node]) == 0:
points[node] = tot - 1
maxv = max(maxv, tot - 1)
return 1
s = 0
m = 1
for neighbor in graph[node]:
s += dfs(neighbor)
m *= dfs(neighbor)
if node != 0:
score = m * (tot-s-1)
else:
score = m * (tot-s)
maxv = max(maxv, score)
points[node] = score
return s + 1
dfs(0)
res = 0
for v in points.values():
if v == maxv:
res += 1
return res | count-nodes-with-the-highest-score | python easy recursive solution | byuns9334 | 0 | 22 | count nodes with the highest score | 2,049 | 0.471 | Medium | 28,450 |
https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/2300451/Python3-or-DFS-Approach | class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
hmap=defaultdict(list)
n=len(parents)
for i in range(n):
hmap[i]=[]
for i in range(1,n):
hmap[parents[i]].append(i)
self.childCount=[1 for i in range(n)]
for i in hmap[0]:
self.childCount[0]+=self.dfs(i,hmap)
ans=0
count=0
for i in range(n):
currProd=1
currSum=0
for j in hmap[i]:
currProd*=self.childCount[j]
currSum+=self.childCount[j]
rem=(n-1)-(currSum)
if rem>=1:
currProd*=rem
if ans==currProd:
count+=1
if ans<currProd:
count=1
ans=currProd
return count
def dfs(self,curr,hmap):
if hmap[curr]==[]:
return 1
for it in hmap[curr]:
self.childCount[curr]+=self.dfs(it,hmap)
return self.childCount[curr] | count-nodes-with-the-highest-score | [Python3] | DFS Approach | swapnilsingh421 | 0 | 48 | count nodes with the highest score | 2,049 | 0.471 | Medium | 28,451 |
https://leetcode.com/problems/parallel-courses-iii/discuss/1546258/Python-solution-using-topology-sort-and-BFS | class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
graph = { course:[] for course in range(n)}
inDegree = [0]*n
# 1- build graph
# convert 1-base into 0-baseindexes and add to graph
# Note: choose Prev->next since it helps to preserve the topology order
for prevCourse,nextCourse in relations:
prevCourse,nextCourse = prevCourse-1, nextCourse-1
graph[prevCourse].append(nextCourse)
inDegree[nextCourse] += 1
# 2 Assign time cost
q = collections.deque()
cost = [0] * n
for course in range(n):
if inDegree[course] == 0:
q.append(course)
cost[course] = time[course] # number of months
# 3- BFS
while q:
prevCourse = q.popleft()
for nextCourse in graph[prevCourse]:
# Update cost[nextCourse] using the maximum cost of the predecessor course
cost[nextCourse] = max(cost[nextCourse], cost[prevCourse] + time[nextCourse])
inDegree[nextCourse] -= 1
if inDegree[nextCourse] == 0:
q.append(nextCourse)
return max(cost)
``` | parallel-courses-iii | Python solution using topology sort and BFS | MAhmadian | 1 | 91 | parallel courses iii | 2,050 | 0.595 | Hard | 28,452 |
https://leetcode.com/problems/parallel-courses-iii/discuss/1538703/Python3-topo-sort | class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
graph = [[] for _ in range(n)]
indeg = [0]*n
for u, v in relations:
graph[u-1].append(v-1)
indeg[v-1] += 1
start = [0]*n
queue = deque((i, time[i]) for i, x in enumerate(indeg) if x == 0)
while queue:
u, t = queue.popleft() # earlist to finish course u
for v in graph[u]:
start[v] = max(start[v], t) # earlist to start course v
indeg[v] -= 1
if indeg[v] == 0: queue.append((v, start[v] + time[v]))
return max(s+t for s, t in zip(start, time)) | parallel-courses-iii | [Python3] topo sort | ye15 | 1 | 68 | parallel courses iii | 2,050 | 0.595 | Hard | 28,453 |
https://leetcode.com/problems/parallel-courses-iii/discuss/2671252/Python3-topological-sort-%2B-priority-queue | class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
adj_list = collections.defaultdict(list)
indegree = [0] * n
for prev, next in relations:
adj_list[prev].append(next)
indegree[next - 1] += 1
queue = []
for i in range(n):
if not indegree[i]:
heapq.heappush(queue, (time[i], i + 1))
endtime = 0
while queue:
endtime, course = heapq.heappop(queue)
for neighbor in adj_list[course]:
indegree[neighbor - 1] -= 1
if not indegree[neighbor - 1]:
heapq.heappush(queue, (endtime + time[neighbor - 1], neighbor))
return endtime | parallel-courses-iii | Python3 topological sort + priority queue | ellayu | 0 | 2 | parallel courses iii | 2,050 | 0.595 | Hard | 28,454 |
https://leetcode.com/problems/parallel-courses-iii/discuss/2330255/Python3-or-Priority-Queue-%2B-BFS | class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
indegree=[0]*n
adj=[[] for i in range(n)]
for i,j in relations:
adj[i-1].append(j-1)
indegree[j-1]+=1
preReq_time=defaultdict(int)
q=[(time[x],x) for x in range(n) if indegree[x]==0]
heapify(q)
cnt=0
while q:
t,course=heappop(q)
cnt+=1
if cnt==n:
return t
for it in adj[course]:
indegree[it]-=1
preReq_time[it]=max(preReq_time[it],t)
if indegree[it]==0:
heappush(q,(preReq_time[it]+time[it],it)) | parallel-courses-iii | [Python3] | Priority-Queue + BFS | swapnilsingh421 | 0 | 31 | parallel courses iii | 2,050 | 0.595 | Hard | 28,455 |
https://leetcode.com/problems/parallel-courses-iii/discuss/1548033/Python-Easy-DFS-with-Memo | class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
graph = collections.defaultdict(list)
prv_set = set()
for prv, nxt in relations:
graph[nxt-1].append(prv-1)
prv_set.add(prv-1)
course_not_prv = list(set(range(0,n))-prv_set)
@lru_cache(None)
def dfs(course):
prevs = graph[course]
cost = 0
for p in prevs:
cost = max(cost, dfs(p))
return cost + time[course]
return max(dfs(course) for course in course_not_prv) | parallel-courses-iii | [Python] Easy DFS with Memo | nightybear | 0 | 101 | parallel courses iii | 2,050 | 0.595 | Hard | 28,456 |
https://leetcode.com/problems/parallel-courses-iii/discuss/1538556/Python-3Kahn's-algorithm-and-Heap | class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
g = defaultdict(set)
deg = defaultdict(int)
for a, b in relations:
deg[b-1] += 1
g[a-1].add(b-1)
cnt = 0
# time to finish all prerequisites
prev_max_t = defaultdict(int)
q = [(time[x], x) for x in range(n) if deg[x] == 0]
heapify(q)
while q:
t, course = heappop(q)
cnt += 1
if cnt == n:
return t
for nei in g[course]:
deg[nei] -= 1
prev_max_t[nei] = max(prev_max_t[nei], t)
if deg[nei] == 0:
heappush(q, (prev_max_t[nei] + time[nei], nei)) | parallel-courses-iii | [Python 3]Kahn's algorithm and Heap | chestnut890123 | 0 | 61 | parallel courses iii | 2,050 | 0.595 | Hard | 28,457 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1549003/Python3-freq-table | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
freq = Counter(arr)
for x in arr:
if freq[x] == 1: k -= 1
if k == 0: return x
return "" | kth-distinct-string-in-an-array | [Python3] freq table | ye15 | 19 | 1,200 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,458 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1637956/Python-simplest-solution | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
n = len(arr)
cnt = defaultdict(int)
for c in arr:
cnt[c] += 1
distinct = []
for i in range(n):
if cnt[arr[i]] == 1:
distinct.append(arr[i])
if len(distinct) < k:
return ""
else:
return distinct[k-1] | kth-distinct-string-in-an-array | Python simplest solution | byuns9334 | 1 | 201 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,459 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2851502/less-python-one-solution-greater | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
a =[i for i in arr if arr.count(i)==1];
return "" if k > len(a) else a[k - 1] | kth-distinct-string-in-an-array | <-- python one solution --> | seifsoliman | 0 | 1 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,460 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2840260/Python-1-line%3A-Optimal-and-Clean-with-explanation-2-ways%3A-O(n)-time-and-O(n)-space | class Solution:
# Use frequency counter to filter the array.
def kthDistinct(self, arr: List[str], k: int) -> str:
freq = Counter(arr)
return [s for s in arr if freq[s] == 1][k-1] if k-1 < len([s for s in arr if freq[s] == 1]) else ""
# O(n) time : O(n) space
def kthDistinct(self, arr: List[str], k: int) -> str:
freq = Counter(arr)
distinct = [s for s in arr if freq[s] == 1]
return distinct[k-1] if k-1 < len(distinct) else "" | kth-distinct-string-in-an-array | Python 1 line: Optimal and Clean with explanation - 2 ways: O(n) time and O(n) space | topswe | 0 | 1 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,461 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2837108/Python3-Solution-with-using-hashmap | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
c = collections.Counter(arr)
for num in arr:
if c[num] == 1:
k -= 1
if k == 0:
return num
return "" | kth-distinct-string-in-an-array | [Python3] Solution with using hashmap | maosipov11 | 0 | 1 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,462 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2815501/Easy-solution | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
list=[]
for i in range (len(arr)):
if arr[i] not in arr[0:i]:
if arr[i] not in arr [i+1:]:
list.append(arr[i])
if k<=len(list):
return list[k-1]
return "" | kth-distinct-string-in-an-array | Easy solution | nishithakonuganti | 0 | 1 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,463 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2813481/Simple-Python-Solution | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
hashMap = {}
lst =[]
for word in arr:
hashMap[word] = arr.count(word)
for i in hashMap:
if hashMap[i] == 1:
lst.append(i)
return lst[k-1] if len(lst) >= k else "" | kth-distinct-string-in-an-array | Simple Python Solution | danishs | 0 | 1 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,464 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2811753/Python-Solution-EXPLAINED | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
#frequency
d={}
for i in arr:
if i in d:
d[i]+=1
else:
d[i]=1
#finding distinct
l=[]
for i in d.keys():
if d[i]==1:
l.append(i)
#if l has no kth element or l is empty return empty string
if len(l)<k-1 or len(l)==0:
return ""
else:
return l[k-1] #return kth string (k-1 -> for index coz len(l)==k) | kth-distinct-string-in-an-array | Python Solution - EXPLAINEDβ | T1n1_B0x1 | 0 | 2 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,465 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2758845/python-code | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
arr2=collections.Counter(arr)
for i in arr2:
if arr2[i]==1:
k-=1
if k==0:
return i
return "" | kth-distinct-string-in-an-array | python code | ayushigupta2409 | 0 | 8 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,466 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2696531/Easy-and-faster-simple | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
l=0
c=Counter(arr)
for i,j in c.items():
if(j==1):
l+=1
if(k==l):
return i
return "" | kth-distinct-string-in-an-array | Easy and faster simple | Raghunath_Reddy | 0 | 8 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,467 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2667385/Kth-Distinct-String-in-an-Array-oror-Python3-oror-Dictionary | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
d={}
for i in arr:
if i not in d:
d[i]=1
else:
d[i]+=1
print(d)
c=0
for i in arr:
if d[i]==1:
c+=1
if c==k:
return i
return '' | kth-distinct-string-in-an-array | Kth Distinct String in an Array || Python3 || Dictionary | shagun_pandey | 0 | 6 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,468 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2642466/easy-very-easy-to-understand-100 | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
newarr = []
for i in range(len(arr)):
if arr[i] not in arr[0:i]:
if arr[i] not in arr[i+1:]:
newarr.append(arr[i])
if k <= len(newarr):
return newarr[k-1]
return "" | kth-distinct-string-in-an-array | easy very easy to understand 100% | MAMuhammad571 | 0 | 8 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,469 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2559827/Fast-python-solution-using-set-dictionary!-O(n) | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
set_arr = set(arr)
if len(set_arr) < k:
return ""
if len(arr) != 1 and len(set_arr) == 1:
return ""
if len(set_arr) == len(arr):
return arr[k-1]
dict_arr = collections.Counter(arr)
distinct_num_dict = {}
for key, val in dict_arr.items():
if val == 1:
distinct_num_dict[key] = 0
count = 0
for i in range(len(arr)):
if arr[i] in distinct_num_dict:
count += 1
distinct_num_dict[arr[i]] = count
for key, val in distinct_num_dict.items():
if val == k:
return key
if k not in distinct_num_dict.values():
return "" | kth-distinct-string-in-an-array | Fast python solution using set, dictionary! O(n) | samanehghafouri | 0 | 17 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,470 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2522285/Simple-Python-solution-using-set | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
res = []
seen = set()
for i in arr:
if i in seen:
while i in res:
res.remove(i)
else:
seen.add(i)
res.append(i)
print(res)
return res[k-1] if k - 1 <= len(res) -1 else "" | kth-distinct-string-in-an-array | Simple Python solution using set | aruj900 | 0 | 28 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,471 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2099769/Python-simple-solution | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
pointer = 1
for i in arr:
if arr.count(i) == 1:
if pointer == k:
return i
else:
pointer += 1
return "" | kth-distinct-string-in-an-array | Python simple solution | StikS32 | 0 | 79 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,472 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2004000/Python-Counter!-Clean-and-Simple | class Solution:
def kthDistinct(self, arr, k):
c = Counter(arr)
a = [s for s in arr if c[s]==1]
return a[k-1] if k <= len(a) else "" | kth-distinct-string-in-an-array | Python - Counter! Clean and Simple | domthedeveloper | 0 | 55 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,473 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/2000683/Python-Solution | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
data = {}
for char in arr:
data[char] = data.get(char, 0) + 1
result = list(filter(lambda x: data[x] == 1, data))
if len(result) < k:
return ''
return result[k - 1] | kth-distinct-string-in-an-array | Python Solution | hgalytoby | 0 | 27 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,474 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1974826/Easiest-and-Simplest-Python3-Solution-or-Beginner-friendly-or-100-Faster-or-Easy-to-understand | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
temp=[]
for i in arr:
c=arr.count(i)
if c==1:
if i not in temp:
temp.append(i)
return (temp[k-1]) if len(temp)>=k else "" | kth-distinct-string-in-an-array | Easiest & Simplest Python3 Solution | Beginner-friendly | 100% Faster | Easy to understand | RatnaPriya | 0 | 51 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,475 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1954680/Hahmap-oror-Python-oror-Easy | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
dict={}
nums=[]
for i in arr:
dict[i]=dict.get(i,0)+1
for j in dict:
if dict[j]==1:
nums.append(j)
if len(nums)<k:
return ""
return nums[k-1] | kth-distinct-string-in-an-array | Hahmap || Python || Easy | Aniket_liar07 | 0 | 42 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,476 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1886642/Python-dollarolution-(faster-than-98) | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
d = Counter(arr)
for i in d:
if d[i] == 1:
k -= 1
if k == 0:
return i
return '' | kth-distinct-string-in-an-array | Python $olution (faster than 98%) | AakRay | 0 | 56 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,477 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1837682/python-easy-to-read-and-understand-or-hashmap | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
d = {}
for ch in arr:
d[ch] = d.get(ch, 0) + 1
for key in d:
if d[key] == 1:
k -= 1
if k == 0:
return key
return "" | kth-distinct-string-in-an-array | python easy to read and understand | hashmap | sanial2001 | 0 | 41 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,478 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1804258/Python3-or-Fast-(faster-than-97.02)-or-Low-Memory-(less-than-61.46)-or-Simple-or-Easy-or | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
d={}
for i in arr:
if i not in d:
d[i]=1
elif i in d:
d[i]-=1
ans=[x for x in d.keys() if d[x]==1]
if ans and len(ans)>=k:
return ans[k-1]
return '' | kth-distinct-string-in-an-array | Python3 | Fast (faster than 97.02%) | Low Memory (less than 61.46%) | Simple | Easy | | noviicee | 0 | 67 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,479 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1802811/Python-3-(60ms)-or-Counter-HashMap-Solution-or-Easy-to-Understand | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
c=Counter(arr)
for i in c:
if c[i]==1:
k-=1
if k==0:
return i
return "" | kth-distinct-string-in-an-array | Python 3 (60ms) | Counter HashMap Solution | Easy to Understand | MrShobhit | 0 | 36 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,480 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1789346/Python3-Beginner-solution-or-Easy-to-understand | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
count = collections.Counter(arr)
res = []
for i in count:
if count[i]==1:
res.append(i)
if k >len(res):
return ""
return res[k-1] | kth-distinct-string-in-an-array | [Python3] Beginner solution | Easy to understand | Rakesh_Gunelly | 0 | 28 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,481 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1756000/Kth-Distinct-String-in-an-Array-python-simple-solution | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
lst=[]
flst=[]
for i in arr:
lst.append(arr.count(i))
for x in range(len(lst)):
if lst[x]==1:
flst.append(arr[x])
if k>len(flst):
return ""
else:
return flst[k-1] | kth-distinct-string-in-an-array | Kth Distinct String in an Array python simple solution | seabreeze | 0 | 50 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,482 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1701143/Python-simple-and-easy-to-read | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
mapped = Counter(arr)
i = 0
for key, count in mapped.items():
if count == 1:
i += 1
if i == k:
return key
return "" | kth-distinct-string-in-an-array | Python simple and easy to read | johnro | 0 | 94 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,483 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1700015/Python3-accepted-solution | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
return "" if(len([i for i in arr if(arr.count(i)==1)])<k) else [i for i in arr if(arr.count(i)==1)][k-1] | kth-distinct-string-in-an-array | Python3 accepted solution | sreeleetcode19 | 0 | 63 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,484 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1695606/code-python3-(easy-understanding) | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
count = 0
a=0
d={}
b=[]
for i in arr:
d[i]=d.get(i,0)+1
for j in arr:
if j in d and d[j] == 1:
b.append(j)
print(b)
for i in b:
a += 1
if a == k:
return i
return ""
``` | kth-distinct-string-in-an-array | code python3 (easy understanding) | Asselina94 | 0 | 43 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,485 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1571570/Python3-O(n)-easy-solution | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
res = {}
ans = []
for char in arr:
if char not in res:
res[char] = 1
else:
res[char] += 1
for key, val in res.items():
if val == 1:
ans.append(key)
if len(ans) >= k:
return ans[k - 1]
else:
return '' | kth-distinct-string-in-an-array | [Python3] O(n) easy solution | erictang10634 | 0 | 74 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,486 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1554001/Python3-One-Liner | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
distinct = [string for string, count in Counter(arr).items() if count == 1]
return "" if k > len(distinct) else distinct[k - 1] | kth-distinct-string-in-an-array | Python3, One Liner | kingjonathan310 | 0 | 60 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,487 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1554001/Python3-One-Liner | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
return "" if k > len(distinct := [string for string, count in Counter(arr).items() if count == 1]) else distinct[k - 1] | kth-distinct-string-in-an-array | Python3, One Liner | kingjonathan310 | 0 | 60 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,488 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1549731/Counter-%2B-one-pass | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
if len(arr) < k: return ""
count = Counter(arr)
for i, a in enumerate(arr):
if count[a] == 1: k -= 1
if k == 0: return a
return "" | kth-distinct-string-in-an-array | Counter + one pass | abuOmar2 | 0 | 59 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,489 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1549113/Python-O(n)-Easy-to-Understand-Solution | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
dic = {}
ans = []
for i in arr:
dic[i] = dic.get(i, 0) + 1
count = 0
for i in arr:
if dic[i] == 1:
count += 1
if count == k:
return i
return '' | kth-distinct-string-in-an-array | Python O(n) - Easy to Understand Solution | satyu | 0 | 73 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,490 |
https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1549320/Python-two-liner | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
unique = [v for v, count in Counter(arr).items() if count == 1]
return unique[k-1] if k <= len(unique) else "" | kth-distinct-string-in-an-array | Python, two liner | blue_sky5 | -1 | 52 | kth distinct string in an array | 2,053 | 0.718 | Easy | 28,491 |
https://leetcode.com/problems/two-best-non-overlapping-events/discuss/1549284/Heap-oror-very-Easy-oror-Well-Explained | class Solution:
def maxTwoEvents(self, events: List[List[int]]) -> int:
events.sort()
heap = []
res2,res1 = 0,0
for s,e,p in events:
while heap and heap[0][0]<s:
res1 = max(res1,heapq.heappop(heap)[1])
res2 = max(res2,res1+p)
heapq.heappush(heap,(e,p))
return res2 | two-best-non-overlapping-events | ππ Heap || very-Easy || Well-Explained π | abhi9Rai | 13 | 502 | two best non overlapping events | 2,054 | 0.45 | Medium | 28,492 |
https://leetcode.com/problems/two-best-non-overlapping-events/discuss/1549074/Python3-binary-search | class Solution:
def maxTwoEvents(self, events: List[List[int]]) -> int:
time = []
vals = []
ans = prefix = 0
for st, et, val in sorted(events, key=lambda x: x[1]):
prefix = max(prefix, val)
k = bisect_left(time, st)-1
if k >= 0: val += vals[k]
ans = max(ans, val)
time.append(et)
vals.append(prefix)
return ans | two-best-non-overlapping-events | [Python3] binary search | ye15 | 13 | 766 | two best non overlapping events | 2,054 | 0.45 | Medium | 28,493 |
https://leetcode.com/problems/two-best-non-overlapping-events/discuss/1549074/Python3-binary-search | class Solution:
def maxTwoEvents(self, events: List[List[int]]) -> int:
ans = most = 0
pq = []
for st, et, val in sorted(events):
heappush(pq, (et, val))
while pq and pq[0][0] < st:
_, vv = heappop(pq)
most = max(most, vv)
ans = max(ans, most + val)
return ans | two-best-non-overlapping-events | [Python3] binary search | ye15 | 13 | 766 | two best non overlapping events | 2,054 | 0.45 | Medium | 28,494 |
https://leetcode.com/problems/two-best-non-overlapping-events/discuss/1557513/Sort-event-endings-and-bisect-for-start-92-speed | class Solution:
def maxTwoEvents(self, events: List[List[int]]) -> int:
end_max = defaultdict(int)
for start, end, val in events:
end_max[end] = max(end_max[end], val)
max_val = max(end_max.values())
lst_ends = sorted(end_max.keys())
for i in range(1, len(lst_ends)):
end_max[lst_ends[i]] = max(end_max[lst_ends[i]],
end_max[lst_ends[i - 1]])
for start, end, val in events:
idx = bisect_right(lst_ends, start)
if idx > 0 and start > lst_ends[idx - 1]:
max_val = max(max_val, end_max[lst_ends[idx - 1]] + val)
elif idx > 1 and start > lst_ends[idx - 2]:
max_val = max(max_val, end_max[lst_ends[idx - 2]] + val)
return max_val | two-best-non-overlapping-events | Sort event endings and bisect for start, 92% speed | EvgenySH | 0 | 114 | two best non overlapping events | 2,054 | 0.45 | Medium | 28,495 |
https://leetcode.com/problems/plates-between-candles/discuss/1549304/100-faster-Linear-Python-solution-or-Prefix-sum-or-O(N) | class Solution:
def platesBetweenCandles(self, s: str, qs: List[List[int]]) -> List[int]:
n=len(s)
prefcandle=[-1]*n #this stores the position of closest candle from current towards left
suffcandle=[0]*n #this stores the position of closest candle from current towards right
pref=[0]*n #stores the number of plates till ith position from 0 - for i = 0 -> n
ind=-1
c=0
#The following method calculates number of plates(*) till ith position from 0 - for i = 0 -> n
for i in range(n):
if ind!=-1 and s[i]=='*':
c+=1
elif s[i]=='|':
ind=i
pref[i]=c
#this method calculates the left nearest candle to a point
#intial is -1 as to left of leftmost element no candle can be present
ind =-1
for i in range(n):
if s[i] == '|':
ind=i
prefcandle[i]=ind
#this method calculates the right nearest candle to a point
#intial is infinity as to right of rightmost element no candle can be present
ind = float('inf')
for i in range(n-1, -1, -1):
if s[i]=='|':
ind=i
suffcandle[i]=ind
#m = no of queries
m=len(qs)
ans=[0]*m
for i in range(m):
c=0
l=qs[i][0]
r=qs[i][1]
#check if left nearest candle of right boundary is after left boundary
#check if right nearest candle of left boundary is before right boundary
# to summarise - here we find if there is a pair of candle present within the given range or not
if prefcandle[r]<l or suffcandle[l]>r:
continue
#desired answer is no of pplates(*) only inside 2 candles (|) inside the given boundary area
ans[i]=pref[prefcandle[r]]-pref[suffcandle[l]]
return ans | plates-between-candles | 100 % faster Linear Python solution | Prefix sum | O(N) | acloj97 | 12 | 1,200 | plates between candles | 2,055 | 0.444 | Medium | 28,496 |
https://leetcode.com/problems/plates-between-candles/discuss/1549015/Python3-binary-search-and-O(N)-approach | class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
prefix = [0]
candles = []
for i, ch in enumerate(s):
if ch == '|': candles.append(i)
if ch == '|': prefix.append(prefix[-1])
else: prefix.append(prefix[-1] + 1)
ans = []
for x, y in queries:
lo = bisect_left(candles, x)
hi = bisect_right(candles, y) - 1
if 0 <= hi and lo < len(candles) and lo <= hi:
ans.append(prefix[candles[hi]+1] - prefix[candles[lo]])
else: ans.append(0)
return ans | plates-between-candles | [Python3] binary search & O(N) approach | ye15 | 9 | 1,200 | plates between candles | 2,055 | 0.444 | Medium | 28,497 |
https://leetcode.com/problems/plates-between-candles/discuss/1549015/Python3-binary-search-and-O(N)-approach | class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
prefix = [0]
stack = []
upper = [-1]*len(s)
lower = [-1]*len(s)
lo = -1
for i, ch in enumerate(s):
prefix.append(prefix[-1] + (ch == '*'))
stack.append(i)
if ch == '|':
while stack: upper[stack.pop()] = i
lo = i
lower[i] = lo
ans = []
for x, y in queries:
lo = upper[x]
hi = lower[y]
if hi != -1 and lo != -1 and lo <= hi: ans.append(prefix[hi+1] - prefix[lo])
else: ans.append(0)
return ans | plates-between-candles | [Python3] binary search & O(N) approach | ye15 | 9 | 1,200 | plates between candles | 2,055 | 0.444 | Medium | 28,498 |
https://leetcode.com/problems/plates-between-candles/discuss/1636558/Python-oror-O(N%2BQ)-Time-O(N)-Space-oror-Easy-Commented-Code | class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
"""
Use of Prefix Sum Logic and
some additional memory to store closest plate to the left and right of given index
"""
n = len(s)
# finds next candle to Right of given Index
nextCandle2R = [0]*n
# finds next candle to Left of given Index
nextCandle2L = [n]*n
# prefix array storing cumulative plates upto given index i in string 's' at cumPlates[i+1]
cumPlates = [0]*(n+1)
candleL = -1
count = 0
for i in range(n):
if s[i] == '*':
count +=1
cumPlates[i+1] = count
if s[i] == '|':
candleL = i
nextCandle2L[i] = candleL
candleR = n
for i in range(n-1,-1,-1):
if s[i] == '|':
candleR = i
nextCandle2R[i] = candleR
"""
print("total length of s: ",n)
print("nextcandle 2 left of given index: ",nextCandle2L)
print("nextcandle 2 right of given index: ",nextCandle2R)
print("prefix array: ",cumPlates)
"""
ans = []
for query in queries:
start = query[0]
end = query[1]
#print(start,end)
# find next closest plate to right of 'start' in s
next_plateR = nextCandle2R[start]
# find next closest plate to left of 'end' in s
next_plateL = nextCandle2L[end]
if next_plateL < next_plateR:
ans.append(0)
else:
ans.append(cumPlates[next_plateL+1]-cumPlates[next_plateR+1])
return ans | plates-between-candles | Python || O(N+Q) Time, O(N) Space || Easy Commented Code | henriducard | 1 | 257 | plates between candles | 2,055 | 0.444 | Medium | 28,499 |
Subsets and Splits