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/grid-illumination/discuss/1497659/Beginner-Friendly-oror-96-faster-oror-Easy-to-understand
class Solution: def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]: row,col,dig1,dig2 = defaultdict(int),defaultdict(int),defaultdict(int),defaultdict(int) def switch(i,j,isOn): val = 1 if isOn else -1 row[i] += val col[j] += val dig1[i+j]+=val dig2[i-j]+=val def check(x,y): return 1 if row[x] or col[y] or dig1[x+y] or dig2[x-y] else 0 seen = set() for x,y in set([tuple(lamp) for lamp in lamps]): seen.add((x,y)) switch(x,y,1) res = [] for x,y in queries: res.append(check(x,y)) for dx,dy in [(0,0),(0,1),(0,-1),(1,0),(-1,0),(1,1),(-1,-1),(1,-1),(-1,1)]: if (x+dx,y+dy) in seen: seen.remove((x+dx,y+dy)) switch(x+dx,y+dy,0) return res
grid-illumination
๐Ÿ“Œ๐Ÿ“Œ Beginner-Friendly || 96% faster || Easy-to-understand ๐Ÿ
abhi9Rai
0
58
grid illumination
1,001
0.362
Hard
16,300
https://leetcode.com/problems/find-common-characters/discuss/721548/Python-Faster-than-77.67-and-Better-Space-than-86.74
class Solution: def commonChars(self, A: List[str]) -> List[str]: alphabet = string.ascii_lowercase d = {c: 0 for c in alphabet} for k, v in d.items(): d[k] = min([word.count(k) for word in A]) res = [] for c, n in d.items(): if n > 0: res += [c] * n return res
find-common-characters
Python Faster than 77.67% and Better Space than 86.74
parkershamblin
8
997
find common characters
1,002
0.683
Easy
16,301
https://leetcode.com/problems/find-common-characters/discuss/1037047/Python3-easy-solution
class Solution: def commonChars(self, A: List[str]) -> List[str]: ans = [] for i in set(A[0]): x = [] for j in A: x.append(j.count(i)) a = 0 while a < min(x): ans.append(i) a += 1 return ans
find-common-characters
Python3 easy solution
EklavyaJoshi
4
421
find common characters
1,002
0.683
Easy
16,302
https://leetcode.com/problems/find-common-characters/discuss/1150217/Python3-Simple-And-Readable-Solution
class Solution: def commonChars(self, A: List[str]) -> List[str]: arr = [] for i in set(A[0]): ans = [A[0].count(i)] for j in A[1:]: if(i in j): ans.append(j.count(i)) if(len(ans) == len(A)): arr += ([i] * min(ans)) return arr
find-common-characters
[Python3] Simple And Readable Solution
Lolopola
3
279
find common characters
1,002
0.683
Easy
16,303
https://leetcode.com/problems/find-common-characters/discuss/1310060/O(n2)-Solution(python3)
class Solution: def commonChars(self, words: List[str]) -> List[str]: if len(words)==1: return list(*words) output=[] for i in words[0]: temp=0 for j,k in enumerate(words[1:]): if i in k: words[j+1]=k.replace(i,"_",1) temp+=1 if temp==len(words)-1: output.append(i) return output
find-common-characters
O(n^2) Solution(python3)
_jorjis
2
276
find common characters
1,002
0.683
Easy
16,304
https://leetcode.com/problems/find-common-characters/discuss/1053340/Python-Faster-than-98-Easy-to-Understand
class Solution: def commonChars(self, A: List[str]) -> List[str]: A.sort(key=lambda x: len(x)) # in-place sort by shortest to longest length letter_count = {letter: A[0].count(letter) for letter in A[0]} # dict for shortest word: key = letter, value=count of letter for letter in letter_count.keys(): for word in A[1:]: # No need to check A[0] as that is the reference point (i.e shortest word) tmp_count = word.count(letter) if tmp_count == 0: # If letter not found in word, skip this letter letter_count[letter] = 0 break if tmp_count < letter_count[letter]: letter_count[letter] = word.count(letter) return [letter for letter, count in letter_count.items() for _ in range(count)]
find-common-characters
Python Faster than 98% Easy to Understand
peatear-anthony
2
628
find common characters
1,002
0.683
Easy
16,305
https://leetcode.com/problems/find-common-characters/discuss/355203/Python-Concise-Solution-which-beats-97
class Solution: def commonChars(self, A: List[str]) -> List[str]: spec=A[0] answer=[] for each in spec: flag=True for each_str in A[1:]: if each in each_str: continue else: flag=False break if flag: answer.append(each) for i in range(1,len(A)): A[i]=A[i].replace(each,"",1) return answer
find-common-characters
Python Concise Solution which beats 97%
Sprinter1999
2
661
find common characters
1,002
0.683
Easy
16,306
https://leetcode.com/problems/find-common-characters/discuss/2619650/two-dictionaries-python
class Solution: def commonChars(self, words: List[str]) -> List[str]: d1=defaultdict(int) for l in range(len(words[0])): z =words[0][l] d1[z]+=1 for i in range(1,len(words)): d2=defaultdict(int) z=words[i] for l in z: d2[l]+=1 for k in d1: d1[k]=min(d1[k],d2[k]) ret=[] for k in sorted(d1): while(d1[k]>0): ret.append(k) d1[k]-=1 return ret
find-common-characters
two dictionaries python
abhayCodes
1
36
find common characters
1,002
0.683
Easy
16,307
https://leetcode.com/problems/find-common-characters/discuss/1990526/easy-python-code
class Solution: def commonChars(self, words: List[str]) -> List[str]: d = [] n = len(words) for i in words[0]: flag = 0 for j in words: if i not in j: flag = 1 break if flag == 0: d.append(i) for k in range(len(words)): for l in range(len(words[k])): if words[k][l] == i: words[k] = words[k][:l] + words[k][l+1:] break return d
find-common-characters
easy python code
dakash682
1
379
find common characters
1,002
0.683
Easy
16,308
https://leetcode.com/problems/find-common-characters/discuss/1793561/85-lesser-memory-or-Simple-python-solution
class Solution: def commonChars(self, words: List[str]) -> List[str]: f = words[0] if len(words)==1: return list(f) words = [list(i) for i in words[1:]] lst = [] c= 0 for i in f: for j in range(len(words)): if i in words[j]: words[j].remove(i) c += 1 if c == len(words): lst.append(i) c = 0 return lst
find-common-characters
85% lesser memory | Simple python solution
Coding_Tan3
1
203
find common characters
1,002
0.683
Easy
16,309
https://leetcode.com/problems/find-common-characters/discuss/1563368/Python3-dollarolution
class Solution: def commonChars(self, words: List[str]) -> List[str]: d, d1, l = {}, {}, [] for i in words[0]: if i not in d: d[i] = 1 else: d[i] += 1 for i in words[1:]: d1 = {} for j in i: if j not in d: continue elif j in d and j not in d1: d1[j] = 1 elif j in d1 and d[j] > d1[j]: d1[j] += 1 d = d1 for i in d1: for j in range(d1[i]): l.append(i) return l
find-common-characters
Python3 $olution
AakRay
1
339
find common characters
1,002
0.683
Easy
16,310
https://leetcode.com/problems/find-common-characters/discuss/2847921/Python-Solution
class Solution: def commonChars(self, words: List[str]) -> List[str]: res=[] for i in words[0]: k=0 for j in range(1,len(words)): words[j]=list(words[j]) if(i not in words[j]): k+=1 else: words[j].remove(i) if(k==0): res.append(i) return res
find-common-characters
Python Solution
CEOSRICHARAN
0
1
find common characters
1,002
0.683
Easy
16,311
https://leetcode.com/problems/find-common-characters/discuss/2840096/Python3-Beats-98-or-Optimized-lee215's-code
class Solution: def commonChars(self, words: List[str]) -> List[str]: if len(words) == 1: return list(words) r = collections.Counter(words[0]) for word in words[1:]: r &amp;= collections.Counter(word) return list(r.elements())
find-common-characters
[Python3] Beats 98% | Optimized lee215's code
m0nxt3r
0
2
find common characters
1,002
0.683
Easy
16,312
https://leetcode.com/problems/find-common-characters/discuss/2831873/Python-Solution-Hashmap-oror-Explained
class Solution: def commonChars(self, words: List[str]) -> List[str]: l=[] for i in range(len(words[0])): #select words from words[0] r=words[0][i] c=1 #count the same character as r in every other remaining strings in words for j in range(1,len(words)): if r in words[j]: c+=1 words[j]=words[j].replace(r,"",1) #delete that r from the string #if count of the particular character is equal to len(words) #that means every string containg it if c==len(words): l.append(r) return l
find-common-characters
Python Solution - Hashmap || Explainedโœ”
T1n1_B0x1
0
2
find common characters
1,002
0.683
Easy
16,313
https://leetcode.com/problems/find-common-characters/discuss/2724687/Easy-Python-Solution
class Solution: def commonChars(self, words: List[str]) -> List[str]: op = [] check = words[0] new_lst = words for i in check: cnt=0 nxt_lst = [] for j in new_lst: if i in j: nxt_lst.append(j.replace(i,'',1)) cnt+=1 else: nxt_lst.append(j) new_lst = nxt_lst if cnt==len(words): op.append(i) return op
find-common-characters
Easy Python Solution
BAparna97
0
13
find common characters
1,002
0.683
Easy
16,314
https://leetcode.com/problems/find-common-characters/discuss/2603929/Python-solution-O(n)
class Solution: def commonChars(self, words: List[str]) -> List[str]: common_chs = set(words[0]) for i in range(1, len(words)): common_chs = set(words[i]).intersection(common_chs) dict_count = {} for word in words: mini_dict = {} for ch in word: if ch not in common_chs: continue if ch in mini_dict: mini_dict[ch] += 1 else: mini_dict[ch] = 1 for ch, cnt in mini_dict.items(): if ch in dict_count: dict_count[ch].add(cnt) else: dict_count[ch] = {cnt} result = [] for char, set_cnts in dict_count.items(): for _ in range(min(set_cnts)): result.append(char) return result
find-common-characters
Python solution O(n)
samanehghafouri
0
75
find common characters
1,002
0.683
Easy
16,315
https://leetcode.com/problems/find-common-characters/discuss/2473907/Python-or-Counter-or-2-versions
class Solution: def commonChars(self, words: List[str]) -> List[str]: res = reduce(lambda x, y: Counter(x) &amp; Counter(y), words) return res.elements()
find-common-characters
Python | Counter | 2 versions
Wartem
0
152
find common characters
1,002
0.683
Easy
16,316
https://leetcode.com/problems/find-common-characters/discuss/2439776/Python-Beginner-Friendly
class Solution: def commonChars(self, words: List[str]) -> List[str]: x=words.pop() res=[] for i in x: for j in range(len(words)): if i not in words[j]:break words[j]=words[j].replace(i,"",1) else:res.append(i) return res
find-common-characters
Python Beginner Friendly
imamnayyar86
0
186
find common characters
1,002
0.683
Easy
16,317
https://leetcode.com/problems/find-common-characters/discuss/2420209/Simple-and-fast-python3-solution-88-faster
class Solution: def commonChars(self, words: List[str]) -> List[str]: res = [] for _ in words[0]: if all(_ in __ for __ in words[1:]): # okay, all strings have the same char, but # some of them have more than one res.append(_) # so we need to update other strings and remove # the char we found words[1:] = [__.replace(_,'',1) for __ in words[1:]] return res
find-common-characters
Simple and fast python3 solution ๐Ÿš€๐Ÿš€๐Ÿš€ 88% faster ๐Ÿ‘Œ
TheCodeBeer
0
117
find common characters
1,002
0.683
Easy
16,318
https://leetcode.com/problems/find-common-characters/discuss/1982521/Pythonor-Dictionary-or-min-or-hash-table
class Solution: def commonChars(self, words: List[str]) -> List[str]: word0 = Counter(words[0]) print(word0) for key in word0.keys(): for i in range(0,len(words)): if key in words[i]: word0[key] = min(word0[key],words[i].count(key)) else: word0[key] = 0 output = '' for k , v in word0.items(): if v >= 1: output += k * v return list(output)
find-common-characters
Python| Dictionary | min | hash table
user4774i
0
139
find common characters
1,002
0.683
Easy
16,319
https://leetcode.com/problems/find-common-characters/discuss/1848277/Python-Simple-and-Concise!
class Solution(object): def commonChars(self, words): counters = map(Counter, words) counter = reduce(and_, counters) return counter.elements()
find-common-characters
Python - Simple and Concise!
domthedeveloper
0
278
find common characters
1,002
0.683
Easy
16,320
https://leetcode.com/problems/find-common-characters/discuss/1848277/Python-Simple-and-Concise!
class Solution(object): def commonChars(self, words): return reduce(and_, map(Counter, words)).elements()
find-common-characters
Python - Simple and Concise!
domthedeveloper
0
278
find common characters
1,002
0.683
Easy
16,321
https://leetcode.com/problems/find-common-characters/discuss/1833423/Python3-solution
class Solution: def commonChars(self, words: List[str]) -> List[str]: result = [] first = words.pop(0) words_len = len(words) for char in first: if len(list(filter(lambda x: char in x, words))) == words_len: result.append(char) words = list(map(lambda x: x.replace(char, '', 1), words)) return result
find-common-characters
Python3 solution
hgalytoby
0
192
find common characters
1,002
0.683
Easy
16,322
https://leetcode.com/problems/find-common-characters/discuss/1833423/Python3-solution
class Solution: def commonChars(self, words: List[str]) -> List[str]: result = [] first = words.pop(0) for char in first: add = False for index, word in enumerate(words): if char in word: words[index] = word.replace(char, '', 1) add = True else: add = False break if add: result.append(char) return result
find-common-characters
Python3 solution
hgalytoby
0
192
find common characters
1,002
0.683
Easy
16,323
https://leetcode.com/problems/find-common-characters/discuss/1819917/Python3-Solution-with-using-hashamp
class Solution: def _get(self, sets, alpha): cnt = float('inf') for _set in sets: if alpha not in _set: return 0 cnt = min(cnt, _set[alpha]) return cnt def commonChars(self, words: List[str]) -> List[str]: sets = [] for word in words: d = collections.defaultdict(int) for c in word: d[c] += 1 sets.append(d) res = [] alphas = 'abcdefghijklmnopqrstuvwxyz' for alpha in alphas: present_cnt = self._get(sets, alpha) res += [alpha] * present_cnt return res
find-common-characters
[Python3] Solution with using hashamp
maosipov11
0
164
find common characters
1,002
0.683
Easy
16,324
https://leetcode.com/problems/find-common-characters/discuss/1757073/Python3-solution
class Solution: def commonChars(self, words: List[str]) -> List[str]: words_len = len(words) if words_len == 1: return list(words[0]) letters = list(words[0]) check_words = words[1:] words_len -= 1 result = "" for l in letters: letter_in_all_word = False for word_index in range(words_len): if l in check_words[word_index]: letter_in_all_word = True check_words[word_index] = check_words[word_index].replace(l, "", 1) else: letter_in_all_word = False break if letter_in_all_word: result += l return list(result)
find-common-characters
Python3 solution
khalidhassan3011
0
225
find common characters
1,002
0.683
Easy
16,325
https://leetcode.com/problems/find-common-characters/discuss/1738745/Python3-99.6-or-Detailed-Commented-or-Beginenr-Friendly
class Solution: def commonChars(self, words: List[str]) -> List[str]: # build a filter based on the first word w = words[0] d = Counter(w) for s in words: ds = Counter(s) del_list = [] for k in d.keys(): if not k in ds.keys(): del_list.append(k) # 1. remove all the difference (d.keys - d intersect ds) for dl in del_list: del d[dl] # 2. update the existing letter's frequency for k, v in ds.items(): if k in d.keys() and ds[k] <= d[k]: d[k] = ds[k] ans = [] # populate ans from the original filter for k, v in d.items(): for _ in range(v): ans.append(k) return ans
find-common-characters
Python3 99.6% | Detailed Commented | Beginenr Friendly
doneowth
0
314
find common characters
1,002
0.683
Easy
16,326
https://leetcode.com/problems/find-common-characters/discuss/1592045/Python-Solution-without-Collections
class Solution: def commonChars(self, words: List[str]) -> List[str]: cchars={} res = [] first = words[0] inter = set(first) #Finds the characters common to all words for i in range(1,len(words)): new = set(first) &amp; set(words[i]) if inter != new: inter &amp;= new #Create a dict with occurence for each common character for i in range(0,len(words)): for j in inter: val = words[i].count(j) if j not in cchars: cchars[j] = val else: if val < cchars[j]: cchars[j] = val #Returns a list for k in cchars: cnt = cchars[k] while cnt !=0: res.append(k) cnt-=1 return res
find-common-characters
Python Solution without Collections
kravisha
0
271
find common characters
1,002
0.683
Easy
16,327
https://leetcode.com/problems/find-common-characters/discuss/1581531/described-python-solution-runtime-(36-ms-greater97.94)-memory-(14.1-MB-less95.88)
class Solution: def commonChars(self, words: List[str]) -> List[str]: freq = {} for c in words[0]: freq[c] = freq.get(c, 0) + 1 for w in words[1:]: for k, v in freq.items(): if k in w: freq[k] = min(v, w.count(k)) else: freq[k] = 0 ans = [] for k,v in freq.items(): ans.extend([k] * v) return(ans)
find-common-characters
described python solution, runtime (36 ms, >97.94%), memory (14.1 MB, <95.88%)
motyl
0
192
find common characters
1,002
0.683
Easy
16,328
https://leetcode.com/problems/find-common-characters/discuss/1578505/ez-python-on-solution
class Solution: def commonChars(self, words: List[str]) -> List[str]: cache = [] for i in range(len(words)): cache.append([0] * 26) for i in range(len(words)): word = words[i] for char in word: cache[i][ord(char)-ord('a')] += 1 output = [] for i in range(26): curr_comm = len(words) for j in range(len(words)): curr_comm = min(curr_comm,cache[j][i]) for j in range(curr_comm): output.append(chr(i+ord('a'))) return output
find-common-characters
ez python on solution
yingziqing123
0
115
find common characters
1,002
0.683
Easy
16,329
https://leetcode.com/problems/find-common-characters/discuss/1506730/python-3-oror-beginner-oror-easy-oror-9884
class Solution: def commonChars(self, words: List[str]) -> List[str]: if len(words)==1: return list(words[0]) output=list(words[0]) for word in words[1:]: temp=[] for ch in output: if ch in word: temp.append(ch) word=word.replace(ch,"*",1) else: continue output=temp return output
find-common-characters
python 3 || beginner || easy || 98%,84%
minato_namikaze
0
360
find common characters
1,002
0.683
Easy
16,330
https://leetcode.com/problems/find-common-characters/discuss/1386001/Python3-Faster-Than-98.81-Memory-Less-Than-85.47
class Solution: def commonChars(self, words: List[str]) -> List[str]: s = set(words[0]) for i in words[1:]: s = s &amp; set(i) v = [] s = list(s) for i in s: mn = 101 for z in words: mn = min(mn, z.count(i)) for j in range(mn): v.append(i) return v
find-common-characters
Python3 Faster Than 98.81%, Memory Less Than 85.47%
Hejita
0
225
find common characters
1,002
0.683
Easy
16,331
https://leetcode.com/problems/find-common-characters/discuss/1379555/Python-Using-Dict-faster-than-88.00-of-Python3
class Solution: def commonChars(self, n: List[str]) -> List[str]: l =len(n) d = {} for x in n: for y in set(x): if y not in d: d[y] = [x.count(y)] else: d[y].append(x.count(y)) res = [] for x, y in d.items(): if len(y) >= l: z = min(y) if z > 1: for _ in range(z): res.append(x) else: res.append(x) return(res)
find-common-characters
[Python] Using Dict, faster than 88.00% of Python3
sushil021996
0
148
find common characters
1,002
0.683
Easy
16,332
https://leetcode.com/problems/find-common-characters/discuss/1275165/Python-Faster-than-86-or-Use-ord-function
class Solution: def commonChars(self, words: List[str]) -> List[str]: temp = [] for word in words: les = [0] * 26 for char in word: les[ord(char) - ord('a')] += 1 temp.append(les) # zip fuction => list(zip([1,2,3],[4,5,6])) = [(1, 4), (2, 5), (3, 6)] # zip => It is to count the number of occurrences of the same letter of each word and group them into the same array # *temp => * unpack array record_value = list(zip(*temp)) ans = [] for i,v in enumerate(record_value): # use the min value to express that this word appears at least several times in each word for _ in range(min(v)): ans.append(chr(ord('a') + i)) return ans
find-common-characters
Python Faster than 86 % | Use ord function
doimustz
0
226
find common characters
1,002
0.683
Easy
16,333
https://leetcode.com/problems/find-common-characters/discuss/1204027/python-easy-solution-or-No-extra-DS-used
class Solution: def commonChars(self, A: List[str]) -> List[str]: letters = list(A[0]) for i in range(1,len(A)): j=0 while j < len(letters): if letters[j] not in A[i]: letters.remove(letters[j]) else: A[i] = A[i].replace(letters[j],"",1) j = j+1 return letters
find-common-characters
[python] easy-solution | No extra DS used
arkumari2000
0
357
find common characters
1,002
0.683
Easy
16,334
https://leetcode.com/problems/find-common-characters/discuss/1139150/Python-pythonic-solution
class Solution: def commonChars(self, A: List[str]) -> List[str]: result = [] # iterrate set of shortest word for ch in set(min(A, key=len)): result.extend(ch for _ in range(min([word.count(ch) for word in A], default=0))) return result
find-common-characters
[Python], pythonic solution
cruim
0
201
find common characters
1,002
0.683
Easy
16,335
https://leetcode.com/problems/find-common-characters/discuss/786642/Python3-solution-easy-to-understand-92.42-faster!
class Solution: def commonChars(self, A: List[str]) -> List[str]: c = None for i in range(len(A)): if c != None: x = c c = Counter(A[i]) # Finding intersection of dictionaries newc = x &amp; c c = newc continue c = Counter(A[i]) news = "" for x in c: news += str(x)*newc[x] return list(news)
find-common-characters
Python3 solution, easy-to-understand; 92.42% faster!
rocketrikky
0
184
find common characters
1,002
0.683
Easy
16,336
https://leetcode.com/problems/find-common-characters/discuss/367553/Python-solution-beats-98
class Solution: def commonChars(self, A: List[str]) -> List[str]: alpha = list(A[0]) A = list(map(list,A)) n = len(A) result = [] for c in alpha: for i in range(1,n): s = A[i] if c not in s: break else: s.remove(c) else: result.append(c) return result
find-common-characters
Python solution beats 98%
oumoussmehdi
0
201
find common characters
1,002
0.683
Easy
16,337
https://leetcode.com/problems/find-common-characters/discuss/305744/Python-solution-using-frequency-maps
class Solution: def commonChars(self, A: List[str]) -> List[str]: n = len(A) if n == 0: return [] master = None for word in A: freq = get_freq(word) if master is None: master = freq else: master = get_new_master(master, freq) output = [] for char in master: output = output + [char]*master[char] return output def get_new_master(m, s): dict = {} for char in m: if char in s: if s[char] >= m[char]: dict[char] = m[char] else: dict[char] = s[char] return dict def get_freq(word): dict = {} for char in word: if char in dict: dict[char]+=1 else: dict[char] = 1 return dict
find-common-characters
Python solution using frequency maps
nzelei
0
179
find common characters
1,002
0.683
Easy
16,338
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1291378/python-solution-using-stack
class Solution: def isValid(self, s: str) -> bool: stack=[] for i in s: if i == 'a':stack.append(i) elif i=='b': if not stack:return False else: if stack[-1]=='a':stack.pop() else:return False stack.append(i) else: if not stack:return False else: if stack[-1]=='b':stack.pop() else:return False return len(stack)==0
check-if-word-is-valid-after-substitutions
python solution using stack
chikushen99
2
94
check if word is valid after substitutions
1,003
0.582
Medium
16,339
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/2238315/EasySimple-Stack-And-String-Replace-Approaches
class Solution: def isValid(self, s: str) -> bool: incomplete = True while incomplete: if 'abc' in s: s= s.replace('abc','') else: incomplete = False return s == ''
check-if-word-is-valid-after-substitutions
[Easy]Simple Stack And String Replace Approaches
ankitshetty
1
54
check if word is valid after substitutions
1,003
0.582
Medium
16,340
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/2238315/EasySimple-Stack-And-String-Replace-Approaches
class Solution: def isValid(self, s: str) -> bool: stack = [] for i in s: if i == 'c' and len(stack) >= 2 and stack[-1] == 'b' and stack[-2] == 'a': stack.pop() stack.pop() else: stack.append(i) if ''.join(stack) == 'abc': stack = [] return stack == []
check-if-word-is-valid-after-substitutions
[Easy]Simple Stack And String Replace Approaches
ankitshetty
1
54
check if word is valid after substitutions
1,003
0.582
Medium
16,341
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1793602/98.67-Lesser-Memory-or-only-3-lines-of-code-or-Very-simple-python-Solution
class Solution: def isValid(self, s: str) -> bool: while("abc" in s): s = s.replace("abc","") # continuously replace "abc" by "". By the end if we end up with "", then the word is valid. return s == ""
check-if-word-is-valid-after-substitutions
โœ”98.67% Lesser Memory | only 3 lines of code | Very simple python Solution
Coding_Tan3
1
58
check if word is valid after substitutions
1,003
0.582
Medium
16,342
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/2835036/easy-python-solution
class Solution: def isValid(self, s: str) -> bool: while len(s) > 0 : if 'abc' in s : s = s.replace('abc', '') else : return False return True
check-if-word-is-valid-after-substitutions
easy python solution
sghorai
0
3
check if word is valid after substitutions
1,003
0.582
Medium
16,343
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/2794355/python-super-easy-using-stack
class Solution: def isValid(self, s: str) -> bool: if s[0] != "a": return False stack = [] for i in s: if i == "c": if not stack: return False prev = i pop_count = 0 while stack and ord(prev) - ord(stack[-1]) == 1: prev = stack[-1] stack.pop() pop_count +=1 if pop_count != 2: return False else: stack.append(i) return not stack
check-if-word-is-valid-after-substitutions
python super easy using stack
harrychen1995
0
2
check if word is valid after substitutions
1,003
0.582
Medium
16,344
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/2673561/Python-clean-and-concise
class Solution: def isValid(self, s: str) -> bool: while s: temp = s.replace("abc", "") if temp == s: return False else: s = temp return True
check-if-word-is-valid-after-substitutions
Python - clean and concise
phantran197
0
2
check if word is valid after substitutions
1,003
0.582
Medium
16,345
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/2661248/Short-and-Clean-Python-Solution
class Solution: def isValid(self, s: str) -> bool: while "abc" in s: s = s.replace("abc", "") return s == ""
check-if-word-is-valid-after-substitutions
Short and Clean Python Solution
emrecoltu
0
3
check if word is valid after substitutions
1,003
0.582
Medium
16,346
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/2334578/Easy-python-solution-Noob-must-watch-and-upvote
class Solution: def isValid(self, s: str) -> bool: ans = '' for i in s: ans+=i while len(ans)>=3: if ans[-3:]=="abc": ans=ans[0:-3] else: break if ans=='': return True else: return False
check-if-word-is-valid-after-substitutions
Easy python solution Noob must watch and upvote
Brillianttyagi
0
36
check if word is valid after substitutions
1,003
0.582
Medium
16,347
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/2133703/Easy-Python3
class Solution: def isValid(self, s: str) -> bool: while True: if 'abc' in s: s = s.replace('abc','') elif len(s) == 0: return True else: return False
check-if-word-is-valid-after-substitutions
Easy Python3
jayeshmaheshwari555
0
41
check if word is valid after substitutions
1,003
0.582
Medium
16,348
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1998113/ororPYTHON-SOL-oror-STACK-oror-WELL-EXPLAINED-oror-EASY-oror-FAST-oror
class Solution: def isValid(self, s: str) -> bool: stack = [] for i in s: if i == "c" and len(stack) > 1 and stack[-1] == 'b' and stack[-2] == 'a': stack.pop() stack.pop() else: stack.append(i) return stack == []
check-if-word-is-valid-after-substitutions
||PYTHON SOL || STACK || WELL EXPLAINED || EASY || FAST ||
reaper_27
0
55
check if word is valid after substitutions
1,003
0.582
Medium
16,349
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1934252/python-3-oror-stack-solution-oror-O(n)O(n)
class Solution: def isValid(self, s: str) -> bool: stack = [] for c in s: if c == 'a': stack.append(c) elif c == 'b': if not stack or stack[-1] != 'a': return False stack[-1] = 'ab' elif not stack or stack.pop() != 'ab': return False return not stack
check-if-word-is-valid-after-substitutions
python 3 || stack solution || O(n)/O(n)
dereky4
0
53
check if word is valid after substitutions
1,003
0.582
Medium
16,350
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1498519/Python-oror-Easy-Solution-oror-Beat-~-99.6
class Solution: def isValid(self, s: str) -> bool: while "abc" in s: s = s.replace("abc", "") if s == "": return (True) return (False)
check-if-word-is-valid-after-substitutions
Python || Easy Solution || Beat ~ 99.6%
naveenrathore
0
58
check if word is valid after substitutions
1,003
0.582
Medium
16,351
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1480073/Python3-solution-using-stack
class Solution: def isValid(self, s: str) -> bool: st = [] for i in s: st.append(i) while len(st) > 2: flag = False i = 2 while i < len(st): if st[i] == 'c' and st[i-1] == 'b' and st[i-2] == 'a': flag = True st.pop(i) st.pop(i-1) st.pop(i-2) i += 1 if not flag: return False return True if len(st) == 0 else False
check-if-word-is-valid-after-substitutions
Python3 solution using stack
EklavyaJoshi
0
36
check if word is valid after substitutions
1,003
0.582
Medium
16,352
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1326366/2-liner-Faster-than-~80
class Solution: def isValid(self, s: str) -> bool: while "abc" in s : s = s.replace("abc","") return not s
check-if-word-is-valid-after-substitutions
2 liner , Faster than ~80%
abhijeetgupto
0
47
check if word is valid after substitutions
1,003
0.582
Medium
16,353
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1048410/Python3-Solution
class Solution: def isValid(self, s: str) -> bool: def abc(s): mil=0 for i in range(len(s)-2): if s[i:i+3]=="abc": mil=1 s=s[:i]+s[i+3:] if s=="": return True else: return abc(s) if mil==0: return False return abc(s)
check-if-word-is-valid-after-substitutions
Python3 Solution
samarthnehe
0
62
check if word is valid after substitutions
1,003
0.582
Medium
16,354
https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/985317/Python3-stack-O(N)
class Solution: def isValid(self, s: str) -> bool: stack = [] for c in s: if c == "c" and stack[-2:] == ["a", "b"]: stack.pop() stack.pop() else: stack.append(c) return not stack
check-if-word-is-valid-after-substitutions
[Python3] stack O(N)
ye15
0
63
check if word is valid after substitutions
1,003
0.582
Medium
16,355
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1793625/Python-3-Very-typical-sliding-window-%2B-hashmap-problem.
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: left = 0 answer = 0 counts = {0: 0, 1: 0} for right, num in enumerate(nums): counts[num] += 1 while counts[0] > k: counts[nums[left]] -= 1 left += 1 curr_window_size = right - left + 1 answer = max(answer, curr_window_size) return answer
max-consecutive-ones-iii
[Python 3] Very typical sliding window + hashmap problem.
seankala
5
152
max consecutive ones iii
1,004
0.634
Medium
16,356
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247678/Python-3-Solution%3A-sliding-window-for-zeros'-indexes.-Detailed-explanation-included.
class Solution: def longestOnes(self, A: List[int], K: int) -> int: zero_index = [i for i, v in enumerate(A) if v == 0] if K >= len(zero_index): return len(A) res = 0 for i in range(0, len(zero_index) - K + 1): one_start = zero_index[i-1] + 1 if i > 0 else 0 one_end = zero_index[i+K] - 1 if i+K < len(zero_index) else len(A) - 1 res = max(res, one_end - one_start + 1) return res
max-consecutive-ones-iii
Python 3 Solution: sliding window for zeros' indexes. Detailed explanation included.
jinjiren
4
732
max consecutive ones iii
1,004
0.634
Medium
16,357
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2794365/Beats-98.68-!-Simple-moving-window-without-shrinking-window-size
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: l=r=0 for r in range(len(nums)): if nums[r] == 0: k-=1 if k<0: if nums[l] == 0: k+=1 l+=1 return r-l+1
max-consecutive-ones-iii
Beats 98.68% ! Simple moving window without shrinking window size
avinash_konduri
1
91
max consecutive ones iii
1,004
0.634
Medium
16,358
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2194773/Python3-SlidingWindow-O(n)-oror-O(1)
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: firstStart, secondStart = 0, 0 maxWindow = float('-inf') while firstStart < len(nums): if nums[firstStart] == 0: k -= 1 if k < 0: if nums[secondStart] == 0: k += 1 secondStart += 1 firstStart += 1 maxWindow = max(maxWindow, (firstStart - secondStart)) return maxWindow
max-consecutive-ones-iii
Python3 SlidingWindow O(n) || O(1)
arshergon
1
59
max consecutive ones iii
1,004
0.634
Medium
16,359
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1602308/Easy-to-understand-Python-sliding-window-solution
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: p1,p2,res,seenZeros=0,0,0,0 while p2<len(nums): if nums[p2]==0: seenZeros+=1 while seenZeros>k: seenZeros=seenZeros-1 if nums[p1]==0 else seenZeros p1+=1 res=max(res,p2-p1+1) p2+=1 return res
max-consecutive-ones-iii
Easy to understand Python ๐Ÿ sliding window solution
InjySarhan
1
143
max consecutive ones iii
1,004
0.634
Medium
16,360
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1468182/Python3-Sliding-Window
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: begin = 0 for end in range(len(nums)): if nums[end] == 0: k -= 1 if k < 0: if nums[begin] == 0: k += 1 begin += 1 return end - begin + 1
max-consecutive-ones-iii
[Python3] Sliding Window
maosipov11
1
151
max consecutive ones iii
1,004
0.634
Medium
16,361
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/884066/Python3-concise-sliding-window-solution
class Solution: def longestOnes(self, A: List[int], K: int) -> int: res = 0 i = 0 for j in range(len(A)): if A[j] == 0: K -= 1 res = max(res, j-i) while K < 0: if A[i] == 0: K += 1 i += 1 return max(res, len(A)-i)
max-consecutive-ones-iii
[Python3] concise sliding window solution
hwsbjts
1
138
max consecutive ones iii
1,004
0.634
Medium
16,362
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2842264/O(K)-Memory-O(N)-Time-oror-Python
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: # the go-to sliding window approach is to use: # 1. use a queue to store the current sequence. # 2. use a count variable to keep track of 0 one can take. # Then: # a. whenever the next value is 1, add to queue. # b. otherwise it's a 0, and then: # b.1 if 0-counter is at K: pop queue until a zero is popped and decrease it. # b.2 if 0-counter is less than k: add the 0 to the queue. # This is O(N) memory (sliding window, one iteration) and O(N) worst-case memory. # we can further opt memory to O(K), which is not bounded in this question - but it could be less than the array length. ans=0 l=0 zero_queue=[] # O(K) memory at most. # O(N) runtime. for r,num in enumerate(nums): if num!=1: if zero_queue and len(zero_queue)==k: zero_idx=zero_queue.pop(0) l=zero_idx+1 if len(zero_queue)<k: zero_queue.append(r) else: l=r+1 ans=max(ans, r-l+1) return ans
max-consecutive-ones-iii
O(K) Memory, O(N) Time || Python
d4mahu
0
2
max consecutive ones iii
1,004
0.634
Medium
16,363
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2835663/Simple-and-Easy-Solution-or-Python
class Solution(object): def longestOnes(self, nums, k): max_, zero, ptr = 0, 0, 0 for index, value in enumerate(nums): if value == 0: zero += 1 while zero > k: if nums[ptr] == 0: zero -= 1 ptr += 1 max_ = max(max_, (index - ptr) + 1) return max_
max-consecutive-ones-iii
Simple and Easy Solution | Python
its_krish_here
0
3
max consecutive ones iii
1,004
0.634
Medium
16,364
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2830016/Python-Solution-Sliding-Window-Approach-oror-Explained
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: m=0 #max length of window c=0 #count of 0 found i=0 #initial window index j=0 #window's end's index while j<len(nums): if nums[j]==0: #count if 0 found c+=1 if c==k: #if 0's equal to k in window then store the max m=max(m,j-i+1) #j-i+1 <- valid window length elif c>k: #if somehow 0's > k in window then move the window one step forward if nums[i]==0: #on moving the index i, its necessaray to check if that's 0 or not c-=1 #decrement the count if it is i+=1 #and move the index j+=1 #increment everytime, its making the window if c<k: #if 0's count < k in window, return whole nums length -> forms valid substring return len(nums) #else return max window length return m
max-consecutive-ones-iii
Python Solution - Sliding Window Approach || Explainedโœ”
T1n1_B0x1
0
6
max consecutive ones iii
1,004
0.634
Medium
16,365
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2826469/Sliding-window%3A-runtime-greater-90.62-memory-less-61.79
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: repeated_one, win_start, max_length = 0, 0, 0 sub_arr = [] for win_end in range(len(nums)): right_char = nums[win_end] if right_char == 1: repeated_one += 1 if (win_end - win_start + 1 - repeated_one) > k: if nums[win_start] == 1: repeated_one -= 1 win_start += 1 max_length = max(max_length, win_end - win_start + 1) return max_length
max-consecutive-ones-iii
Sliding window: runtime > 90.62%, memory < 61.79%
samratM
0
4
max consecutive ones iii
1,004
0.634
Medium
16,366
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2788245/Python3-solution
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: left = 0 nFlips =0 for right in range(len(nums)): if nums[right] == 0: nFlips +=1 if nFlips > k: # if the left index points to zero then decrease nFlips # Why ? because we are going to create a new sub array by moving the leftIndex by one. if nums[left] == 0: nFlips -=1 left+=1 return right - left +1
max-consecutive-ones-iii
Python3 solution
user5580aS
0
5
max consecutive ones iii
1,004
0.634
Medium
16,367
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2786521/sliding-window-approach-python
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: # O(n), O(1) # sliding window approach left = max_cons = 0 for right, num in enumerate(nums): k -= 1 - num if k < 0: k += 1 - nums[left] left += 1 else: max_cons = max(max_cons, right - left + 1) return max_cons
max-consecutive-ones-iii
sliding window approach python
sahilkumar158
0
5
max consecutive ones iii
1,004
0.634
Medium
16,368
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2755162/max-consecutive-ones-iii
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: count=0 ans=0 start=0 end=0 while(end<len(nums)): if nums[end]==0: if k==0: while(start<end and nums[start]!=0): count=count-1 start=start+1 start=start+1 end=end+1 ans=max(ans,count) else: count=count+1 k=k-1 ans=max(ans,count) end=end+1 else: count=count+1 end=end+1 ans=max(ans,count) return ans
max-consecutive-ones-iii
max-consecutive-ones-iii
Aviraj_Battan
0
2
max consecutive ones iii
1,004
0.634
Medium
16,369
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2746983/Python-Sliding-Window-short
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: mx, l = 0, 0 zeros = 0 for r in range(len(nums)): zeros += nums[r] == 0 while zeros > k: zeros -= nums[l] == 0 l += 1 mx = max(mx, r - l + 1) return mx
max-consecutive-ones-iii
Python Sliding Window short
JSTM2022
0
4
max consecutive ones iii
1,004
0.634
Medium
16,370
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2718672/Python-Sliding-Window
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: beg, end, zeros, ans = 0,0,0,0 while end < len(nums): if zeros + (nums[end] == 0) <= k: zeros += (nums[end] == 0) end += 1 ans = max(ans, end - beg) else: zeros -= (nums[beg] == 0) beg +=1 return ans
max-consecutive-ones-iii
[Python] Sliding Window
yzhao05
0
5
max consecutive ones iii
1,004
0.634
Medium
16,371
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2681685/Python-easy-solution
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: start = 0 zero_count = 0 max_ones = 0 for end in range(len(nums)): if nums[end] == 0: zero_count = zero_count + 1 while(zero_count > k): if nums[start] == 0: zero_count = zero_count - 1 start = start + 1 max_ones = max(max_ones, end-start + 1) return max_ones
max-consecutive-ones-iii
Python easy solution
rupalimishra_v2
0
37
max consecutive ones iii
1,004
0.634
Medium
16,372
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2663849/Sliding-window-plus-occurrences
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: occ = [0, 0] ans = l = r = 0 while r < len(nums): occ[nums[r]] += 1 while occ[0] > k: occ[nums[l]] -= 1 l += 1 ans = max(ans, r-l+1) r += 1 return ans
max-consecutive-ones-iii
Sliding window plus occurrences
tomfran
0
3
max consecutive ones iii
1,004
0.634
Medium
16,373
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2648233/FAST-and-Simple-Approach
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: l,r,longest = 0,0,0 while r<len(nums): if nums[r] == 1: r+=1 elif nums[r] == 0: if k>0: #0 shift to 1 k-=1 r+=1 else: #exhausted flips so shift pointer from left and increase k if nums[l] was zero if nums[l] == 0: k+=1 l+=1 longest= max(longest,r-l) return longest
max-consecutive-ones-iii
FAST and Simple Approach
Avtansh_Sharma
0
4
max consecutive ones iii
1,004
0.634
Medium
16,374
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2645769/Python3-Solution-oror-O(N)-Time-and-O(1)-Space-Complexity
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: count_0=0 n=len(nums) maxSize=0 currSize=0 left=0 for i in range(n): currSize+=1 if nums[i]==0: count_0+=1 if count_0>k: while count_0>k and left<=i: if nums[left]==0: count_0-=1 currSize-=1 left+=1 if currSize>maxSize and count_0<=k: maxSize=currSize return maxSize
max-consecutive-ones-iii
Python3 Solution || O(N) Time & O(1) Space Complexity
akshatkhanna37
0
5
max consecutive ones iii
1,004
0.634
Medium
16,375
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2613786/Python-Sliding-Window-Technique-(Faster-than-90)
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: count1=0 ws=0 maxlen=0 for we in range(len(nums)): if nums[we]==1: count1+=1 if we-ws+1-count1>k: if nums[ws]==1: count1-=1 ws+=1 maxlen=max(maxlen,we-ws+1) return maxlen
max-consecutive-ones-iii
Python - Sliding Window Technique (Faster than 90%)
utsa_gupta
0
18
max consecutive ones iii
1,004
0.634
Medium
16,376
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2611335/Sliding-window-Solution
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: ws=0 c1=0 c0=0 maxlen=0 for we in range(len(nums)): c=nums[we] if c==0: c0+=1 else: c1+=1 if c0>k: leftchar=nums[ws] if leftchar==0: c0-=1 ws+=1 maxlen=max(maxlen,we-ws+1) return maxlen
max-consecutive-ones-iii
Sliding window Solution
shagun_pandey
0
19
max consecutive ones iii
1,004
0.634
Medium
16,377
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2566023/Python-easy-solution-using-sliding-windows-TC%3A(N)-SC(1)
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: start = 0 mini = 0 maxFreq = 0 for end in range(len(nums)): if(nums[end] == 1): maxFreq += 1 if((end - start + 1) - maxFreq ) > k: if(nums[start] == 1): maxFreq -= 1 start += 1 mini = max(mini , end - start + 1) return mini
max-consecutive-ones-iii
Python easy solution using sliding windows TC:(N) SC(1)
rajitkumarchauhan99
0
28
max consecutive ones iii
1,004
0.634
Medium
16,378
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2401243/Python-Solution-or-Classic-Two-Pointer-Sliding-Window-or-Count-Valid-Zeroes
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: ans = 0 start = 0 end = 0 # to count zeroes encountered zero = 0 while end < len(nums): # count valid zeroes if nums[end] == 0: zero += 1 # if zeroes amount more than valid, remove them while sliding the window while zero > k: if nums[start] == 0: zero -= 1 start += 1 # check for max length ans = max(ans,end-start+1) end += 1 return ans
max-consecutive-ones-iii
Python Solution | Classic Two Pointer - Sliding Window | Count Valid Zeroes
Gautam_ProMax
0
37
max consecutive ones iii
1,004
0.634
Medium
16,379
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2338974/Python-easy-solution
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: j = 0 ans = 0 result = -999999999 for i in range(len(nums)): if nums[i]==0: ans+=1 elif ans>k: result = max(result,j-i) while ans>k: if nums[j]==0: ans-=1 j+=1 return max(result,i-j+1)
max-consecutive-ones-iii
Python easy solution
Brillianttyagi
0
60
max consecutive ones iii
1,004
0.634
Medium
16,380
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2175930/Sliding-Window-Approach-oror-Simplest-Solution-with-Dry-Run
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: l = 0 for r, val in enumerate(nums): k -= (1 - val) if k < 0: k += (1 - nums[l]) l += 1 return r - l + 1
max-consecutive-ones-iii
Sliding Window Approach || Simplest Solution with Dry Run
Vaibhav7860
0
72
max consecutive ones iii
1,004
0.634
Medium
16,381
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2124836/Python-or-SImple-Sliding-window-solution
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: zeroes_in_window = 0 max_len=0 slow=0 for fast,f in enumerate(nums) : if f == 0: zeroes_in_window+=1 # Maintain Valid Window. # I.E If Number of zeroes has exceeded k shrink from left till zeroes_in_window<=k while zeroes_in_window > k : #Decrement count of zeroes in window if nums[slow]==0 : zeroes_in_window -= 1 slow+=1 #Update max window if current window is larger max_len=max(fast-slow+1,max_len) return max_len
max-consecutive-ones-iii
Python | SImple Sliding window solution
pbprasad_99
0
28
max consecutive ones iii
1,004
0.634
Medium
16,382
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/2061486/Python-two-pointers
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: start = flip = result = 0 for end in range(len(nums)): flip += nums[end] == 0 while flip > k: flip -= nums[start] == 0 start += 1 result = max(result, end - start + 1) return result
max-consecutive-ones-iii
Python, two pointers
blue_sky5
0
44
max consecutive ones iii
1,004
0.634
Medium
16,383
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1998136/PYTHON-SOL-oror-SLIDING-WINDOW-oror-FASTER-THAN-99.46-oror-COMMENTED-oror-EXPLAINED-oror
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: #sliding window ans = 0 n = len(nums) left = k prev = 0 for i in range(n): if nums[i] == 1: # no need to flip continue else: # check if we can flip if left > 0: left -= 1 continue else: # we cannot flip so sliding window is stopped if i - prev > ans : ans = i - prev # now sliding window will shrink while prev < i and nums[prev] != 0: prev += 1 prev += 1 if n - prev > ans : ans = n - prev return ans
max-consecutive-ones-iii
PYTHON SOL || SLIDING WINDOW || FASTER THAN 99.46% || COMMENTED || EXPLAINED ||
reaper_27
0
126
max consecutive ones iii
1,004
0.634
Medium
16,384
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1949596/5-Lines-Python-Solution-oror-99-Faster-oror-Memory-less-than-95
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: l=0 for r in range(len(nums)): k-=1-nums[r] if k<0: k+=1-nums[l] ; l+=1 return r-l+1
max-consecutive-ones-iii
5-Lines Python Solution || 99% Faster || Memory less than 95%
Taha-C
0
101
max consecutive ones iii
1,004
0.634
Medium
16,385
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1949596/5-Lines-Python-Solution-oror-99-Faster-oror-Memory-less-than-95
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: l=0 ; ans=0 ; C={0:0, 1:0} for r,num in enumerate(nums): C[num]+=1 while C[0]>k: C[nums[l]]-=1 ; l+=1 ans=max(ans,r-l+1) return ans
max-consecutive-ones-iii
5-Lines Python Solution || 99% Faster || Memory less than 95%
Taha-C
0
101
max consecutive ones iii
1,004
0.634
Medium
16,386
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1827489/Python-easy-to-read-and-understand-or-sliding-window
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: cnt, ans, i = 0, 0, 0 for j in range(len(nums)): if nums[j] == 0: cnt += 1 while cnt > k: if nums[i] == 0: cnt -= 1 i = i+1 ans = max(ans, j-i+1) return ans
max-consecutive-ones-iii
Python easy to read and understand | sliding window
sanial2001
0
102
max consecutive ones iii
1,004
0.634
Medium
16,387
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1784602/Python-Sliding-window-approach-Simple-to-understand-explained-with-comments
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: zeros = 0 # Keep track of all the zeros in the window left = 0 # Left pointer res = 0 # result to return # Just like most window problems, iterate through the array and imagine the index is your right pointer for i in range(len(nums)): # If the number is zero we need to increment our zeros counter, we know # that k zeros can be flipped, that means our window can have at max k 0s # # If we see that the window has more than k zeros we need to start moving the left pointer # once we work passed a zero on the left we can continue iterating through the rest of the numbers if nums[i] == 0: zeros += 1 # increment our zeros counter every time we spot one while zeros > k: if nums[left] == 0: zeros -= 1 # Subtract our counter because our window is moving passed a zero left += 1 # Move the left pointer # In most sliding window problems you'll use a similar approach to keep track of the result, # (i + 1 - left) is basically calculating the window size, you add 1 to the right pointer because arrays # start at 0, an array of 5 numbers has a max index of 4. res = max(res, i + 1 - left) return res
max-consecutive-ones-iii
Python - Sliding window approach - Simple to understand, explained with comments
iamricks
0
65
max consecutive ones iii
1,004
0.634
Medium
16,388
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1740528/Unique-EASY-Solution-or-python3
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: lo, hi, N, ones, zeros, max_sum = 0, 0, len(nums), 0, 0, -math.inf while hi < N: if nums[hi] == 1: ones+=1 if nums[hi] == 0: zeros+=1 while lo <= hi and zeros > k: if nums[lo] == 1: ones-=1 if nums[lo] == 0: zeros-=1 lo+=1 max_sum = max(max_sum, ones+zeros) hi+=1 return max_sum
max-consecutive-ones-iii
Unique EASY Solution | python3
SN009006
0
50
max consecutive ones iii
1,004
0.634
Medium
16,389
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1720185/Python-Simple-sliding-window-explained
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: l, r = 0, 0 while r < len(nums): # if the right pointer sees a 0 # decrement the available number # of zeroes we have if nums[r] == 0: k -= 1 # if at any point we don't # have num(zeroes) to flip, # we'll increment the left pointer # BUT, while incrementing the left # pointer if we come across a 0 # it means we're going to remove # that from our window [l..r] so # we increment the available zeroes too if k < 0: if nums[l] == 0: k += 1 l += 1 # right pointer is going to # march ahead irrespectively r += 1 # the length of the required # window can be determined by # the distance bw left and righ return r - l
max-consecutive-ones-iii
[Python] Simple sliding window explained
buccatini
0
110
max consecutive ones iii
1,004
0.634
Medium
16,390
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1625066/python-or-96.68
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: zeros = [-1] for i in range(len(nums)): if nums[i]==0: zeros.append(i) zeros.append(len(nums)) if len(zeros)-2<=k: return len(nums) ret = 0 for i in range(k+1, len(zeros)): ret = max(ret, zeros[i] - zeros[i-k-1] - 1) return ret
max-consecutive-ones-iii
python | 96.68%
1579901970cg
0
120
max consecutive ones iii
1,004
0.634
Medium
16,391
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1616582/python3-sliding-window-solutionvery-easy-to-understand
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: countZeros=0 res=0 left=0 for right in range(len(nums)): if nums[right]==0: countZeros+=1 while countZeros>k: if nums[left]==0: countZeros-=1 left+=1 res=max(res,right-left+1) return res
max-consecutive-ones-iii
python3 sliding window solution,very easy to understand
Karna61814
0
56
max consecutive ones iii
1,004
0.634
Medium
16,392
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1572697/Easiest-Solution-Python-or-Faster-than-80
class Solution: def longestOnes(self, nums: List[int], k: int) -> int: start=0 end=0 ans=0 d={} while end<=len(nums)-1: d[nums[end]]=d.get(nums[end],0)+1 if 0 not in d: ans=max(ans,end-start+1) end+=1 else: if d[0]<=k: ans=max(ans,end-start+1) end+=1 else: if d[nums[start]]==1: del d[nums[start]] start+=1 end+=1 else: d[nums[start]]-=1 start+=1 end+=1 return ans
max-consecutive-ones-iii
Easiest Solution Python | Faster than 80%
AdityaTrivedi88
0
88
max consecutive ones iii
1,004
0.634
Medium
16,393
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1087613/Python-or-Sliding-Window
class Solution: def longestOnes(self, A: List[int], K: int) -> int: max_ones, window_start, max_size = 0, 0, 0 for window_end in range(len(A)): if A[window_end] == 1: max_ones += 1 if (window_end - window_start + 1 - max_ones) > K: if A[window_start] == 1: max_ones -= 1 window_start += 1 max_size = max(max_size, window_end-window_start+1) return max_size
max-consecutive-ones-iii
Python | Sliding Window
Rakesh301
0
134
max consecutive ones iii
1,004
0.634
Medium
16,394
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/985341/Python3-sliding-window-O(N)
class Solution: def longestOnes(self, A: List[int], K: int) -> int: ans = cnt = 0 seen = {0: -1} for i in range(len(A)): if A[i] == 0: cnt += 1 # count of 0s seen.setdefault(cnt, i) ans = max(ans, i - seen.get(cnt-K, -1)) return ans
max-consecutive-ones-iii
[Python3] sliding window O(N)
ye15
0
78
max consecutive ones iii
1,004
0.634
Medium
16,395
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/985341/Python3-sliding-window-O(N)
class Solution: def longestOnes(self, A: List[int], K: int) -> int: ans = ii = cnt = 0 for i, x in enumerate(A): if not x: cnt += 1 while ii <= i and cnt > K: if not A[ii]: cnt -= 1 ii += 1 ans = max(ans, i - ii + 1) return ans
max-consecutive-ones-iii
[Python3] sliding window O(N)
ye15
0
78
max consecutive ones iii
1,004
0.634
Medium
16,396
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1120243/WEEB-EXPLAINS-PYTHON-SOLUTION
class Solution: def largestSumAfterKNegations(self, A: List[int], K: int) -> int: A.sort() i = 0 while i < len(A) and K>0: if A[i] < 0: # negative value A[i] = A[i] * -1 # update the list, change negative to positive K-=1 elif A[i] > 0: # positive value if K % 2 == 0: # let K==2(must be even value), this means -1*-1==1 so it has no effect on sum return sum(A) else: return sum(A) - 2 * min(A) # let A==[1,2,3],K=1, so equation is 6-2(1)==4, same as -1+2+3=4 after taking the minimum in the list to give the largest possible sum required in the question else: return sum(A) # if A[i]==0,just sum cuz 0 is neutral: 1-0==1 or 1+0==1 thus no change just sum i+=1 if K > len(A): # that means we have changed all values to positive A.sort() # cuz now its the opposite let A = [-4,-2,-3], K = 8, now flipping all negatives to positives, we have a new minimum which is 2 if K % 2 == 0: # Here onwards is basically the same thing from before return sum(A) else: return sum(A) - 2 * min(A) return sum(A)
maximize-sum-of-array-after-k-negations
WEEB EXPLAINS PYTHON SOLUTION
Skywalker5423
6
361
maximize sum of array after k negations
1,005
0.51
Easy
16,397
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/350855/Solution-in-Python-3-(beats-~100)
class Solution: def largestSumAfterKNegations(self, A: List[int], K: int) -> int: S, a = sum(A), sorted([i for i in A if i < 0]) L, b = len(a), min([i for i in A if i >= 0]) if L == 0: return S if K % 2 == 0 else S - 2*b if K <= L or (K - L) % 2 == 0: return S - 2*sum(a[:min(K,L)]) return S - 2*sum(a[:-1]) if -a[-1] < b else S - 2*sum(a) - 2*b - Junaid Mansuri
maximize-sum-of-array-after-k-negations
Solution in Python 3 (beats ~100%)
junaidmansuri
3
477
maximize sum of array after k negations
1,005
0.51
Easy
16,398
https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1809612/Greedy-approach-python
class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: nums.sort(key=abs, reverse=True) for i in range(len(nums)): if nums[i] < 0 and k > 0: nums[i] *= -1 k -= 1 if k == 0: break if k % 2 != 0: nums[-1] *= -1 return sum(nums) ```
maximize-sum-of-array-after-k-negations
Greedy approach - python
lister777
2
93
maximize sum of array after k negations
1,005
0.51
Easy
16,399