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/node-with-highest-edge-score/discuss/2422372/Python-oror-Easy-Approach-oror-Hashmap
class Solution: def edgeScore(self, edges: List[int]) -> int: n = len(edges) cnt = defaultdict(int) ans = 0 // we have the key stores the node edges[i], and the value indicates the edge score. for i in range(n): cnt[edges[i]] += i m = max(cnt.values()) // In the second iteration, i is also the index of the node. So the first one meets == m, is the smallest index. for i in range(n): if cnt[i] == m: ans = i break return ans
node-with-highest-edge-score
✅Python || Easy Approach || Hashmap
chuhonghao01
4
226
node with highest edge score
2,374
0.462
Medium
32,500
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422159/Python-or-Simple-counting
class Solution: def edgeScore(self, edges: List[int]) -> int: n = len(edges) score = [0] * n for i, val in enumerate(edges): score[val] += i return score.index(max(score))
node-with-highest-edge-score
Python | Simple counting
thoufic
2
50
node with highest edge score
2,374
0.462
Medium
32,501
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2434913/Linear-solution-98-speed
class Solution: def edgeScore(self, edges: List[int]) -> int: sums = [0] * len(edges) for i, n in enumerate(edges): sums[n] += i return sums.index(max(sums))
node-with-highest-edge-score
Linear solution, 98% speed
EvgenySH
0
17
node with highest edge score
2,374
0.462
Medium
32,502
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2424663/Easy-Python
class Solution: def edgeScore(self, edges: List[int]) -> int: res = [] dic = collections.defaultdict(int) for i, n in enumerate(edges): dic[n] = i + dic.get(n, 0) for i, n in dic.items(): if len(res) == 0: res = [n, i] else: temp = res if n > temp[0]: res = [n, i] elif n == temp[0]: if i < temp[1]: res = [n, i] return res[1]
node-with-highest-edge-score
Easy Python
iampravat01
0
7
node with highest edge score
2,374
0.462
Medium
32,503
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2423124/Python-Solution-with-Dictionary
class Solution: def edgeScore(self, edges: List[int]) -> int: d=collections.defaultdict(list) for i in range(len(edges)): d[edges[i]].append(i) l=list() s=0 c=0 for u,v in d.items(): if sum(v)>s: s=sum(v) c=u if sum(v)==s and u<c: c=u return c
node-with-highest-edge-score
Python Solution with Dictionary
a_dityamishra
0
3
node with highest edge score
2,374
0.462
Medium
32,504
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2423120/O(n)-counting-node-score-at-every-edges
class Solution: def edgeScore(self, edges: List[int]) -> int: s = {} for i in range(len(edges)): s[edges[i]] = s.get(edges[i], 0) + i an = sorted(s.keys()) ans = -1 for ni in an: if ans == -1 or s[ni]>s[ans]: ans = ni return ans
node-with-highest-edge-score
O(n) counting node score at every edges
dntai
0
5
node with highest edge score
2,374
0.462
Medium
32,505
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422499/Python3-Easy-approach-short-code
class Solution: def edgeScore(self, edges: List[int]) -> int: n = len(edges) scores = [0] * n for i in range(n): scores[edges[i]] += i return scores.index(max(scores))
node-with-highest-edge-score
[Python3] Easy approach, short code
celestez
0
5
node with highest edge score
2,374
0.462
Medium
32,506
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422466/Secret-Python-Answer-Linear-Time-Counting-and-Max
class Solution: def edgeScore(self, edges: List[int]) -> int: res = 0 n = len(edges) sc = [0 for i in range(n)] for i,n in enumerate(edges): sc[n] += i m = max(sc) for i,e in enumerate(sc): if e == m: return i
node-with-highest-edge-score
[Secret Python Answer🤫🐍👌😍] Linear Time Counting and Max
xmky
0
5
node with highest edge score
2,374
0.462
Medium
32,507
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422465/Python-Simple-Python-Solution-Using-HashMap-or-Dictionary
class Solution: def edgeScore(self, edges: List[int]) -> int: d = {} for i in range(len(edges)): if edges[i] not in d: d[edges[i]] = [i] else: d[edges[i]].append(i) key = 100000000 value = -100000000 for k in d: current_sum = sum(d[k]) if current_sum == value: value = current_sum key = min(key, k) if current_sum > value: value = current_sum key = k return key
node-with-highest-edge-score
[ Python ] ✅✅ Simple Python Solution Using HashMap | Dictionary 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
12
node with highest edge score
2,374
0.462
Medium
32,508
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422418/python3-count-scores-then-find-max-then-iterate-index-and-return-first-that-equals-max
class Solution: def edgeScore(self, edges: List[int]) -> int: n = len(edges) scores = [0 for _ in range(n)] # scores[i] is the total score that node 'i' has for score, pointed in enumerate(edges): scores[pointed] += score mx = max(scores) for i in range(n): # iterate from smallest to biggest index and return immediately if match if scores[i] == mx: return i return -1
node-with-highest-edge-score
python3 count scores then find max then iterate index and return first that equals max
Pinfel
0
2
node with highest edge score
2,374
0.462
Medium
32,509
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422291/Python-3-O(n)-Time-and-Space-or-Easy-to-read
class Solution: def edgeScore(self, edges: List[int]) -> int: n = len(edges) sums = [0] * n for src, dst in enumerate(edges): sums[dst] += src max_sum = max(sums) return sums.index(max_sum) ```
node-with-highest-edge-score
[Python 3] O(n) Time & Space | Easy to read
leet_aiml
0
7
node with highest edge score
2,374
0.462
Medium
32,510
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422229/Python3-simulations
class Solution: def edgeScore(self, edges: List[int]) -> int: score = [0]*len(edges) for i, x in enumerate(edges): score[x] += i return score.index(max(score))
node-with-highest-edge-score
[Python3] simulations
ye15
0
5
node with highest edge score
2,374
0.462
Medium
32,511
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422196/Python3-Solution
class Solution: def edgeScore(self, edges: List[int]) -> int: score_map = {} #Iterate edges and find the score for all the nodes. for i,num in enumerate(edges): score_map[num] = score_map.get(num,0) + i result,max_score = sys.maxsize,0 for k,v in score_map.items(): if v > max_score: result = k max_score = v elif v == max_score and k < result: result = k return result
node-with-highest-edge-score
Python3 Solution
parthberk
0
8
node with highest edge score
2,374
0.462
Medium
32,512
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422196/Python3-Solution
class Solution: def edgeScore(self, edges: List[int]) -> int: scores = [0]*len(edges) for i,num in enumerate(edges): scores[num] += i result,max_score = 0,-sys.maxsize for i,num in enumerate(scores): if scores[i] > max_score: result = i max_score = num return result
node-with-highest-edge-score
Python3 Solution
parthberk
0
8
node with highest edge score
2,374
0.462
Medium
32,513
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422093/Python3-Counter-and-Return-Max
class Solution: def edgeScore(self, edges: List[int]) -> int: edge_cnts = defaultdict(int) max_idx, max_val = 0, 0 for inp, out in enumerate(edges): edge_cnts[out] += inp for idx in range(len(edges)): if edge_cnts[idx] > max_val: max_idx, max_val = idx, edge_cnts[idx] return max_idx
node-with-highest-edge-score
[Python3] Counter & Return Max
0xRoxas
0
24
node with highest edge score
2,374
0.462
Medium
32,514
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2422249/Python3-greedy
class Solution: def smallestNumber(self, pattern: str) -> str: ans = [1] for ch in pattern: if ch == 'I': m = ans[-1]+1 while m in ans: m += 1 ans.append(m) else: ans.append(ans[-1]) for i in range(len(ans)-1, 0, -1): if ans[i-1] == ans[i]: ans[i-1] += 1 return ''.join(map(str, ans))
construct-smallest-number-from-di-string
[Python3] greedy
ye15
22
994
construct smallest number from di string
2,375
0.739
Medium
32,515
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2422249/Python3-greedy
class Solution: def smallestNumber(self, pattern: str) -> str: ans = [] stack = [] for i in range(len(pattern)+1): stack.append(str(i+1)) if i == len(pattern) or pattern[i] == 'I': while stack: ans.append(stack.pop()) return ''.join(ans)
construct-smallest-number-from-di-string
[Python3] greedy
ye15
22
994
construct smallest number from di string
2,375
0.739
Medium
32,516
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2425788/Python-easy-to-understand-greedy-solution.
class Solution: def smallestNumber(self, pattern: str) -> str: ans = [] dec_count = 0 for i in range(len(pattern)): if pattern[i] == "I": for j in range(i, i-dec_count-1,-1): ans.append(str(j+1)) dec_count = 0 elif pattern[i] == "D": dec_count += 1 # for the remaining dec_count if there is any for j in range(len(pattern), len(pattern)-dec_count-1,-1): ans.append(str(j+1)) return "".join(ans)
construct-smallest-number-from-di-string
[Python] easy to understand greedy solution.
tolimitiku
5
188
construct smallest number from di string
2,375
0.739
Medium
32,517
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2800344/Python3-Solution-with-using-stack
class Solution: def smallestNumber(self, pattern: str) -> str: res, stack = [], [] for i in range(len(pattern) + 1): stack.append(str(i + 1)) if i == len(pattern) or pattern[i] == 'I': while stack: res.append(stack.pop()) return ''.join(res)
construct-smallest-number-from-di-string
[Python3] Solution with using stack
maosipov11
0
3
construct smallest number from di string
2,375
0.739
Medium
32,518
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2781262/One-pass-method-with-Easy-to-understand-beats-98
class Solution: def smallestNumber(self, s: str) -> str: res = [0] * (len(s) + 1) stack = [] cur = 1 for i in range(len(res)): if i == len(s) or s[i] == 'D': stack.append(i) if i < len(s): continue else: res[i] = cur cur += 1 while stack: res[stack.pop()] = cur cur += 1 return ''.join(map(str,res))
construct-smallest-number-from-di-string
One pass method with Easy to understand beats 98%
RanjithRagul
0
6
construct smallest number from di string
2,375
0.739
Medium
32,519
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2748096/Python-Greedy-Solution-O(n)-Time-O(1)-extra-space
class Solution: def smallestNumber(self, pattern: str) -> str: res = [] n = len(pattern) cur = 1 i = 0 while i < n: d_count = 0 while i < n and pattern[i] == 'D': d_count += 1 i += 1 for x in range(cur + d_count, cur - 1, -1): res.append(str(x)) cur += d_count + 1 if i == n - 1 and pattern[i] == 'I': res.append(str(cur)) i += 1 return ''.join(res)
construct-smallest-number-from-di-string
Python Greedy Solution O(n) Time O(1) extra space
nevergiveup2
0
1
construct smallest number from di string
2,375
0.739
Medium
32,520
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2748095/Python-Greedy-Solution-O(n)-Time-O(1)-extra-space
class Solution: def smallestNumber(self, pattern: str) -> str: res = [] n = len(pattern) cur = 1 i = 0 while i < n: d_count = 0 while i < n and pattern[i] == 'D': d_count += 1 i += 1 for x in range(cur + d_count, cur - 1, -1): res.append(str(x)) cur += d_count + 1 if i == n - 1 and pattern[i] == 'I': res.append(str(cur)) i += 1 return ''.join(res)
construct-smallest-number-from-di-string
Python Greedy Solution O(n) Time O(1) extra space
nevergiveup2
0
1
construct smallest number from di string
2,375
0.739
Medium
32,521
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2666308/Python3O(n)O(1)-Linear-Scan-with-constant-space-with-explaincomments
class Solution: def smallestNumber(self, pattern: str) -> str: # the result res = '' # current number curr = 0 # how many Ds we see so far decrease_count = 0 # we are adding 'I' to our pattern so that we can avoid # doing the inner for loop again after the main loop # due to trailing Ds for ch in pattern + 'I': if ch == 'D': # if we see D, we just up the count and continue decrease_count += 1 continue # otherwise we will first flush any decreasing sequence # if there is one (decrease_count > 0) curr += 1 for i in range(curr + decrease_count, curr, -1): res += str(i) # add in the current number res += str(curr) # now curr will also increase by decreasing count curr += decrease_count decrease_count = 0 return res
construct-smallest-number-from-di-string
[Python3][O(n)/O(1)] Linear Scan with constant space with explain/comments
eaglediao
0
4
construct smallest number from di string
2,375
0.739
Medium
32,522
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2451111/Python3-or-Index-Out-of-Bounds-Help(Can't-Identify-Cause-of-Bug)
class Solution: def smallestNumber(self, pattern: str) -> str: #Approach: Basically, given pattern string input of length n, generate all possible #distinct length n+1 num strings, check if each of them is a valid DI string, then #check it against built-up answer and update if necessary! Once recursion ends, we should #have our answer! n = len(pattern) #1st helper function: tell if current DI String is valid or not! def is_Valid(s, p): l = len(p) flag = False for i in range(0, l): if(p[i] == 'I'): if(s[i] < s[i+1]): continue else: flag = True break else: if(s[i] > s[i+1]): continue else: flag = True break if(flag): return False return True ans = "" #initialize ans! for i in range(n+1): ans += "9" def helper(cur, a): nonlocal n, pattern, ans #base case: len(cur) == n + 1 if(len(cur) == n + 1): if(is_Valid(cur, pattern)): #compare lexicographically! ans = min(ans, cur) return #if not base case, we will simply recurse! length = len(a) #iterate through all of the available unused digits to add to built up cur string! for i in range(length): digit = a[i] #add current available digit to cur! cur += digit #exclude ith index element! a = a[:i] + a[i+1:] helper(cur, a) #once recursion finishes, restore for backtracking! #restore array a! a = a[:i] + [digit] + a[i+1:] cur = cur[:len(cur)-1] #initial_arr will be filled with digits "1"-"9" before start of recursion! #It will be passed as 2nd arg. to helper to indicate which digits are available #for use! initial_arr = [] for a in range(1, 10): initial_arr.append(str(a)) helper("", initial_arr) return ans
construct-smallest-number-from-di-string
Python3 | Index Out of Bounds Help(Can't Identify Cause of Bug)
JOON1234
0
13
construct smallest number from di string
2,375
0.739
Medium
32,523
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2451069/Python3-or-Why-Am-I-Failing-Edge-Case(%22DDDIII%22)
class Solution: def smallestNumber(self, pattern: str) -> str: #Approach: I will define a recursive helper function that will build up the valid num #string based on specified pattern string! #It will involve 3 parameters: current built up string cur, index i of pattern to consider, #as well as pre, which indiates the most recently added digit! #For exhausting all possible ways to construct DI-string, I will initialize pre to be 0 #if pattern[0] is 'I' and 10 otherwise! #Basically, the general idea is at every decision making node in rec. tree, #if 'I', then we iterate from [pre+1, 9] and if the digit is in set, then it's unused #and available to concatenate to current built up string and recurse further on the new string! #if 'D', then iterate from [pre-1, 1] and if digit is in set, go ahead and add the current digit #char and recurse on it! #Base Case: if i == len(pattern), then we constructed a valid num string and compare #against current built up smallest number and update answer! #Another case where rec. bottoms out is if we iterate through all possible numbers and none #available in set, we hit a dead end and know that the particular path we are on won't lead #us to a valid di string! n = len(pattern) ans = "" #initialize ans as really large garbage string! for i in range(n): ans += "9" def helper(i, cur, pre, s): #base case nonlocal n, pattern, ans if(i == n): if(cur < ans): #since cur may change once we return to parent caller during recursion, #we need to assign answer to a deep copy! ans = cur[::] return else: return #get the current pattern char! cp = pattern[i] #if not base case, iterate! if(cp == 'I'): for a in range(pre+1, 10, 1): #if current digit a is available in set s, go ahead and add to cur and recurse! if(a in s): cur += str(a) s.remove(a) #make sure to remove current integer a since it's unavailable to use in rec. #call! helper(i+1, cur, a, s) #once rec. finishes, restore s and cur before backtracking! s.add(a) cur = cur[:len(cur)-1] continue else: continue else: for b in range(pre-1, 0, -1): if(b in s): cur += str(b) s.remove(b) helper(i+1, cur, b, s) s.add(b) cur = cur[:len(cur)-1] continue #even if current digit b is unavailable for use, already in cur as char, still #continue to next iteration if can! else: continue initial_pre = 0 if pattern[0] == 'I' else 10 initial_set = set() for c in range(1, 10): initial_set.add(c) #Depending on first char, I will concatenate to cur string first available digit to start out #with! #Make sure to update set as well as before initiating recursion! if(pattern[0] == 'I'): for d in range(1, 9, 1): copy = initial_set copy.remove(d) helper(0, str(d), initial_pre, initial_set) else: for e in range(9, 1, -1): copy2 = initial_set copy2.remove(e) helper(0, str(e), initial_pre, initial_set) return ans
construct-smallest-number-from-di-string
Python3 | Why Am I Failing Edge Case("DDDIII")
JOON1234
0
11
construct smallest number from di string
2,375
0.739
Medium
32,524
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2425749/backtrack-oror-Python3
class Solution: def smallestNumber(self, pattern: str) -> str: # flag works as backtrack ending signal self.flag = False self.res = "" # num: current digit string up to this step # string: remaining pattern need to be deal with # unused: remaining digits that are not used in num def backtrack(num, string, unused): # ending conditions if self.flag: return # this equals to len(num)==len(pattern)+1 if len(string)==0: self.flag = True self.res = num return # for two possibilities, loop over unused list, by default small to large if string[0]=='I': for u in unused: if int(u)>int(num[-1]): unused_copy = unused[:] unused_copy.remove(u) backtrack(num+u, string[1:], unused_copy) else: for u in unused: if int(u)<int(num[-1]): unused_copy = unused[:] unused_copy.remove(u) backtrack(num+u, string[1:], unused_copy) # l: all available digits l = [str(_) for _ in range(1, 10)] # loop over l: assume final answer can start with i (1 to 9, small to large) for i in l: unused = l[:] unused.remove(i) backtrack(i, pattern, unused) # if flag is True after backtracking, meaning answer is formatted already if self.flag: return self.res
construct-smallest-number-from-di-string
backtrack || Python3
xmmm0
0
7
construct smallest number from di string
2,375
0.739
Medium
32,525
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2425098/Python3-or-Need-Help-Figuring-Why-I-am-getting-Index-Out-of-Bounds-Error!
class Solution: #define a helper function that checks whether given streets meets the given pattern! def helper(self, string: str, pattern: str)->bool: n = len(pattern) #basically, for every index position i, check whether string[i] > string[i+1] if pattern[i] #is 'D' or opposite otherwise! for i in range(0, n): pattern_c = pattern[i] if(pattern_c == 'I'): if(string[i] > string[i+1]): return False #dec. case! else: if(string[i] < string[i+1]): return False return True def smallestNumber(self, pattern: str) -> str: #initialize ans with largest string value possible! ans = "987654321" #generate all possible strings, each using all digits 1-9 at most once! def generate(string, s): nonlocal pattern, ans #base case of recursion: check if usuable elements or digits in set s is empty! #the given accumulated string should be compared to answer! if(s == None): if(int(string) < int(ans) and self.helper(string, pattern)): ans = string return #otherwise, take the current string and recurse further for each unused digit in set s! for unused in s: d = s.copy() d = d.remove(unused) generate(string + unused, d) initial_set = set() #loop through and add digits 1-9 at the start since all of it is unused to pass into parameter #of generate helper function! for i in range(1, 10): initial_set.add(str(i)) generate("", initial_set) return ans
construct-smallest-number-from-di-string
Python3 | Need Help Figuring Why I am getting Index Out of Bounds Error!
JOON1234
0
6
construct smallest number from di string
2,375
0.739
Medium
32,526
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2424538/Python3-Intuitive-O(n)-solution
class Solution: def smallestNumber(self, pattern: str) -> str: n = len(pattern) # Since we want the minimal string satisfying the conditions, we can restrict our search to the smallest n+1 values: numbers = [i for i in range(n+1,0,-1)] # Next, we initialize the array I_next, where I_next[i] will contain the distance to the next 'I' in pattern. If pattern[i] == I, then I_next[i] = 0. I_next = [0]*(n+1) for i in range(n-1,-1,-1): I_next[i] = I_next[i+1] + 1 if pattern[i]=='D' else 0 #Finally, we iteratively select the smallest possible available element. Notice that if the distance to the next I is n, then we can take the nth smallest element to make room for the n-1 Ds until then: output = "" for cur in range(n+1): output += str(numbers.pop(-1-I_next[cur])) return output
construct-smallest-number-from-di-string
Python3 Intuitive O(n) solution
yshulz
0
13
construct smallest number from di string
2,375
0.739
Medium
32,527
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2423894/python3-Stack-sol-for-reference
class Solution: def smallestNumber(self, pattern: str) -> str: s = ["1"] chars = list("23456789") for index, p in enumerate(pattern): i = index if p == 'I': tmp = [] while s and chars[0] < s[-1] and pattern[i] == pattern[index]: tmp.append(s.pop()) s.append(chars.pop(0)) while tmp: s.append(tmp.pop()) elif p == 'D': tmp = [] while s and chars[0] > s[-1] and pattern[i] == pattern[index]: tmp.append(s.pop()) i -= 1 s.append(chars.pop(0)) while tmp: s.append(tmp.pop()) return "".join(s)
construct-smallest-number-from-di-string
[python3] Stack sol for reference
vadhri_venkat
0
6
construct smallest number from di string
2,375
0.739
Medium
32,528
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2423182/Switch-Digits
class Solution: def smallestNumber(self, pattern: str) -> str: res = [] def switch(s,d): nonlocal res while s<d: res[s], res[d] = res[d], res[s] s += 1 d -= 1 i = 1 while i<len(pattern)+2: res.append(i) i += 1 i = 0 while i<len(pattern): x = pattern[i] if x == 'D': s = i # find d while i < len(pattern): if pattern[i] != 'D': d = i break elif i == len(pattern)-1: d = i+1 break i += 1 # switch switch(s,d) i = d+1 else: i += 1 return ''.join(map(str,res))
construct-smallest-number-from-di-string
Switch Digits
leetcodeman117
0
2
construct smallest number from di string
2,375
0.739
Medium
32,529
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2423097/Back-tracking-with-pattern-and-unique-constrains
class Solution: def smallestNumber(self, pattern: str) -> str: def fsol(i, n, ans): if len(ans)>0: return for j in range(1, 10): if chk[j] is False and (i==0 or (pattern[i-1]=="I" and s[i-1]<j) or (pattern[i-1]=="D" and s[i-1]>j)): s[i] = j chk[j] = True if i==n: for i in s: ans.append(i) return else: fsol(i+1, n, ans) chk[j] = False s[i] = -1 pass n = len(pattern) chk = [False] * 10 s = [-1] * (n+1) ans = [] fsol(0, n, ans) ans = "".join([str(v) for v in ans]) return ans
construct-smallest-number-from-di-string
Back-tracking with pattern and unique constrains
dntai
0
4
construct smallest number from di string
2,375
0.739
Medium
32,530
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2422427/Python-Simple-Python-Solution-By-Generating-All-Permutation
class Solution: def smallestNumber(self, pattern: str) -> str: l = [x for x in range(1,len(pattern)+2)] check = [] from itertools import permutations perm = permutations(l) for i in list(perm): num = list(i) count = 0 for j in range(len(pattern)): if pattern[j] == 'I': if num[j] < num[j+1]: count = count + 1 elif pattern[j] == 'D': if num[j] > num[j+1]: count = count + 1 if count == len(pattern): check.append(num) break result = '' for n in check[0]: result = result + str(n) return result
construct-smallest-number-from-di-string
[ Python ] ✅✅ Simple Python Solution By Generating All Permutation 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
27
construct smallest number from di string
2,375
0.739
Medium
32,531
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2422390/Secret-Python-Answer-Recursive-%2B-Backtracking-Set-of-Visited
class Solution: def smallestNumber(self, pattern: str) -> str: l = len(pattern) sol = "" visited = set([1,2,3,4,5,6,7,8,9]) def backtrack(cur, i ): nonlocal l nonlocal sol if len(cur) == l+1: sol = cur return True for j in visited: k = int(cur[-1]) if pattern[i] == 'I' and j <= k: continue if pattern[i] == 'D' and j >= k: continue visited.remove(j) if backtrack(cur + str(j), i+1): return True visited.add(j) return False for j in visited: visited.remove(j) if backtrack(str(j), 0): return sol visited.add(j)
construct-smallest-number-from-di-string
[Secret Python Answer🤫🐍👌😍] Recursive + Backtracking Set of Visited
xmky
0
19
construct smallest number from di string
2,375
0.739
Medium
32,532
https://leetcode.com/problems/count-special-integers/discuss/2422258/Python3-dp
class Solution: def countSpecialNumbers(self, n: int) -> int: vals = list(map(int, str(n))) @cache def fn(i, m, on): """Return count at index i with mask m and profile flag (True/False)""" ans = 0 if i == len(vals): return 1 for v in range(vals[i] if on else 10 ): if m &amp; 1<<v == 0: if m or v: ans += fn(i+1, m ^ 1<<v, False) else: ans += fn(i+1, m, False) if on and m &amp; 1<<vals[i] == 0: ans += fn(i+1, m ^ 1<<vals[i], True) return ans return fn(0, 0, True)-1
count-special-integers
[Python3] dp
ye15
5
466
count special integers
2,376
0.363
Hard
32,533
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2454458/Python-oror-Easy-Approach-oror-Sliding-Window-oror-Count
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: ans = 0 res = 0 for i in range(len(blocks) - k + 1): res = blocks.count('B', i, i + k) ans = max(res, ans) ans = k - ans return ans
minimum-recolors-to-get-k-consecutive-black-blocks
✅Python || Easy Approach || Sliding Window || Count
chuhonghao01
3
318
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,534
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2469113/Python-Elegant-and-Short-or-One-pass-or-Sliding-window
class Solution: """ Time: O(n) Memory: O(k) """ def minimumRecolors(self, blocks: str, k: int) -> int: min_cost = cost = blocks[:k].count('W') for i in range(k, len(blocks)): cost = cost - (blocks[i - k] == 'W') + (blocks[i] == 'W') min_cost = min(min_cost, cost) return min_cost
minimum-recolors-to-get-k-consecutive-black-blocks
Python Elegant & Short | One pass | Sliding window
Kyrylo-Ktl
2
123
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,535
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2488377/Python-for-beginners-Nice-question-to-learn-for-sliding-window-algorithm-Commented-solution!!
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: #Simple-Approach (Sliding Window) #Runtime:42ms lis=[] for i in range(0,len(blocks)): count_b=blocks[i:i+k].count("B") #Count Blacks if(count_b>=k): #If Count Blacks > desired number of consecutive black blocks return 0 return 0 lis.append(k-count_b) # Minimum number of operation required for consecutive black k times return min(lis) #Return minimum number of blocks operation required
minimum-recolors-to-get-k-consecutive-black-blocks
Python for beginners [Nice question to learn for sliding window algorithm] Commented solution!!
mehtay037
1
91
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,536
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2488377/Python-for-beginners-Nice-question-to-learn-for-sliding-window-algorithm-Commented-solution!!
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: #Simple-Approach (Sliding Window) #Runtime:32ms minimum_change=k #Worst Case scenario if all blocks are white minimum change required is k times for i in range(0,len(blocks)): count_b=blocks[i:i+k].count("B") #Count Blacks if(count_b>=k): #If Count Blacks > desired number of consecutive black blocks return 0 return 0 minimum_change=min(minimum_change,k-count_b) #updating the minimum change return minimum_change
minimum-recolors-to-get-k-consecutive-black-blocks
Python for beginners [Nice question to learn for sliding window algorithm] Commented solution!!
mehtay037
1
91
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,537
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2478962/Python-easy-solution-28-ms-oror-faster-than-100
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: min_operation, step = 0, 0 while step < len(blocks) - k + 1: temp_arr = blocks[step : step + k] if step == 0: min_operation += temp_arr.count("W") else: min_operation = min(min_operation, temp_arr.count("W")) step += 1 return min_operation
minimum-recolors-to-get-k-consecutive-black-blocks
✅ Python easy solution 28 ms || faster than 100%
sezanhaque
1
61
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,538
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2471572/Python-easy-sliding-window-solution-faster-than-80
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: res = len(blocks) for i in range(len(blocks)): select = blocks[i:i+k] if len(select) == k: if select.count('W') < res: res = select.count('W') else: break return res
minimum-recolors-to-get-k-consecutive-black-blocks
Python easy sliding window solution faster than 80%
alishak1999
1
54
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,539
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2455631/Python-simple-sliding-window-solution
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: ans = [] for i in range(0, len(blocks)-k+1): ans.append(blocks[i:i+k].count('W')) return min(ans)
minimum-recolors-to-get-k-consecutive-black-blocks
Python simple sliding window solution
StikS32
1
41
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,540
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2454177/Python3-Sliding-window
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: ans = inf rsm = 0 for i, ch in enumerate(blocks): if ch == 'W': rsm += 1 if i >= k and blocks[i-k] == 'W': rsm -= 1 if i >= k-1: ans = min(ans, rsm) return ans
minimum-recolors-to-get-k-consecutive-black-blocks
[Python3] Sliding window
ye15
1
52
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,541
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2844998/Python-Easy-or-Sliding-window-or-Simple-O(N)
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: length = len(blocks) w, ans = 0, float('inf') for j in range(length): if j<k: if blocks[j]=='W': w+=1 if j == k-1: ans = min(w, ans) else: if blocks[j-k]=='W': w-=1 if blocks[j]=='W': w+=1 ans = min(w, ans) return 0 if ans == float('inf') else ans
minimum-recolors-to-get-k-consecutive-black-blocks
[Python] Easy | Sliding window | Simple O(N)
girraj_14581
0
2
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,542
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2832475/Python-or-Clearly-Explained-or-Faster-than-95
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: i = 0 chan = 0 minChain = inf while i+k <= len(blocks): ss = blocks[i:i+k] chan = ss.count('W') minChain = min(chan,minChain) i += 1 return minChain
minimum-recolors-to-get-k-consecutive-black-blocks
Python | Clearly Explained | Faster than 95%
Chityanj
0
2
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,543
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2827321/Python-Sliding-Window-Easy-to-Understand
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: mn = inf for i in range(k, len(blocks) + 1): window = blocks[i-k:i] wcount = window.count('W') mn = min(mn, wcount) return mn
minimum-recolors-to-get-k-consecutive-black-blocks
Python Sliding Window - Easy to Understand
ziqinyeow
0
2
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,544
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2814476/Python-Solution-with-0(n)
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: i, ans, count = 0,0,0 for j in range(len(blocks)): if j < k: if blocks[j] == 'W': count+=1 ans = count else: if blocks[j] == "W": if blocks[i] == "W": pass else: count+=1 else: if blocks[i] == "W": count-=1 else: pass i+=1 ans = min(count, ans) return ans
minimum-recolors-to-get-k-consecutive-black-blocks
Python Solution with 0(n)
duresafeyisa2022
0
1
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,545
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2808316/Simple-Sliding-Window-Solution
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: left, right = 0 , 0 ans = k count = 0 blocks = blocks.replace('W','1').replace('B','0') while right < len(blocks): count += int(blocks[right]) while right - left + 1 > k: count -= int(blocks[left]) left += 1 if right - left +1 == k: ans = min(count, ans) right += 1 return ans
minimum-recolors-to-get-k-consecutive-black-blocks
Simple Sliding Window Solution
vijay_2022
0
3
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,546
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2804084/Solution-based-on-fixed-size-sliding-window-template
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: count = float('inf') start = 0 end = 0 recolorCount = 0 while end < len(blocks): if blocks[end] == 'W': recolorCount += 1 if end - start + 1 >= k: if recolorCount < count: count = recolorCount if blocks[start] == 'W': recolorCount -= 1 start += 1 end += 1 return count
minimum-recolors-to-get-k-consecutive-black-blocks
Solution based on fixed size sliding window template
disturbedbrown1
0
1
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,547
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2799445/SLIDING-WINDOW-SOLUTION
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: res=[] for i in range(len(blocks)-k+1): subarr=blocks[i:i+k] count=subarr.count("W") res.append(count) if len(blocks)<k: return 0 else: return min(res)
minimum-recolors-to-get-k-consecutive-black-blocks
SLIDING WINDOW SOLUTION
vanshikasharma24__
0
3
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,548
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2784869/sliding-window-with-dict
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: count = defaultdict(int) l, res = 0, float('inf') for r in range(len(blocks)): count[blocks[r]] += 1 if r - l + 1 > k: count[blocks[l]] -= 1 l += 1 if r - l + 1 == k: res = min(res, count['W']) return res
minimum-recolors-to-get-k-consecutive-black-blocks
sliding window with dict
JasonDecode
0
2
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,549
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2728935/Simple-Python-Sliding-Window-Solution-95-Time-75-Space
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: # use sliding window to find max number of B in k substring m = curr = blocks[:k].count('B') for i in range(1, len(blocks)-k+1): curr -= 1 if blocks[i-1] == 'B' else 0 #last char of prev substring curr += 1 if blocks[i+k-1] == 'B' else 0 #new addition to this substring m = max(m, curr) return k - m # subtract num of max B's from k to get num of min W's
minimum-recolors-to-get-k-consecutive-black-blocks
Simple Python Sliding Window Solution, 95% Time, 75% Space
Parth86
0
9
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,550
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2723402/Simple-Python-Solution
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: ans = [] for i in range(len(blocks)-k+1): ans.append(blocks[i:i+k].count('W')) return min(ans)
minimum-recolors-to-get-k-consecutive-black-blocks
Simple Python Solution
sbaguma
0
4
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,551
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2695258/sliding-window-easy-concepts-in-python
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: ws=0 we=0 mini=1000000000000000 flips=0 count=0 for we in range(len(blocks)): if blocks[we]=="W": flips+=1 count+=1 elif blocks[we]=="B": count+=1 if count==k: mini=min(mini,flips) if blocks[ws]=="W": flips-=1 count-=1 else: count-=1 ws+=1 return mini
minimum-recolors-to-get-k-consecutive-black-blocks
sliding window easy concepts in python
insane_me12
0
4
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,552
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2635177/Very-Simple-solution-using-SLIDING-WINDOW-with-explanation-or-Python-or-HashMap
class Solution(object): def minimumRecolors(self, blocks, k): """ :type blocks: str :type k: int :rtype: int """ #in this problem, k is the size of window. We need to check 'W' counts in each window of length k. And need to update minimum w.r.t each window minimum=float("inf") windowStart=0 dictionary={} for i in range(len(blocks)): if blocks[i] not in dictionary: dictionary[blocks[i]]=0 dictionary[blocks[i]]+=1 if (i-windowStart+1)>=k: #If 'W' not appeared and we reached to desired length of window, if means we don't need to replace any block. So just return 0 if 'W' not in dictionary: return 0 minimum = min(minimum,dictionary['W']) dictionary[blocks[windowStart]]-=1 windowStart+=1 return minimum
minimum-recolors-to-get-k-consecutive-black-blocks
Very Simple solution using SLIDING WINDOW with explanation | Python | HashMap
msherazedu
0
23
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,553
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2509266/Python-two-solutions
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: return min(blocks[i:i+k].count('W') for i in range((len(blocks)-k)+1))
minimum-recolors-to-get-k-consecutive-black-blocks
Python two solutions
omarihab99
0
59
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,554
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2509266/Python-two-solutions
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: no_operations=0 min_operations=math.inf window_start=0 block_freq=defaultdict(int) for window_end in range(len(blocks)): right=blocks[window_end] block_freq[right]+=1 if right=='W': no_operations+=1 if block_freq['B']==k: return 0 elif block_freq['B'] + block_freq['W'] ==k: min_operations = min(min_operations, no_operations) left=blocks[window_start] window_start+=1 block_freq[left]-=1 if left=='W': no_operations-=1 return min_operations
minimum-recolors-to-get-k-consecutive-black-blocks
Python two solutions
omarihab99
0
59
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,555
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2499396/Python-or-sliding-window-or-easy
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: if 'B'*k in blocks: return 0 curr=0 least=n=len(blocks) i=j=0 blocks2=list(blocks) while j<n: if blocks2[j]=='W': blocks2[j]='B' curr+=1 if j-i+1<k: j+=1 elif j-i+1==k: if 'B' in blocks2[i:j+1] and len(set(blocks2[i:j+1]))==1: least=min(curr,least) if blocks[i]=='W': curr-=1 i+=1 j+=1 return least
minimum-recolors-to-get-k-consecutive-black-blocks
Python | sliding window | easy
ayushigupta2409
0
74
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,556
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2498913/Easy-python-solution
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: ans = float('inf') for i in range(0, len(blocks) - k + 1): ans = min(ans, blocks[i:i+k].count('W')) return ans
minimum-recolors-to-get-k-consecutive-black-blocks
Easy python solution
Maxonchikkkk
0
24
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,557
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2461357/Python-Sliding-Window
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: start = 0 end = 0 op = 0 minop = float("inf") for end in range(len(blocks)): if blocks[end] == 'W': op += 1 if end - start + 1 == k: minop = min(op, minop) if blocks[start] == 'W': op -= 1 start += 1 return minop
minimum-recolors-to-get-k-consecutive-black-blocks
Python Sliding Window
theReal007
0
23
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,558
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2460524/Python-or-Sliding-Window-or-6-Lines
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: max_black = black_count = blocks[:k-1].count('B') for i in range(k-1, len(blocks)): black_count += blocks[i] == 'B' max_black = max(max_black, black_count) black_count -= blocks[i - k + 1] == 'B' return k - max_black
minimum-recolors-to-get-k-consecutive-black-blocks
Python | Sliding Window | 6 Lines
leeteatsleep
0
34
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,559
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2455702/Python-sliding-window
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: result = count = blocks[:k].count('W') for i in range(k, len(blocks)): count += (blocks[i] == 'W') - (blocks[i-k] == 'W') result = min(result, count) return result
minimum-recolors-to-get-k-consecutive-black-blocks
Python, sliding window
blue_sky5
0
34
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,560
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2455429/Sliding-window-one-pass
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: whites = blocks[:k].count("W") ans = whites if ans == 0: return 0 for i in range(k, len(blocks)): whites += (blocks[i] == "W") - (blocks[i - k] == "W") ans = min(ans, whites) if ans == 0: return 0 return ans
minimum-recolors-to-get-k-consecutive-black-blocks
Sliding window, one pass
EvgenySH
0
7
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,561
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2454601/Python3-or-Sliding-Window-Approach
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: #Approach: Just utilize sliding window technique! #Keep track of number of white blocks in current sliding window and once you reach stopping condition: #when you have exactly length of sliding window consisting of k blocks then stop expanding and update current #number of white blocks against the current built-up answer! #in the worst case, we have to flip each and every block if all blocks are white and k == len(blocks) n = len(blocks) #initialize answer! minimum = n L, R = 0, 0 #this variable keeps track of length of current sliding window! length = 0 #variable to keep track of current white blocks white = 0 #as long as R in bounds, initiate sliding window! while R < len(blocks): #process right element! length += 1 cur = blocks[R] if(cur == 'W'): white += 1 #stopping condition: while(length == k): minimum = min(minimum, white) length -= 1 #process left element: if it currently points to white block, decrement it from count or otherwise ignore! if(blocks[L] == 'W'): white -= 1 #shift left pointer one right in sliding window!(shrink) L += 1 #continue expanding R += 1 return minimum
minimum-recolors-to-get-k-consecutive-black-blocks
Python3 | Sliding Window Approach
JOON1234
0
13
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,562
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2454591/Python3-Sliding-window-commented-Solution
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: i = w = front = 0 minimum = 10**6 while i < len(blocks): if blocks[i] =="W": w += 1 # Count of w since we need to repaint them. We can also use B count as well if i-front + 1 == k: # size of window minimum = min(minimum,w) if blocks[front]=="W": w-=1 front += 1 # Front is the index at where our current window starts. i+=1 return minimum
minimum-recolors-to-get-k-consecutive-black-blocks
Python3 Sliding window commented Solution
abhisheksanwal745
0
15
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,563
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2454590/Easiest-solution-in-the-Python-for-beginners-O(n)
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: a=[] for i in range(0,len(blocks)): x=blocks[i:k+i] if len(x)==k: g=x.count("W") a.append(g) else: break return min(a)
minimum-recolors-to-get-k-consecutive-black-blocks
✔️✔️Easiest solution in the Python for beginners O(n) ✔️✔️
giridharan7
0
24
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,564
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2454161/Python3
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: start_index = 0 length = len(blocks) res = float("inf") count = 0 for i in range(start_index, k): if blocks[i] == "W": count += 1 res = min(res, count) for i in range(k, length): if blocks[start_index] == "W": count -= 1 if blocks[i] == "W": count += 1 res = min(res, count) start_index += 1 return res
minimum-recolors-to-get-k-consecutive-black-blocks
[Python3]
zonda_yang
0
32
minimum recolors to get k consecutive black blocks
2,379
0.568
Easy
32,565
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2454195/Python3-O(N)-dp-approach
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: ans = prefix = prev = 0 for i, ch in enumerate(s): if ch == '1': ans = max(prev, i - prefix) prefix += 1 if ans: prev = ans+1 return ans
time-needed-to-rearrange-a-binary-string
[Python3] O(N) dp approach
ye15
49
2,200
time needed to rearrange a binary string
2,380
0.482
Medium
32,566
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2454424/Python-oror-Easy-Approach-oror-Replace-(5-lines)
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: ans = 0 while '01' in s: ans += 1 s = s.replace('01', '10') return ans
time-needed-to-rearrange-a-binary-string
✅Python || Easy Approach || Replace (5 lines)
chuhonghao01
11
551
time needed to rearrange a binary string
2,380
0.482
Medium
32,567
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2677222/PYTHON-or-Beginner-or-Easy-or-81-faster
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: c=0 for i in range(len(s)): if "01" in s: s=s.replace("01","10") c+=1 return(c) ```
time-needed-to-rearrange-a-binary-string
PYTHON | Beginner | Easy | 81% faster
envyTheClouds
1
52
time needed to rearrange a binary string
2,380
0.482
Medium
32,568
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2478370/Python-brute-force-step-by-step-solution-and-small-solution
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: count = 0 temp = "" ones = s.count("1") # get the count of 1 for _ in range(ones): """ make a string with total number of 1 """ temp += "1" while s[:ones] != temp: """ loop through index 0 to count of 1 while the string is not equal to temp string """ left, right = 0, 1 while right < len(s): """ Compare the two index from left to right if they both are equal to "01" if so then replace them and count the number of occurrence """ if s[left : left + 1] + s[right : right + 1] == "01": s = s.replace(s[left : left + 1] + s[right : right + 1], "10") count += 1 left += 1 right += 1 return count
time-needed-to-rearrange-a-binary-string
Python brute force step by step solution & small solution
sezanhaque
1
65
time needed to rearrange a binary string
2,380
0.482
Medium
32,569
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2478370/Python-brute-force-step-by-step-solution-and-small-solution
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: count = 0 while "01" in s: """ While we are getting "01" in the string we will replace them into "10" and count the number of occurrence """ s = s.replace("01", "10") count += 1 return count
time-needed-to-rearrange-a-binary-string
Python brute force step by step solution & small solution
sezanhaque
1
65
time needed to rearrange a binary string
2,380
0.482
Medium
32,570
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2795812/Python-(Simple-Maths)
class Solution: def secondsToRemoveOccurrences(self, s): total = zeros = 0 for i in range(len(s)): zeros += 1 if s[i] == "0" else 0 if s[i] == "1" and zeros: total = max(total+1,zeros) return total
time-needed-to-rearrange-a-binary-string
Python (Simple Maths)
rnotappl
0
14
time needed to rearrange a binary string
2,380
0.482
Medium
32,571
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2618579/Python-Easy-solution
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: ans=zeros=0 for i in range(len(s)): zeros+=1 if s[i] == '0' else 0 if s[i] == '1' and zeros: ans=max(ans+1,zeros) return ans
time-needed-to-rearrange-a-binary-string
Python Easy solution
beingab329
0
44
time needed to rearrange a binary string
2,380
0.482
Medium
32,572
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2540242/O(N)-Solution
class Solution(object): def secondsToRemoveOccurrences(self, s): """ :type s: str :rtype: int """ res = 0 index = 0 pre = 0 for i in range(len(s)): if s[i] == '0': pre = max(pre-1, 0) else: if i == index: index += 1 continue if i-index+pre > res: res = i-index+pre pre += 1 index += 1 return res
time-needed-to-rearrange-a-binary-string
O(N) Solution
ryhurain
0
122
time needed to rearrange a binary string
2,380
0.482
Medium
32,573
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2456430/Python-Solution
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: c=0 while "01" in s: s=s.replace("01","10") c+=1 return c
time-needed-to-rearrange-a-binary-string
Python Solution
a_dityamishra
0
21
time needed to rearrange a binary string
2,380
0.482
Medium
32,574
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2455905/DP-approach-Time-complexity-O(n)-100-fast
class Solution(object): def secondsToRemoveOccurrences(self, s): zeroes = ones = ans = 0 for c in s: if c == "1": if zeroes: ans = max(ans+1,zeroes) ones+=1 else: zeroes+=1 return ans
time-needed-to-rearrange-a-binary-string
DP approach, Time complexity O(n), 100% fast
Virus_003
0
47
time needed to rearrange a binary string
2,380
0.482
Medium
32,575
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2455615/Python3-or-Brute-Force-Approach
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: #Brute Force this! count = 0 while "01" in s: s = s.replace("01", "10") count += 1 return count
time-needed-to-rearrange-a-binary-string
Python3 | Brute Force Approach
JOON1234
0
6
time needed to rearrange a binary string
2,380
0.482
Medium
32,576
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2454499/Python3-or-Brute-force-or-Easy-to-understand
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: seconds = 0 my_list = [*s] my_string = s while '01' in my_string: i = 0 while i < len(my_list) - 1: if my_list[i] == '0' and my_list[i + 1] == '1': my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i] i += 2 else: i += 1 my_string = ''.join(my_list) seconds += 1 return seconds
time-needed-to-rearrange-a-binary-string
Python3 | Brute force | Easy to understand
Amunra43
0
22
time needed to rearrange a binary string
2,380
0.482
Medium
32,577
https://leetcode.com/problems/shifting-letters-ii/discuss/2454404/Python-Cumulative-Sum-oror-Easy-Solution
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: cum_shifts = [0 for _ in range(len(s)+1)] for st, end, d in shifts: if d == 0: cum_shifts[st] -= 1 cum_shifts[end+1] += 1 else: cum_shifts[st] += 1 cum_shifts[end+1] -= 1 cum_sum = 0 for i in range(len(s)): cum_sum += cum_shifts[i] new_code = (((ord(s[i]) + cum_sum) - 97) % 26) + 97 s = s[:i] + chr(new_code) + s[i+1:] return s
shifting-letters-ii
✅ Python Cumulative Sum || Easy Solution
idntk
15
850
shifting letters ii
2,381
0.342
Medium
32,578
https://leetcode.com/problems/shifting-letters-ii/discuss/2465791/Python3-oror-8-lines-letter-indexing-wexplanation-oror-TM%3A-100-60
class Solution: # Here's the plan: # 1) 1a: Initiate an array offsets with length len(s)+1. # 1b: Iterate through shifts and collect the endpts and the direction # of each shift. (Note that 2*(0)-1 = -1 and 2*(1)-1 = 1.) # 1c: Accumulate the elements in offsets to determine the cummulative # offset for each char in s # # 2) 2a: Write the letter index (1-26) of each char of s to a list chNums. # 2b: Add to each letter index its corresponding offset and determine # its new letter index by applying %26. # 2c: Return the result string from chNums. def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: n = len(s) offsets = [0]*(n+1) # <-- 1a for start, end, direction in shifts: # <-- 1b offsets[start]+= 2*direction-1 offsets[end+1]-= 2*direction-1 offsets = accumulate(offsets) # <-- 1c chNums = (ord(ch)-97 for ch in s) # <-- 2a chNums = ((chNum + offset)%26 for chNum, # <-- 2b offset in zip(chNums, offsets)) return ''.join(chr(chNum+97) for chNum in chNums) # <-- 2c
shifting-letters-ii
Python3 || 8 lines, letter indexing, w/explanation || T/M: 100%/ 60%
warrenruud
5
158
shifting letters ii
2,381
0.342
Medium
32,579
https://leetcode.com/problems/shifting-letters-ii/discuss/2492482/Python-3-or-Prefix-Sum-or-Explanation
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: n = len(s) d = collections.Counter() for st, e, right in shifts: d[st] += 1 if right else -1 # Mark at the beginning to indicate everything after it need to be shifted if e+1 < n: # Mark (inversely) at the index after the end, to negate the unnecessary shifts d[e+1] += -1 if right else 1 prefix = [0] # Initialize the prefix array ans = '' for i in range(n): # Use prefix sum style to accumulate all shifts needed, which were carried over from the previous index cur = prefix[-1] + d[i] prefix.append(cur) ans += string.ascii_lowercase[(ord(s[i]) - ord('a') + cur) % 26] return ans
shifting-letters-ii
Python 3 | Prefix Sum | Explanation
idontknoooo
1
84
shifting letters ii
2,381
0.342
Medium
32,580
https://leetcode.com/problems/shifting-letters-ii/discuss/2454506/Python3-Sum-Changes-per-Element
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: n = len(s) dp = [0]*(n + 1) res = "" #Get changes for u, v, w in shifts: if w: dp[u] += 1 dp[v + 1] -= 1 else: dp[u] -= 1 dp[v + 1] += 1 #Prefix sum for idx in range(1, n): dp[idx] += dp[idx - 1] #Apply changes for idx in range(n): res += chr((ord(s[idx]) - ord('a') + dp[idx]) % 26 + ord('a')) return res
shifting-letters-ii
[Python3] Sum Changes per Element
0xRoxas
1
51
shifting letters ii
2,381
0.342
Medium
32,581
https://leetcode.com/problems/shifting-letters-ii/discuss/2454215/Python3-Line-sweep
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: ops = [] for start, end, direction in shifts: direction = 2*direction-1 ops.append((start, direction)) ops.append((end+1, -direction)) ops.sort() ans = [] prefix = ii = 0 for i, ch in enumerate(s): while ii < len(ops) and ops[ii][0] == i: prefix += ops[ii][1] ii += 1 ans.append(chr((ord(ch)-97+prefix)%26+97)) return ''.join(ans)
shifting-letters-ii
[Python3] Line sweep
ye15
1
99
shifting letters ii
2,381
0.342
Medium
32,582
https://leetcode.com/problems/shifting-letters-ii/discuss/2764071/python-3-or-line-sweep-or-O(n)O(n)
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: n = len(s) totalShifts = [0] * (n + 1) for start, end, direction in shifts: if not direction: direction = -1 totalShifts[start] += direction totalShifts[end + 1] -= direction for i in range(1, n): totalShifts[i] += totalShifts[i - 1] res = [] for c, totalShift in zip(s, totalShifts): res.append(chr((ord(c) - 97 + totalShift) % 26 + 97)) return ''.join(res)
shifting-letters-ii
python 3 | line sweep | O(n)/O(n)
dereky4
0
4
shifting letters ii
2,381
0.342
Medium
32,583
https://leetcode.com/problems/shifting-letters-ii/discuss/2668723/Python3-or-Line-Sweep
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: sz=len(s) freq=[0 for i in range(sz+1)] for a,b,c in shifts: if c==1: freq[a]+=1 freq[b+1]-=1 else: freq[a]-=1 freq[b+1]+=1 for i in range(sz+1): freq[i]=freq[i-1]+freq[i] if i>=1 else freq[i] s=list(s) for i in range(sz): s[i]=chr(((ord(s[i])+freq[i]-97)%26)+97) return "".join(s)
shifting-letters-ii
[Python3] | Line Sweep
swapnilsingh421
0
10
shifting letters ii
2,381
0.342
Medium
32,584
https://leetcode.com/problems/shifting-letters-ii/discuss/2455661/Segment-Tree-with-updating-on-range
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: def update(a, x, y, p, v, l, r): """ update at position p """ if x>=r or l>=y: return if x<=l and r<=y: tree[v]["full"] += p tree[v]["value"] += p * (r - l) return v1, v2 = (v<<1), (v<<1) +1 m = (l + r)//2 update(a, x, y, p, v1, l, m) update(a, x, y, p, v2, m, r) tree[v]["value"] = tree[v1]["value"] + tree[v2]["value"] pass # update def query(a, x, y, p, v, l, r): """ query on [x, y) in [0,n) of arr """ if x>=r or l>=y: # [x, y) intersection [l,r) = empty return 0 if x<=l and r <= y: # // [l,r) is a subset of [x,y) return a[v]["value"] + p * (r - l) v1, v2 = (v<<1), (v<<1) +1 p += a[v]["full"] m = (l + r) // 2 q1 = query(a, x, y, p, v1, l, m) q2 = query(a, x, y, p, v2, m, r) return q1 + q2 pass # query n = len(s) tree = [{"value": 0, "full": 0} for _ in range(4*n)] # shifts = sorted(shifts) s0, e0, d0 = shifts[0] p0 = 1 if d0==1 else -1 for si, ei, di in shifts[1:]: pi = 1 if di==1 else -1 if s0==si and e0==ei: p0 += pi elif e0+1==si and p0==pi: e0 = ei else: update(tree, s0, e0+1, p0, 1, 0, n) s0, e0, p0 = si, ei, pi update(tree, s0, e0+1, p0, 1, 0, n) ans = [] for i in range(0, n): di = query(tree, i, i+1, 0, 1, 0, n) pi = (ord(s[i]) - ord('a') + di)%26 # (ord('z') - ord('a') + 1) ans.append(chr(ord('a') + pi)) ans = "".join(ans) # print(ans) # print("="*20) return ans print = lambda *a, **aa: ()
shifting-letters-ii
Segment Tree with updating on range
dntai
0
30
shifting letters ii
2,381
0.342
Medium
32,585
https://leetcode.com/problems/shifting-letters-ii/discuss/2455166/Reverse-Pref-Sum-Diff-Sum
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: b, n = [], len(s) list_s = [0] + [ord(i) - ord('a') for i in s] for i in range(n): b.append(list_s[i + 1] - list_s[i]) for start, end, direction in shifts: if end >= n - 1: b[start] += 1 if direction == 1 else -1 b[start] = (b[start] + 26)%26 else: b[start] += 1 if direction == 1 else -1 b[start] = (b[start] + 26)%26 b[end + 1] -= 1 if direction == 1 else -1 b[end + 1] = (b[end + 1] + 26)%26 res = [0] for i in range(n): res.append(b[i] + res[-1]) return ''.join([chr(97 + i%26) for i in res[1:]])
shifting-letters-ii
Reverse Pref Sum - Diff Sum
Che4pSc1ent1st
0
10
shifting letters ii
2,381
0.342
Medium
32,586
https://leetcode.com/problems/shifting-letters-ii/discuss/2455020/Python3-or-Need-Help-Understanding-Why-I-am-Failing-2nd-example-test-case!
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: #Try brute force! #use a hashmap to keep track of how many times we have to forward or backward shift: #neg value -> shift that many times backwards! #0 -> no shift! #pos -> shift that many times forwards! #initialize hashamp to be 0 shift for each and every index pos! hashmap = {i:0 for i in range(0, len(s))} for start, end, is_f in shifts: #third value is like a boolean flag: if it's forward shift! if(is_f): for j in range(start, end+1): #add 1 to indicate we want to forward shift once more for all indices from start - end! hashmap[j] += 1 continue else: for d in range(start, end+1): hashmap[d] -= 1 continue #once for loop is finishes, simply iterate through indices 0 to len(s) - 1, apply the shift, and add each #and every converted char to built up ans string! ans = "" #for shifting, always modulo total_number_of_shifts by 26 since there are total of 26 lowercase chars and #it wraps around! for a in range(0, len(s)): shifts = hashmap[a] ord_val = ord(s[a]) n = abs(shifts) if shifts == 0: ans += s[a] continue #if positive shifts, make sure it's not 'z'! elif shifts > 0: n = n % 26 #check if 'z' if(ord_val == 127): ans += "".join(chr(97 + (n - 1))) continue else: ans += "".join(chr(ord_val + n)) continue #else case: overall number of shifts is negative! else: #get the magnitude of number of shifts, if neg, and take modulo and that's number of backward shifts #left to do! n = n % 26 #check if it's lowercase 'a' if(ord_val == 97): ans += "".join(chr(127 - (n -1))) continue else: ans += "".join(chr(ord_val - n)) continue return ans
shifting-letters-ii
Python3 | Need Help Understanding Why I am Failing 2nd example test case!
JOON1234
0
20
shifting letters ii
2,381
0.342
Medium
32,587
https://leetcode.com/problems/shifting-letters-ii/discuss/2454613/prefix_sum
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: s = list(s) prefix = defaultdict(int) for i in shifts: prefix[i[0]]+=(2*i[2]-1) prefix[i[1]+1] -=(2*i[2]-1) prefix_sum = 0 for i in range(len(s)): prefix_sum+=prefix[i] s[i] = chr((((ord(s[i])+prefix_sum)-97)%26)+97) return "".join(s)
shifting-letters-ii
prefix_sum
shashichintu
0
17
shifting letters ii
2,381
0.342
Medium
32,588
https://leetcode.com/problems/shifting-letters-ii/discuss/2454423/Secret-Python-Answer-Simple-Sort-Solution
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: change = [[0,0]] * (len(shifts) *2) i = 0 for start,end,dir in shifts: change[i] = [start,1 if dir == 1 else -1] i+=1 change[i] = [end+1,-1 if d == 1 else 1] i+=1 change.sort() res = '' j = 0 add = 0 for i,l in enumerate(s): while j < len(change) and i == change[j][0] : add += change[j][1] j+=1 res += chr((ord(s[i]) + add - ord('a')) %26 + ord('a')) return res
shifting-letters-ii
[Secret Python Answer🤫🐍👌😍] Simple Sort Solution
xmky
0
46
shifting letters ii
2,381
0.342
Medium
32,589
https://leetcode.com/problems/shifting-letters-ii/discuss/2454368/Accumulating-Deltas-for-Ranges-and-then-Processing
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: ops = [0]*(len(s)+1) for start, end, direction in shifts: ops[start] += 1 if direction == 1 else -1 ops[end+1] += -1 if direction == 1 else 1 runningDelta = 0 w = [] for ind, letter in enumerate(s): runningDelta += ops[ind] newLetter = chr( (ord(letter) - ord('a') + runningDelta) % 26 + ord('a')) w.append(newLetter) return "".join(w)
shifting-letters-ii
Accumulating Deltas for Ranges and then Processing
user2867d
0
20
shifting letters ii
2,381
0.342
Medium
32,590
https://leetcode.com/problems/maximum-segment-sum-after-removals/discuss/2454397/Do-it-backwards-O(N)
class Solution: def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]: mp, cur, res = {}, 0, [] for q in reversed(removeQueries[1:]): mp[q] = (nums[q], 1) rv, rLen = mp.get(q+1, (0, 0)) lv, lLen = mp.get(q-1, (0, 0)) total = nums[q] + rv + lv mp[q+rLen] = (total, lLen + rLen + 1) mp[q-lLen] = (total, lLen + rLen + 1) cur = max(cur, total) res.append(cur) return res[::-1] + [0]
maximum-segment-sum-after-removals
Do it backwards O(N)
user9591
29
1,100
maximum segment sum after removals
2,382
0.476
Hard
32,591
https://leetcode.com/problems/maximum-segment-sum-after-removals/discuss/2454234/Python3-Priority-queue
class Solution: def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]: n = len(nums) sl = SortedList([-1, n]) prefix = list(accumulate(nums, initial=0)) mp = {-1 : n} pq = [(-prefix[-1], -1, n)] ans = [] for q in removeQueries: sl.add(q) i = sl.bisect_left(q) lo = sl[i-1] hi = sl[i+1] mp[lo] = q mp[q] = hi heappush(pq, (-(prefix[q]-prefix[lo+1]), lo, q)) heappush(pq, (-(prefix[hi]-prefix[q+1]), q, hi)) while mp[pq[0][1]] != pq[0][2]: heappop(pq) ans.append(-pq[0][0]) return ans
maximum-segment-sum-after-removals
[Python3] Priority queue
ye15
7
476
maximum segment sum after removals
2,382
0.476
Hard
32,592
https://leetcode.com/problems/maximum-segment-sum-after-removals/discuss/2475939/python-3-or-union-find
class Solution: def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]: n = len(nums) res = [0] * n parent = [i for i in range(n)] rank = [1] * n sums = [0] * n def union(i, j): i, j = find(i), find(j) if rank[i] < rank[j]: i, j = j, i parent[j] = i rank[i] += rank[j] sums[i] += sums[j] def find(i): while i != parent[i]: parent[i] = i = parent[parent[i]] return i for i in range(n - 1, 0, -1): j = removeQueries[i] sums[j] = nums[j] if j and sums[j - 1]: union(j, j - 1) if j != n - 1 and sums[j + 1]: union(j, j + 1) res[i - 1] = max(res[i], sums[find(j)]) return res
maximum-segment-sum-after-removals
python 3 | union find
dereky4
0
35
maximum segment sum after removals
2,382
0.476
Hard
32,593
https://leetcode.com/problems/maximum-segment-sum-after-removals/discuss/2454430/Python3-or-Prefix-Sum-and-Bisect-or-O(n-log(n))
class Solution: def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]: running, sum_before = 0, [] for num in nums: running += num sum_before.append(running) sum_before.append(0) # [-1] def get_sum(start, end): return sum_before[end] - sum_before[start - 1] removed, res = [-1, len(nums)], [] max_seg_sums = [float('-inf'), sum(nums)] for i in removeQueries: ins = bisect_left(removed, i) before, after = removed[ins - 1], removed[ins] to_del = bisect_left(max_seg_sums, get_sum(before + 1, after - 1)) del max_seg_sums[to_del] new_l, new_r = get_sum(before + 1, i - 1), get_sum(i + 1, after - 1) res.append(max(max_seg_sums[-1], new_l, new_r)) bisect.insort(removed, i) bisect.insort(max_seg_sums, new_l) bisect.insort(max_seg_sums, new_r) return res
maximum-segment-sum-after-removals
Python3 | Prefix Sum & Bisect | O(n log(n))
ryangrayson
0
48
maximum segment sum after removals
2,382
0.476
Hard
32,594
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456759/Python-oror-Easy-Approach
class Solution: def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int: ans = 0 n = len(energy) for i in range(n): while initialEnergy <= energy[i] or initialExperience <= experience[i]: if initialEnergy <= energy[i]: initialEnergy += 1 ans += 1 if initialExperience <= experience[i]: initialExperience += 1 ans += 1 initialEnergy -= energy[i] initialExperience += experience[i] return ans
minimum-hours-of-training-to-win-a-competition
✅Python || Easy Approach
chuhonghao01
6
460
minimum hours of training to win a competition
2,383
0.41
Easy
32,595
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2722230/Python-Java-Elegant-and-Short-or-One-pass
class Solution: """ Time: O(n) Memory: O(1) """ def minNumberOfHours(self, energy: int, experience: int, energies: List[int], experiences: List[int]) -> int: hours = 0 for eng, exp in zip(energies, experiences): # Adding the missing amount of energy extra_en = max(0, eng - energy + 1) energy += extra_en # Adding the missing amount of experience extra_ex = max(0, exp - experience + 1) experience += extra_ex energy -= eng experience += exp hours += extra_en + extra_ex return hours
minimum-hours-of-training-to-win-a-competition
Python, Java Elegant & Short | One pass
Kyrylo-Ktl
2
103
minimum hours of training to win a competition
2,383
0.41
Easy
32,596
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456615/Python3-simulation
class Solution: def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int: ans = 0 for x, y in zip(energy, experience): if initialEnergy <= x: ans += x + 1 - initialEnergy initialEnergy = x + 1 if initialExperience <= y: ans += y + 1 - initialExperience initialExperience = y + 1 initialEnergy -= x initialExperience += y return ans
minimum-hours-of-training-to-win-a-competition
[Python3] simulation
ye15
2
78
minimum hours of training to win a competition
2,383
0.41
Easy
32,597
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2834506/Simple-python-solution
class Solution: def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int: energy_gain = experience_gain = 0 for ene in energy: if initialEnergy - ene < 1: energy_gain += ene + 1 - initialEnergy initialEnergy = ene + 1 initialEnergy -= ene for exp in experience: if initialExperience - exp < 1: experience_gain += exp + 1 - initialExperience initialExperience = exp + 1 initialExperience += exp return energy_gain + experience_gain
minimum-hours-of-training-to-win-a-competition
Simple python solution
StacyAceIt
0
1
minimum hours of training to win a competition
2,383
0.41
Easy
32,598
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2816970/python3-solution
class Solution: def minNumberOfHours(self, initialEnergy: int, ie: int, energy: List[int], experience: List[int]) -> int: hours=sum(energy)-initialEnergy+1 if hours<0: hours=0 for x in experience: if ie>x: ie=ie+x else: hours=hours+(x-ie+1) ie=ie+(x-ie+1) ie=ie+x return hours
minimum-hours-of-training-to-win-a-competition
python3 solution
giftyaustin
0
1
minimum hours of training to win a competition
2,383
0.41
Easy
32,599