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/reconstruct-original-digits-from-english/discuss/2079750/Simple-intuitive-Python-Using-Dict-less-Operator
class Solution: def originalDigits(self, s: str) -> str: # (z)ero, one, t(w)o, three, fo(u)r, five, si(x), seven, ei(g)ht, nine from collections import Counter sc = Counter(s) digits = {0: Counter("zero"), 1: Counter("one"), 2:Counter("two"), 3:Counter("three"), 4:Counter("four"), 5:Counter("five"), 6:Counter("six"), 7: Counter("seven"), 8: Counter("eight"), 9: Counter("nine")} counts = [0]*10 for i in [0, 2, 4, 6, 8, 3, 1, 7, 5, 9]: digit = digits[i] while digit <= sc: sc -= digit counts[i] += 1 return "".join([str(i)*c for i, c in enumerate(counts)])
reconstruct-original-digits-from-english
Simple, intuitive Python, Using Dict <= Operator
boris17
1
70
reconstruct original digits from english
423
0.513
Medium
7,500
https://leetcode.com/problems/reconstruct-original-digits-from-english/discuss/1131036/Simple-solution-in-Python3-by-taking-the-count-of-the-unique-characters
class Solution: def originalDigits(self, s: str) -> str: c = dict() c[0] = s.count("z") c[2] = s.count("w") c[4] = s.count("u") c[6] = s.count("x") c[8] = s.count("g") c[3] = s.count("h") - c[8] c[5] = s.count("f") - c[4] c[7] = s.count("s") - c[6] c[9] = s.count("i") - (c[8] + c[5] + c[6]) c[1] = s.count("o") - (c[0] + c[2] + c[4]) c = sorted(c.items(), key = lambda x: x[0]) ans = "" for k, v in c: ans += (str(k) * v) return ans
reconstruct-original-digits-from-english
Simple solution in Python3 by taking the count of the unique characters
amoghrajesh1999
1
67
reconstruct original digits from english
423
0.513
Medium
7,501
https://leetcode.com/problems/reconstruct-original-digits-from-english/discuss/2009700/Python-easy-solution-using-dictionaries
class Solution: def originalDigits(self, s: str) -> str: freq = Counter(s) res = {} res["0"] = freq["z"] res["2"] = freq["w"] res["4"] = freq["u"] res["6"] = freq["x"] res["8"] = freq["g"] res["3"] = freq["h"] - res["8"] res["5"] = freq["f"] - res["4"] res["7"] = freq["s"] - res["6"] res["9"] = freq["i"] - res["5"] - res["6"] - res["8"] res["1"] = freq["n"] - res["7"] - (2 * res["9"]) num = "" for i in res: if res[i] != 0: num += i * res[i] return ''.join(sorted(num))
reconstruct-original-digits-from-english
Python easy solution using dictionaries
alishak1999
0
97
reconstruct original digits from english
423
0.513
Medium
7,502
https://leetcode.com/problems/reconstruct-original-digits-from-english/discuss/1696076/Python3-accepted-solution
class Solution: def originalDigits(self, s: str) -> str: ans = "" # words with unique letters ans += "0"*(s.count("z")) s = s.replace("z","",s.count("z")).replace("e","",s.count("z")).replace("r","",s.count("z")).replace("o","",s.count("z")) ans += "2"*(s.count("w")) s = s.replace("w","",s.count("w")).replace("t","",s.count("w")).replace("o","",s.count("w")) ans += "4"*(s.count("u")) s = s.replace("u","",s.count("u")).replace("f","",s.count("u")).replace("o","",s.count("u")).replace("r","",s.count("u")) ans += "6"*(s.count("x")) s = s.replace("x","",s.count("x")).replace("s","",s.count("x")).replace("i","",s.count("x")) ans += "8"*(s.count("g")) s = s.replace("g","",s.count("g")).replace("e","",s.count("g")).replace("i","",s.count("g")).replace("h","",s.count("g")).replace("t","",s.count("g")) # print(ans) # print(s) #1 ans += "1"*(s.count("o")) s = s.replace("o","",s.count("o")).replace("n","",s.count("o")).replace("e","",s.count("o")) #3 ans += "3"*(s.count("r")) s = s.replace("r","",s.count("r")).replace("t","",s.count("r")).replace("h","",s.count("r")).replace("e","",s.count("r")*2) #5 ans += "5"*(s.count("f")) s = s.replace("f","",s.count("f")).replace("i","",s.count("f")).replace("v","",s.count("f")).replace("e","",s.count("f")) #7 ans += "7"*(s.count("v")) s = s.replace("v","",s.count("v")).replace("s","",s.count("v")).replace("n","",s.count("v")).replace("e","",s.count("v")*2) #9 ans += "9"*(s.count("i")) s = s.replace("i","",s.count("i")).replace("e","",s.count("i")).replace("n","",s.count("i")).replace("n","",s.count("i")*2) return "".join(sorted(ans))
reconstruct-original-digits-from-english
Python3 accepted solution
sreeleetcode19
0
192
reconstruct original digits from english
423
0.513
Medium
7,503
https://leetcode.com/problems/reconstruct-original-digits-from-english/discuss/839022/Python3-via-Counter
class Solution: def originalDigits(self, s: str) -> str: freq = Counter(s) nums = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] ans = [0]*10 for c, i in ("g", 8), ("u", 4), ("w", 2), ("x", 6), ("z", 0), ("s", 7), ("v", 5), ("h", 3), ("i", 9), ("o", 1): ans[i] = freq[c] freq -= Counter(nums[i]*freq[c]) return "".join(sorted(str(i)*x for i, x in enumerate(ans)))
reconstruct-original-digits-from-english
[Python3] via Counter
ye15
0
161
reconstruct original digits from english
423
0.513
Medium
7,504
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/900524/Simple-Python-solution-moving-window-O(n)-time-O(1)-space
class Solution: def characterReplacement(self, s: str, k: int) -> int: # Maintain a dictionary that keeps track of last 'window' characters # See if 'window' size minus occurrences of the most common char is <= k, if so it's valid # Run time is O(length of string * size of alphabet) # Space is O(size of alphabet) d = {} window = 0 for i, char in enumerate(s): d[char] = d.get(char, 0) + 1 if window+1 - max(d.values()) <= k: window += 1 else: d[s[i-window]] -= 1 return window
longest-repeating-character-replacement
Simple Python solution, moving window O(n) time, O(1) space
wesleyliao3
16
2,100
longest repeating character replacement
424
0.515
Medium
7,505
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1965712/Python-Easiest-solution-With-Explanation-or-96.68-Faster-or-Beg-to-Adv-or-Sliding-Window
class Solution: def characterReplacement(self, s: str, k: int) -> int: maxf = l = 0 count = collections.Counter() # counting the occurance of the character in the string. # instead of using "count = collections.Counter()", we can do the following:- """ for r, n in enumerate(s): if n in hashmap: hashmap[n] += 1 else: hashmap[n] = 1 """ for r in range(len(s)): count[s[r]] += 1 # increasing the count of the character as per its occurance. maxf = max(maxf, count[s[r]]) # having a max freq of the character that is yet occurred. if r - l + 1 > maxf + k: # if length of sliding window is greater than max freq of the character and the allowed number of replacement. count[s[l]] -= 1 # then we have to decrease the occurrance of the character by 1 are we will be sliding the window. l += 1 # and we have to slide our window return len(s) - l # this will provide the length of the longest substring containing the same letter with the replacement allowed.
longest-repeating-character-replacement
Python Easiest solution With Explanation | 96.68% Faster | Beg to Adv | Sliding Window
rlakshay14
13
871
longest repeating character replacement
424
0.515
Medium
7,506
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1705860/Python-Intuitive-and-Clean-O(n)-time-approach-and-Big-O-explained
class Solution: def characterReplacement(self, s: str, k: int) -> int: leftPointer = 0 currentCharDict = {} longestLength = 0 for rightPointer,rightValue in enumerate(s): leftValue = s[leftPointer] if rightValue not in currentCharDict: currentCharDict[rightValue] = 0 currentCharDict[rightValue] += 1 currentLength = rightPointer - leftPointer + 1 if currentLength - max(currentCharDict.values()) <= k: longestLength = max(longestLength, currentLength) else: currentCharDict[leftValue] -= 1 if currentCharDict[leftValue] == 0: del currentCharDict[leftValue] leftPointer += 1 return longestLength
longest-repeating-character-replacement
Python Intuitive and Clean O(n) time, approach and Big O explained
kenanR
5
597
longest repeating character replacement
424
0.515
Medium
7,507
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2497159/O(n)-Hashmap-and-sliding-window-or-Python
class Solution: def characterReplacement(self, s: str, k: int) -> int: res = 0 left = 0 count = {} for right in range(len(s)): count[s[right]] = 1 + count.get(s[right], 0) # Check this is a valid window while (right - left + 1) - max(count.values()) > k: count[s[left]] -= 1 left += 1 res = max(res, right - left + 1) return res
longest-repeating-character-replacement
O(n) Hashmap & sliding window | Python
Monicaaaaaa
3
270
longest repeating character replacement
424
0.515
Medium
7,508
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2327129/Sliding-window-Python-code-with-proper-explanation
class Solution: def characterReplacement(self, s: str, k: int) -> int: """ s = ABAB k = 2 If we have no limit on k then we can say that (no of replacements to be done = length of string - count of character with maximum occurence) AAAAAABB - Here 2 replacements to be done ABABABABAA - Here 4 replacements to be done Let's say there is a restriction on the number of updates done no. of replacements = len of str - min (count chars with max occur , k ) If we change the problem statement from String to substring then we have to find the sustring of max length where atmost K repelacements can be done s = "AABABBA" k = 1 i AABABBA count of max occur = 1 length of the substr = 1 repl = 0 j i AABABBA count of max occur = 2 length of substr = 2 repl = 0 j i AABABBA count max occur = 2 length of substr = 3 repl = 1 j i AABABBA count max occur = 3 length of substr = 4 repl = 1 j i AABABBA count max occur = 3 length of substr = 5 repl = 2 j Here 2 > k => 2 > 1 decrease window till repl becomes 1 again i AABABBA count max occur = 2 length of substr = 4 repl = 2 j further decrease the window i AABABBA count max occur = 2 length of substr = 3 repl = 1 j i AABABBA count max occur = 3 length of substr = 4 repl = 1 j i AABABBA count max occur = 3 length of susbstr = 5 repl = 2 increase i j i AABABBA length of substr = 3 j maximum length of substring with replacements that can be done = 1 is 4 At any particular moment we need (max occur,length of substr,repl) """ # In the below line we are keeping the count of each character in the string count = collections.Counter() # i : start of the window # j : end of the window i = j = 0 # maxLen : maximum length of the substring maxLen = 0 # maxOccur will store the count of max occurring character in the window maxOccur = None while j < len(s): # Increase the count of characters as we are increasing the window count[s[j]] += 1 # maxOccur : count maximum occurring character in the window maxOccur = count[max(count , key = lambda x: count[x])] j += 1 # length of substring - count of character with maximum occurence <= k while j - i - maxOccur > k : # We are decreasing the count here count[s[i]] -= 1 # Here we are again updating maxOccur maxOccur = count[max(count , key = lambda x: count[x])] # and then we are decreasing the window i += 1 maxLen = max(maxLen , j - i) return maxLen # Time complexity is nearly O(n) as max operation can run for atmost 26 characters
longest-repeating-character-replacement
Sliding window - Python code with proper explanation
Pratyush_Priyam_Kuanr
3
206
longest repeating character replacement
424
0.515
Medium
7,509
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1585789/Python-Sliding-Window-Approach
class Solution: def characterReplacement(self, s: str, k: int) -> int: windowStart = 0 maxRepeatLetterCount = 0 maxLength = 0 char_freq = {} for windowEnd in range(len(s)): rightChar = s[windowEnd] if rightChar not in char_freq: char_freq[rightChar] = 0 char_freq[rightChar] += 1 maxRepeatLetterCount = max(maxRepeatLetterCount, char_freq[rightChar]) if (windowEnd-windowStart+1 - maxRepeatLetterCount) > k: leftChar = s[windowStart] char_freq[leftChar] -= 1 windowStart += 1 maxLength = max(maxLength, windowEnd-windowStart+1) return maxLength
longest-repeating-character-replacement
Python - Sliding Window Approach
lennywgonzalez
3
668
longest repeating character replacement
424
0.515
Medium
7,510
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2750877/Python-Sliding-Window
class Solution: def characterReplacement(self, s: str, k: int) -> int: d = {} slow = 0 ans = 0 for fast in range(len(s)): if s[fast] in d: d[s[fast]] += 1 else: d[s[fast]] = 1 # get max of the window and check if # length of the window - max valued key <= k if ((fast-slow+1) - max(d.values())) <= k: pass else: # shrink the window while ((fast-slow+1) - max(d.values())) > k: d[s[slow]] -= 1 if d[s[slow]] == 0: del d[s[slow]] slow += 1 # calculate the length of the window ans = max(ans, fast - slow + 1) return ans
longest-repeating-character-replacement
Python Sliding Window
DietCoke777
2
157
longest repeating character replacement
424
0.515
Medium
7,511
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1779450/Python-sliding-window-simple-explanation-with-comments
class Solution: def characterReplacement(self, s: str, k: int) -> int: seen = {} # These are the elements we have seen left = 0 # This is the left pointer for our window res = 0 # The result we will return in the end # We will iterate through the entire array # you can usually think of the index as the right pointer in sliding window problems for i in range(len(s)): # This will print your window print(s[left:i]) # If we have seen the current character, we will increment the counter # If we are seeing it for the first time, we will add it to the dict and set # the counter to 1 if s[i] in seen: seen[s[i]] += 1 else: seen[s[i]] = 1 # This is the tricky part, this is basically # (window_size - char_repeated_the_most <= maximum_gap) # # This works because you can change k letters to any other letter, so # If you can change 2 letters you can have 2 random letters inbetween the # char_repeated_the_most # # k = 1, s = AABABBA # once you get to the window [AABA] in this example you will end up entering the max result if (i + 1 - left) - max(seen.values()) <= k: res = max(res, (i + 1 - left)) else: # once you get to the window [AABAB] you need to move the left pointer # You need to move the left pointer because the gap is now 2, you window will now become # [ABAB] # Then it will be # [BABB] seen[s[left]] -= 1 left += 1 return res
longest-repeating-character-replacement
Python - sliding window - simple explanation with comments
iamricks
2
166
longest repeating character replacement
424
0.515
Medium
7,512
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1529076/Python-code-%2B-explanation-of-logic
class Solution: def characterReplacement(self, s: str, k: int) -> int: left = 0 right = 0 ht = {} longest = 0 while right < len(s): letter = s[right] if letter not in ht: ht[letter] = 0 ht[letter] += 1 max_count = self.get_max(ht) cells_count = right - left + 1 temp = cells_count - max_count if temp <= k: longest = max(longest, cells_count) else: letter = s[left] ht[letter] -= 1 if not ht[letter]: # del ht[letter] ht.pop(letter) left += 1 right += 1 return longest def get_max(self, ht): return max(ht.values())
longest-repeating-character-replacement
Python code + explanation of logic
SleeplessChallenger
2
252
longest repeating character replacement
424
0.515
Medium
7,513
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1264545/Readable-Code-With-Explanation
class Solution: def characterReplacement(self, string, k): left, right = 0, 0 frequencyOfChars, mostCommonElementCount = {}, 0 for right in range(len(string)): frequencyOfChars[string[right]] = frequencyOfChars.get(string[right], 0) + 1 mostCommonElementCount = max(mostCommonElementCount, frequencyOfChars[string[right]]) windowSize = right - left + 1 if windowSize - mostCommonElementCount > k: frequencyOfChars[string[left]] -= 1 left += 1 return right - left + 1
longest-repeating-character-replacement
Readable Code With Explanation
ramit_kumar
2
387
longest repeating character replacement
424
0.515
Medium
7,514
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2635275/Python-3-Sliding-window-super-easy-to-understand
class Solution: def characterReplacement(self, s: str, k: int) -> int: window = [] max_len = 0 max_freq = 0 char_dict = defaultdict(lambda: 0) for char in s: char_dict[char] += 1 window.append(char) max_freq = max(max_freq, char_dict[char]) if len(window) - max_freq > k: first = window.pop(0) char_dict[first] -= 1 else: max_len = max(max_len, len(window)) return max_len
longest-repeating-character-replacement
Python 3 Sliding window - super easy to understand
zakmatt
1
163
longest repeating character replacement
424
0.515
Medium
7,515
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2611348/Sliding-Window-Python-Solution
class Solution: def characterReplacement(self, s: str, k: int) -> int: ws=0 d={} freq=0 maxlen=0 for we in range(len(s)): c=s[we] d[c]=d.get(c,0)+1 freq=max(freq,d[c]) if we-ws+1-freq>k: leftchar=s[ws] d[leftchar]-=1 if d[leftchar]==0: del d[leftchar] ws+=1 maxlen=max(maxlen,we-ws+1) return maxlen
longest-repeating-character-replacement
Sliding Window Python Solution
shagun_pandey
1
119
longest repeating character replacement
424
0.515
Medium
7,516
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2258780/Python-O(N)-Faster-than-99-of-submissions-with-explanation
class Solution: def characterReplacement(self, s: str, k: int) -> int: # output = 10, k = 5, used 4 we need at least 5 counts = {} l,r = 0,0 most_frequent = s[0] while r < len(s): letter = s[r] # increment this letter's count counts[letter] = counts.get(letter,0) + 1 # update most frequent letter if necessary if counts[letter] > counts[most_frequent]: most_frequent = letter # shift left pointer if the # of letters that need to be replaced > k if r+1-l-counts[most_frequent] > k: counts[s[l]] -= 1 l+=1 r+=1 return r-l
longest-repeating-character-replacement
Python O(N) Faster than 99% of submissions with explanation
joshnewburn42
1
147
longest repeating character replacement
424
0.515
Medium
7,517
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2228279/Python-Sliding-Window-Beats-98-with-full-working-explanation
class Solution: def characterReplacement(self, s: str, k: int) -> int: # Time: O(n) and Space:O(n) count = {} # hashmap to count the occurrences of the characters in string res = 0 l = 0 # maxfreq will store the frequency of most occurring word in the entire string, # this way we don't have to search the entire hashmap to find the frequency of each character, # instead we will just use the most occurring one for all the characters, # cause if most occurring value satisfies the conditions then surely any other value will too. maxfreq = 0 for r in range(len(s)): count[s[r]] = 1 + count.get(s[r], 0) maxfreq = max(maxfreq, count[s[r]]) # checking if the current char frequency is greater than the maxfreq if (r - l + 1) - maxfreq > k: # if window - maxfreq fails it means that there are atleast k elements in the window who can be converted count[s[l]] -= 1 # if it is true, then we have exceeded our k limit, and we have to shorten of window l += 1 # removing the frequency of this character from hashmap count &amp; moving the window to the right res = max(res, r - l + 1) # checking if current window size if greater than the previous max or not return res
longest-repeating-character-replacement
Python [Sliding Window / Beats 98%] with full working explanation
DanishKhanbx
1
209
longest repeating character replacement
424
0.515
Medium
7,518
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2228279/Python-Sliding-Window-Beats-98-with-full-working-explanation
class Solution: # same as above but takes O(26) each time to serach max count value def characterReplacement(self, s: str, k: int) -> int: # Time: O(26*n) and Space:O(n) count = {} res = 0 l = 0 for r in range(len(s)): count[s[r]] = 1 + count.get(s[r], 0) if r - l + 1 - max(count.values()) > k: # max(count.values()) this will find the maximum frequency of a character in the hash again and again count[s[l]] -= 1 l += 1 res = max(res, r - l + 1) return res
longest-repeating-character-replacement
Python [Sliding Window / Beats 98%] with full working explanation
DanishKhanbx
1
209
longest repeating character replacement
424
0.515
Medium
7,519
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1987332/Python-O(N)
class Solution: def characterReplacement(self, s: str, k: int) -> int: result = 0 counts = defaultdict(int) start = 0 for end in range(len(s)): counts[s[end]] += 1 while end - start + 1 - max(counts.values()) > k: counts[s[start]] -= 1 start += 1 result = max(result, end - start + 1) return result
longest-repeating-character-replacement
Python, O(N)
blue_sky5
1
207
longest repeating character replacement
424
0.515
Medium
7,520
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2833389/Simple-Python-Windows-using-Counter-O(N)
class Solution: def characterReplacement(self, s: str, k: int) -> int: windows = collections.Counter() size = len(s) left, right, max_times = 0, 0, 0 while right < size: windows[ord(s[right])] += 1 max_times = max(max_times, windows[ord(s[right])]) if right - left + 1 - max_times > k: windows[ord(s[left])] -= 1 left += 1 right += 1 return right - left
longest-repeating-character-replacement
Simple Python Windows using Counter O(N)
qunfei
0
3
longest repeating character replacement
424
0.515
Medium
7,521
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2763066/Easy-Python-Solution-oror-Fully-Explained-oror-Sliding-Window
class Solution: def characterReplacement(self, s: str, k: int) -> int: longest = 0 i, j = 0, 0 count = {} while j < len(s): # insert the frequency of current window count.setdefault(s[j], 0) count.update({ s[j]: count[s[j]]+1 }) # find the most frequent char's frequency in current window (count) most = 0 for x in count: if count[x] > most: most = count[x] # find current window length windowLen = j - i + 1 # check if current window can be a valid substring with repeated # characters after at-most k replacements # else shift the current window to right if (windowLen - most) <= k: # save the current longest if windowLen > longest: longest = windowLen # enhance current window j += 1 else: # decrease/remove s[i] the first char of current window if count[s[i]] > 1: count.update({ s[i]: count[s[i]]-1 }) else: del count[s[i]] # shift current window to right by one step i += 1 j += 1 return longest
longest-repeating-character-replacement
Easy Python Solution || Fully Explained || Sliding Window
rishisoni6071
0
12
longest repeating character replacement
424
0.515
Medium
7,522
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2757491/Python3-not-so-effiecient-approach
class Solution: def characterReplacement(self, s: str, k: int) -> int: l,r =0,0 res = '' d = collections.defaultdict(int) maxlen = 0 while r < len(s): d[s[r]] += 1 res = res+s[r] if len(res) - max(d.values()) > k: d[s[l]] -= 1 l += 1 res = res[1:] maxlen = max(len(res),maxlen) r += 1 return maxlen
longest-repeating-character-replacement
Python3 not so effiecient approach
leetcodesquad
0
5
longest repeating character replacement
424
0.515
Medium
7,523
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2750335/Python-two-pointer-sliding-window
class Solution: def characterReplacement(self, s: str, k: int) -> int: # O(26 * n), O(n) res = 0 l = 0 count = {} for r in range(len(s)): count[s[r]] = 1 + count.get(s[r], 0) while ((r - l + 1) - max(count.values())) > k: count[s[l]] -= 1 l += 1 res = max(res, r - l + 1) return res
longest-repeating-character-replacement
Python two pointer sliding window
sahilkumar158
0
10
longest repeating character replacement
424
0.515
Medium
7,524
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2729276/Optimised-window-operator-with-hashmap
class Solution: def characterReplacement(self, s: str, k: int) -> int: res = 0 count = {} l = 0 max_f = 0 for r in range(len(s)): count[s[r]] = count.get(s[r], 0) + 1 max_f = max(count[s[r]], max_f) while r - l + 1 - max_f > k: count[s[l]] -= 1 l += 1 res = max(r-l + 1, res) return res
longest-repeating-character-replacement
Optimised window operator with hashmap
meechos
0
10
longest repeating character replacement
424
0.515
Medium
7,525
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2648185/Easy-and-well-explained
class Solution: def characterReplacement(self, s: str, k: int) -> int: sub=[0]*26 pointer=0 res=0 for index,value in enumerate(s): sub[ord(value)-ord('A')]+=1 if sum(sub)-max(sub)>k: char=s[pointer] sub[ord(char)-ord('A')]-=1 pointer+=1 res=max(res,sum(sub)) return res
longest-repeating-character-replacement
Easy and well explained
chuantianlin
0
12
longest repeating character replacement
424
0.515
Medium
7,526
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2626388/Python-%3A-Sliding-Window
class Solution: def characterReplacement(self, s: str, k: int) -> int: hm = {} ans = 0 l = 0 for r in range(len(s)): hm[s[r]] = 1 + hm.get(s[r],0) while (r-l+1) - max(hm.values()) > k: hm[s[l]] -= 1 l += 1 ans = max(ans, r-l+1) return ans
longest-repeating-character-replacement
Python : Sliding Window ✅
Khacker
0
95
longest repeating character replacement
424
0.515
Medium
7,527
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2565941/Python-solution-using-dict-and-sliding-windows
class Solution: def characterReplacement(self, s: str, k: int) -> int: start , end = 0 , 0 ump = {} maxFreq = 0 mini = 0 for end in range(len(s)): ump[s[end]] = ump.get(s[end] , 0) + 1 maxFreq = max(maxFreq , ump[s[end]]) if((end - start + 1) - maxFreq) > k: ump[s[start]] = ump.get(s[start] , 0) - 1 start += 1 mini = max(mini , end - start + 1) return mini
longest-repeating-character-replacement
Python solution using dict and sliding windows
rajitkumarchauhan99
0
64
longest repeating character replacement
424
0.515
Medium
7,528
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2546421/Simple-O(N)-python-solution-or-98.82-Faster
class Solution: def characterReplacement(self, s: str, k: int) -> int: res = 0 count = defaultdict(int) #Initialize count with defaultdict to increment count for new letters maxFreq = 0 #keep track of a count for a letter with maximum occurence rate l = 0 #left pointer of a window for r in range(len(s)): #r indicates right pointer of the window count[s[r]] += 1 maxFreq = max(maxFreq, count[s[r]]) if (r - l + 1) - maxFreq > k: #condition for decreasing window size count[s[l]] -= 1 l += 1 res = max(res, r - l + 1) return res
longest-repeating-character-replacement
Simple O(N) python solution | 98.82% Faster
KohsukeIde
0
210
longest repeating character replacement
424
0.515
Medium
7,529
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2526009/Longest-Repeating-Character-Replacement
class Solution: def characterReplacement(self, s: str, k: int) -> int: size = len(s) if size == 1: return size subStringHash = { 'A':0,'B':0,'C':0,'D':0,'E':0, 'F':0,'G':0,'H':0,'I':0,'J':0, 'K':0,'L':0,'M':0,'N':0,'O':0, 'P':0,'Q':0,'R':0,'S':0,'T':0, 'U':0,'V':0,'W':0,'X':0,'Y':0, 'Z':0 } res = min(size, 1 + k) left, right = 0, 1 subStringHash[s[left]] += 1 subStringHash[s[right]] += 1 while right < size: nonRepeatingLen = (right - left + 1) - max(subStringHash.values()) if nonRepeatingLen <= k: res = max(res, right - left + 1) right += 1 if right < size: subStringHash[s[right]] += 1 elif nonRepeatingLen > k: subStringHash[s[left]] -= 1 left += 1 return res
longest-repeating-character-replacement
Longest Repeating Character Replacement
ashfaque8198
0
63
longest repeating character replacement
424
0.515
Medium
7,530
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2514218/Python-or-3-Different-Solutions-or-Optimal-Complexity
class Solution: def characterReplacement(self, s: str, k: int) -> int: # Method 1 (Naive Approach): T.C: O(26*n) => O(n) S.C: O(26) => O(1) windowsize = 0 count = {} l = r = 0 ans = 0 for i in range(len(s)): windowsize += 1 count[s[r]] = 1 + count.get(s[r],0) maxvalue = max(count.values()) math = windowsize - maxvalue if math <= k: ans = max(ans,windowsize) else: while math>k: count[s[l]] -= 1 l += 1 windowsize -= 1 maxvalue = max(count.values()) math = windowsize - maxvalue r += 1 return ans # Method 2: T.C: O(26*n) => O(n) S.C: O(26) => O(1) # Slightly less cluttered than method 1 and slightly more optimised since we are # using if instead of while l = 0 count = {} ans = 0 r = 0 for i in range(len(s)): count[s[r]] = 1 + count.get(s[r],0) if (r-l+1) - max(count.values()) > k: count[s[l]] -= 1 l += 1 ans = max(ans,r-l+1) r += 1 return ans # Method 3: T.C: O(n) S.C: O(26) => O(1) # Most Optimised Solution l = 0 count = {} maxfreq = 0 ans = 0 for r in range(len(s)): count[s[r]] = 1 + count.get(s[r],0) maxfreq = max(maxfreq,count[s[r]]) if (r-l+1) - maxfreq > k: count[s[l]] -= 1 l += 1 ans = max(ans,(r-l+1)) return ans # Search with tag chawlashivansh for my solutions.
longest-repeating-character-replacement
Python | 3 Different Solutions | Optimal Complexity
chawlashivansh
0
94
longest repeating character replacement
424
0.515
Medium
7,531
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2447422/Python3-oror-Sliding-Window-oror-O(n)-solution
class Solution: def characterReplacement(self, s: str, k: int) -> int: count = {} res = 0 l = 0 maxf = 0 for r in range(len(s)): count[s[r]] = 1 + count.get(s[r], 0) maxf = max(maxf, count[s[r]]) while (r - l + 1) - maxf > k: count[s[l]] -= 1 l+=1 res = max(res, r - l + 1) return res
longest-repeating-character-replacement
Python3 || Sliding Window || O(n) solution
WhiteBeardPirate
0
117
longest repeating character replacement
424
0.515
Medium
7,532
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2430556/Longest-repeating-character-replacement-oror-Python3-oror-Sliding-Window
class Solution: def characterReplacement(self, s: str, k: int) -> int: map = {} max_freq = 1 ans = 1 i = 0 j = 0 # Acquire and release appproach while(j < len(s)): char_val = ord(s[j]) - ord('A') if(char_val in map): map[char_val] += 1 max_freq = max(max_freq, map[char_val]) else: map[char_val] = 1 length = j - i + 1 cond = (length - max_freq) <= k if(cond): ans = max(ans, length) else: while(i < j and j-i+1 - max_freq > k): char = ord(s[i]) - ord('A') map[char] -= 1 max_freq = self.get_max(map) i += 1 j += 1 return ans def get_max(self, map): max_freq = 0 for key in map: max_freq = max(max_freq, map[key]) return max_freq
longest-repeating-character-replacement
Longest repeating character replacement || Python3 || Sliding-Window
vanshika_2507
0
44
longest repeating character replacement
424
0.515
Medium
7,533
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2324218/Python3-Detailed-Explanation-with-Example
class Solution: def characterReplacement(self, s: str, k: int) -> int: start = 0 count = {} max_ = 0 for end in range(len(s)): # Update the most-common character including the current one count[s[end]] = count.get(s[end], 0) + 1 max_ = max(max_, count[s[end]]) # Only moves the start pointer (left end of the window) when it contains "too many kinds" of characters. if end - start + 1 > max_ + k: count[s[start]] -= 1 start += 1 return len(s) - start # It's acutally counting the length. # i.e. len(s) - 1 - start + 1, where len(s) -1 is the index of end pointer. # Because of the if statement above, the start pointer will stop wherever the length of the window equals to max_ + k. Try "ABCDEFG" and k=1 for example.
longest-repeating-character-replacement
Python3 Detailed Explanation with Example
geom1try
0
95
longest repeating character replacement
424
0.515
Medium
7,534
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2188279/Python-Solving-8-Substring-problem-with-same-template
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: hmap = {} begin, end, duplicate = 0, 0, False max_val = 0 while end < len(s): hmap[s[end]] = hmap.get(s[end], 0) + 1 if hmap[s[end]] > 1: duplicate = True end += 1 while duplicate: # duplicate in substring if hmap[s[begin]] > 1: duplicate = False hmap[s[begin]] -= 1 begin += 1 max_val = max(max_val, end-begin) return max_val
longest-repeating-character-replacement
[Python] Solving 8 Substring problem with same template
Gp05
0
76
longest repeating character replacement
424
0.515
Medium
7,535
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2188279/Python-Solving-8-Substring-problem-with-same-template
class Solution: def characterReplacement(self, s: str, k: int) -> int: start, end, duplicate= 0, 0, False length = 0 hashmap = {} while end < len(s): hashmap[s[end]] = hashmap.get(s[end], 0) + 1 if ((end - start + 1) - max(hashmap.values())) > k: duplicate = True else: length = max(length, (end-start+1)) end += 1 while duplicate and start < len(s): hashmap[s[start]] -= 1 start += 1 if ((end - start) - max(hashmap.values())) <= k: duplicate = False return length
longest-repeating-character-replacement
[Python] Solving 8 Substring problem with same template
Gp05
0
76
longest repeating character replacement
424
0.515
Medium
7,536
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2188279/Python-Solving-8-Substring-problem-with-same-template
class Solution: def length_of_longest_substring_two_distinct(self, s: str) -> int: start, end, duplicate= 0, 0, False length = 0 listmap = [] val = 0 while end < len(s): if s[end] not in listmap: val += 1 listmap.append(s[end]) if val > 2: duplicate = True else: length = max(length, (end-start+1)) end += 1 while duplicate: listmap.remove(s[start]) if s[start] not in listmap: val -= 1 start += 1 if val <= 2: duplicate = False return length
longest-repeating-character-replacement
[Python] Solving 8 Substring problem with same template
Gp05
0
76
longest repeating character replacement
424
0.515
Medium
7,537
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2188279/Python-Solving-8-Substring-problem-with-same-template
class Solution: def length_of_longest_substring_k_distinct(self, s: str, k: int) -> int: start, end, duplicate= 0, 0, False length = 0 listmap = [] val = 0 while end < len(s): if s[end] not in listmap: val += 1 listmap.append(s[end]) if val > k: duplicate = True else: length = max(length, (end-start+1)) end += 1 while duplicate: listmap.remove(s[start]) if s[start] not in listmap: val -= 1 start += 1 if val <= k: duplicate = False return length
longest-repeating-character-replacement
[Python] Solving 8 Substring problem with same template
Gp05
0
76
longest repeating character replacement
424
0.515
Medium
7,538
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2188279/Python-Solving-8-Substring-problem-with-same-template
class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: hmap = Counter(p) start, end, count = 0, 0, len(hmap) res = [] while end < len(s): if s[end] in hmap: hmap[s[end]] -= 1 if hmap[s[end]] == 0: count -= 1 end += 1 while count == 0: if (end-start) == len(p): res.append(start) if s[start] in hmap: hmap[s[start]] += 1 if hmap[s[start]] > 0: count += 1 start += 1 return res
longest-repeating-character-replacement
[Python] Solving 8 Substring problem with same template
Gp05
0
76
longest repeating character replacement
424
0.515
Medium
7,539
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2188279/Python-Solving-8-Substring-problem-with-same-template
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: hashmap = Counter(s1) start, end, counter = 0, 0, len(hashmap) while end < len(s2): if s2[end] in hashmap: hashmap[s2[end]] -= 1 if hashmap[s2[end]] == 0: counter -=1 end += 1 while counter == 0: if (end - start) == len(s1): return True if s2[start] in hashmap: hashmap[s2[start]] += 1 if hashmap[s2[start]] > 0: counter += 1 start += 1 return False
longest-repeating-character-replacement
[Python] Solving 8 Substring problem with same template
Gp05
0
76
longest repeating character replacement
424
0.515
Medium
7,540
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2188279/Python-Solving-8-Substring-problem-with-same-template
class Solution: def findSubstring(self, s: str, words: List[str]) -> List[int]: lenWords = len(words[0]) res = [] for i in range(lenWords): begin, end = (i + 0), (i + 0) hashmap = Counter(words) counter = len(hashmap) while end < len(s): if s[end:end+lenWords] in hashmap: hashmap[s[end:end+lenWords]] -= 1 if hashmap[s[end:end+lenWords]] == 0: counter -= 1 end += lenWords while counter == 0: if end - begin == (len(words) * lenWords): res.append(begin) if s[begin: begin+lenWords] in hashmap: hashmap[s[begin: begin+lenWords]] += 1 if hashmap[s[begin: begin+lenWords]] > 0: counter += 1 begin += lenWords return res
longest-repeating-character-replacement
[Python] Solving 8 Substring problem with same template
Gp05
0
76
longest repeating character replacement
424
0.515
Medium
7,541
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2188279/Python-Solving-8-Substring-problem-with-same-template
class Solution: def minWindow(self, s: str, t: str) -> str: minStr = "" minStrLen = len(s) + 1 hashmap = Counter(t) start, end, counter = 0, 0, len(hashmap) while end < len(s): if s[end] in hashmap: hashmap[s[end]] -= 1 if hashmap[s[end]] == 0: counter -= 1 end += 1 while counter == 0: if end - start < minStrLen: minStrLen = end - start minStr = s[start:end] if s[start] in hashmap: hashmap[s[start]] += 1 if hashmap[s[start]] > 0: counter += 1 start += 1 return minStr
longest-repeating-character-replacement
[Python] Solving 8 Substring problem with same template
Gp05
0
76
longest repeating character replacement
424
0.515
Medium
7,542
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2178054/Sliding-Window-Approach-(Optimized)
class Solution: def characterReplacement(self, s: str, k: int) -> int: length = len(s) l = 0 frequency = {} longestLength = 0 maxFrequency = 0 for r in range(length): frequency[s[r]] = 1 + frequency.get(s[r], 0) maxFrequency = max(maxFrequency, frequency[s[r]]) while (r - l + 1) - maxFrequency > k: frequency[s[l]] -= 1 l += 1 longestLength = max(longestLength, r - l + 1) return longestLength
longest-repeating-character-replacement
Sliding Window Approach (Optimized)
Vaibhav7860
0
148
longest repeating character replacement
424
0.515
Medium
7,543
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2045109/Python-Two-pointers-and-HashMap
class Solution: def characterReplacement(self, s: str, k: int) -> int: d = {} result = 0 left, right = 0, 0 while right < len(s): d[s[right]] = 1 + d.get(s[right], 0) while (right - left + 1) - max(d.values()) > k: d[s[left]] -= 1 left += 1 result = max(result, (right-left+1)) right += 1 return result
longest-repeating-character-replacement
Python - Two pointers and HashMap
TrueJacobG
0
164
longest repeating character replacement
424
0.515
Medium
7,544
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/2017423/Python-Sliding-Window%2BHashmap-O(n)
class Solution: def characterReplacement(self, s: str, k: int) -> int: n=len(s) dic=defaultdict(int) left=right=0 maxcnt=1 while right<n: dic[s[right]]+=1 maxcnt=max(maxcnt,dic[s[right]]) right+=1 if maxcnt+k<right-left: dic[s[left]]-=1 left+=1 return right-left
longest-repeating-character-replacement
Python Sliding Window+Hashmap O(n)
appleface
0
84
longest repeating character replacement
424
0.515
Medium
7,545
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1905621/Python-Optimal-solution
class Solution: def characterReplacement(self, s: str, k: int) -> int: # using a hash map to keep count of alphabets count={} # left counter l=0 res=0 # iterating over right counter for r in range(len(s)): # assigning values count[s[r]]=1+ count.get(s[r],0) # checking replacement condition while (r-l+1)- max(count.values())>k: # reducing count count[s[l]]-=1 # shifting left counter l+=1 # storing max res=max((r-l+1),res) return res
longest-repeating-character-replacement
Python Optimal solution
saty035
0
111
longest repeating character replacement
424
0.515
Medium
7,546
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1826423/Python-easy-to-read-and-understand-or-sliding-window
class Solution: def characterReplacement(self, s: str, k: int) -> int: d = {} n = len(s) i, ans = 0, 0 for j in range(n): d[s[j]] = d.get(s[j], 0) + 1 cnt = (j-i+1) - max(d.values()) while cnt > k: d[s[i]] -= 1 i = i+1 cnt = (j-i+1) - max(d.values()) ans = max(ans, j-i+1) return ans
longest-repeating-character-replacement
Python easy to read and understand | sliding window
sanial2001
0
241
longest repeating character replacement
424
0.515
Medium
7,547
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1616334/Most-intuitive-python-sliding-window-solution
class Solution: def characterReplacement(self, s: str, k: int) -> int: from collections import defaultdict count=defaultdict(int) n=len(s) left=0 res=0 for right in range(n): count[s[right]]+=1 while right-left+1-max(count.values())>k: count[s[left]]-=1 left+=1 res=max(res,right-left+1) return res
longest-repeating-character-replacement
Most intuitive python sliding window solution
Karna61814
0
134
longest repeating character replacement
424
0.515
Medium
7,548
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1569554/Easy-Python-Sliding-Window-Solution-or-80-Faster
class Solution: def characterReplacement(self, s: str, k: int) -> int: winS=0 maxL=-(1<<31) maxchar=0 freq={} for winE in range(len(s)): freq[s[winE]]=freq.get(s[winE],0)+1 maxchar=max(maxchar,freq[s[winE]]) if ((winE-winS+1)-maxchar)>k: if freq[s[winS]]==1: del freq[s[winS]] else: freq[s[winS]]-=1 winS+=1 maxL=max(maxL,winE-winS+1) return maxL
longest-repeating-character-replacement
Easy Python Sliding Window Solution | 80% Faster
AdityaTrivedi88
0
175
longest repeating character replacement
424
0.515
Medium
7,549
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1350922/GolangPython3-Solution-with-using-sliding-window
class Solution: def characterReplacement(self, s: str, k: int) -> int: start_window_idx = 0 repeat_len = 0 max_len = 0 ch2cnt = collections.defaultdict(int) for end_window_idx in range(len(s)): ch2cnt[s[end_window_idx]] += 1 repeat_len = max(repeat_len, ch2cnt[s[end_window_idx]]) if end_window_idx - start_window_idx + 1 - repeat_len > k: ch2cnt[s[start_window_idx]] -= 1 start_window_idx += 1 max_len = max(max_len, repeat_len + k) if max_len > len(s): return len(s) return max_len
longest-repeating-character-replacement
[Golang/Python3] Solution with using sliding window
maosipov11
0
88
longest repeating character replacement
424
0.515
Medium
7,550
https://leetcode.com/problems/longest-repeating-character-replacement/discuss/1327422/python3-solution-sliding-window-and-hash-map-O(n)-time-complexity.
class Solution: def characterReplacement(self, s: str, k: int) -> int: res = 0 left = 0 count = {} maxf = 0 for right in range(len(s)): count[s[right]] = 1 + count.get(s[right],0) maxf = max(maxf, count[s[right]]) while (right-left+1) - maxf > k: count[s[left]] -= 1 left+=1 res = max(res, right-left+1) return(res)
longest-repeating-character-replacement
python3 solution sliding window and hash map O(n) time complexity.
pravishbajpai06
0
485
longest repeating character replacement
424
0.515
Medium
7,551
https://leetcode.com/problems/construct-quad-tree/discuss/874250/Python3-building-tree-recursively
class Solution: def construct(self, grid: List[List[int]]) -> 'Node': def fn(x0, x1, y0, y1): """Return QuadTree subtree.""" val = {grid[i][j] for i, j in product(range(x0, x1), range(y0, y1))} if len(val) == 1: return Node(val.pop(), True, None, None, None, None) tl = fn(x0, (x0+x1)//2, y0, (y0+y1)//2) tr = fn(x0, (x0+x1)//2, (y0+y1)//2, y1) bl = fn((x0+x1)//2, x1, y0, (y0+y1)//2) br = fn((x0+x1)//2, x1, (y0+y1)//2, y1) return Node(None, False, tl, tr, bl, br) n = len(grid) return fn(0, n, 0, n)
construct-quad-tree
[Python3] building tree recursively
ye15
2
167
construct quad tree
427
0.663
Medium
7,552
https://leetcode.com/problems/construct-quad-tree/discuss/2709862/Python-easy-to-understand
class Solution: def construct(self, grid: List[List[int]]) -> 'Node': bits = {1:0,0:0} for row in grid: for i in row: bits[i] += 1 total_bits = len(grid) ** 2 if bits[1] == total_bits: return Node(1, True, None, None, None, None) if bits[0] == total_bits: return Node(0, True, None, None, None, None) mid = len(grid)//2 return Node(1, False, self.construct(list(map(lambda bits: bits[:mid], grid[:mid]))), self.construct(list(map(lambda bits: bits[mid:], grid[:mid]))), self.construct(list(map(lambda bits: bits[:mid], grid[mid:]))), self.construct(list(map(lambda bits: bits[mid:], grid[mid:]))))
construct-quad-tree
[Python] easy to understand
scrptgeek
0
16
construct quad tree
427
0.663
Medium
7,553
https://leetcode.com/problems/construct-quad-tree/discuss/2642818/Python-O(N2)-O(1)
class Solution: def construct(self, grid: List[List[int]]) -> 'Node': def helper(left, right, down, up): if left == right and up == down: return Node(grid[up][left], 1, None, None, None, None) midlr = (left + right) // 2 midud = (down + up) // 2 bl = helper(left, midlr, midud + 1, up) br = helper(midlr + 1, right, midud + 1, up) tl = helper(left, midlr, down, midud) tr = helper(midlr + 1, right, down, midud) if tl.val == tr.val == bl.val == br.val and tl.isLeaf and tr.isLeaf and bl.isLeaf and br.isLeaf: return Node(tl.val, 1, None, None, None, None) return Node(1, 0, tl, tr, bl, br) return helper(0, len(grid) - 1, 0, len(grid) - 1)
construct-quad-tree
Python - O(N^2), O(1)
Teecha13
0
11
construct quad tree
427
0.663
Medium
7,554
https://leetcode.com/problems/construct-quad-tree/discuss/2276162/Python-Iterative-Tree-Construction-(Simpler-than-Recursion)
class Solution: def construct(self, grid: List[List[int]]) -> 'Node': level = [[Node(val, True, None, None, None, None) for val in row] for row in grid] while len(level) * len(level[0]) != 1: print([[node.val for node in row] for row in level]) height = len(level) width = len(level[0]) root = [] for i in range(0, height, 2): row = [] for j in range(0, width, 2): isLeaf = (level[i][j].val == level[i+1][j].val and level[i+1][j].val == level[i][j+1].val and level[i][j+1].val == level[i+1][j+1].val) if isLeaf and level[i][j].val != None: row.append(Node(level[i][j].val, True, None, None, None, None)) else: row.append(Node(None, False, level[i][j], level[i][j+1], level[i+1][j], level[i+1][j+1])) root.append(row) level = root return level[0][0]
construct-quad-tree
Python, Iterative Tree Construction (Simpler than Recursion?)
boris17
0
57
construct quad tree
427
0.663
Medium
7,555
https://leetcode.com/problems/construct-quad-tree/discuss/1365149/Recursive-short-Python-less-10-Lines
class Solution: def construct(self, grid: List[List[int]]) -> 'Node': def shouldSplit(i,j,n) -> bool: return len(set(x for row in grid[i:i+n] for x in row[j:j+n])) > 1 def f(i,j,n): if shouldSplit(i,j,n): s = n//2 return Node(None,False,f(i,j,s),f(i,j+s,s),f(i+s,j,s),f(i+s,j+s,s)) else: return Node(grid[i][j],True,None,None,None,None) return f(0,0,len(grid))
construct-quad-tree
Recursive short Python < 10 Lines
worker-bee
0
166
construct quad tree
427
0.663
Medium
7,556
https://leetcode.com/problems/construct-quad-tree/discuss/681140/Simple-Python3-Recursion
class Solution: def construct(self, grid: List[List[int]]) -> 'Node': if not grid: return node = Node() grid_sum, n = sum(map(sum, grid)), len(grid) if grid_sum == (n * n) or grid_sum == 0: node.val, node.isLeaf = grid_sum // (n * n), True return node node.isLeaf, node.val = False, 1 node.topLeft = self.construct([[j for j in i[:n//2]] for i in grid[:n//2]]) node.topRight = self.construct([[j for j in i[n//2:]] for i in grid[:n//2]]) node.bottomLeft = self.construct([[j for j in i[:n//2]] for i in grid[n//2:]]) node.bottomRight = self.construct([[j for j in i[n//2:]] for i in grid[n//2:]]) return node
construct-quad-tree
Simple Python3 Recursion
whissely
0
175
construct quad tree
427
0.663
Medium
7,557
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532005/Python-BFS
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: result = [] q = deque([root] if root else []) while q: result.append([]) for _ in range(len(q)): node = q.popleft() result[-1].append(node.val) q.extend(node.children) return result
n-ary-tree-level-order-traversal
Python, BFS
blue_sky5
14
1,300
n ary tree level order traversal
429
0.706
Medium
7,558
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2533492/Python-Elegant-and-Short-or-BFS-%2B-DFS-or-Generators
class Solution: """ Time: O(n) Memory: O(n) """ def levelOrder(self, root: Optional['Node']) -> List[List[int]]: if root is None: return [] queue = deque([root]) levels = [] while queue: levels.append([]) for _ in range(len(queue)): node = queue.popleft() levels[-1].append(node.val) queue.extend(node.children) return levels
n-ary-tree-level-order-traversal
Python Elegant & Short | BFS + DFS | Generators
Kyrylo-Ktl
2
83
n ary tree level order traversal
429
0.706
Medium
7,559
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2533492/Python-Elegant-and-Short-or-BFS-%2B-DFS-or-Generators
class Solution: """ Time: O(n) Memory: O(n) """ def levelOrder(self, root: Optional['Node']) -> List[List[int]]: levels = defaultdict(list) for node, depth in self._walk(root): levels[depth].append(node.val) return [levels[d] for d in sorted(levels)] @classmethod def _walk(cls, root: Optional['Node'], depth: int = 0) -> Generator: if root is None: return yield root, depth for child in root.children: yield from cls._walk(child, depth + 1)
n-ary-tree-level-order-traversal
Python Elegant & Short | BFS + DFS | Generators
Kyrylo-Ktl
2
83
n ary tree level order traversal
429
0.706
Medium
7,560
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/1095683/PythonPython3-N-ary-Tree-Level-Order-Traversal
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] ans = [] level = [root] while level: ans.append([node.val for node in level]) level = [kid for node in level for kid in node.children if kid] return ans
n-ary-tree-level-order-traversal
[Python/Python3] N-ary Tree Level Order Traversal
newborncoder
2
171
n ary tree level order traversal
429
0.706
Medium
7,561
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2533959/Python-Recursive-DFS-Solution
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] res = [] levels = set() def dfs(node, level): if level not in levels: levels.add(level) res.append([]) res[level].append(node.val) for child in node.children: dfs(child, level + 1) dfs(root, 0) return res
n-ary-tree-level-order-traversal
[Python] Recursive DFS Solution
sreenithishb
1
34
n ary tree level order traversal
429
0.706
Medium
7,562
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2533561/100-or-Classic-BFS-.-2-ways-in-each-language-(C%2B%2B-Go-Python-TsJs-Java)
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: r = [] if not root: return r dq = deque() dq.append(root) while dq: temp = [] size = len(dq) for _ in range(size): node = dq.popleft() for n in node.children: dq.append(n) temp.append(node.val) r.append(temp) return r ```py # Python . 2 ```py class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: r = [] if not root: return r r.append([root.val]) dq = deque() dq.append(root) while dq: temp = [] size = len(dq) for _ in range(size): node = dq.popleft() for n in node.children: dq.append(n) temp.append(n.val) if temp: r.append(temp) return r
n-ary-tree-level-order-traversal
🌻 100% | Classic BFS . 2 ways in each language (C++, Go, Python, Ts/Js, Java)
nuoxoxo
1
35
n ary tree level order traversal
429
0.706
Medium
7,563
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532377/Easy-python-solution-18-lines-only
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if root is None: return [] #print(root.children) valList=[[root.val]] flst=[] xlst=[] lst=[root] while lst: x=lst.pop(0) if x.children: for i in x.children: flst.append(i) xlst.append(i.val) if len(lst)==0: lst=flst[:] flst=[] if xlst: valList.append(xlst) xlst=[] return valList
n-ary-tree-level-order-traversal
Easy python solution 18 lines only
shubham_1307
1
11
n ary tree level order traversal
429
0.706
Medium
7,564
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2084329/Python3-BFS-Iterative-Solution
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: #if root is null directly return empty list if not root: return [] #create queue data structure queue=collections.deque() #add the root node to the queue queue.append(root) res=[] while(queue): lst=[] #traverse through all the elements of one level for i in range(len(queue)): node=queue.popleft() if node: lst.append(node.val) #append all the child nodes of the current node to the queue for j in node.children: queue.append(j) if lst: res.append(lst) return res
n-ary-tree-level-order-traversal
Python3 BFS Iterative Solution
rohith4pr
1
95
n ary tree level order traversal
429
0.706
Medium
7,565
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/1725735/python-Faster-than-78
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: groups = [] queue = deque() if root is not None: queue.append((root,0)) while len(queue)>0: current,dist = queue.popleft() if len(groups)-1>=dist: groups[dist].append(current.val) else: groups.append([current.val]) for i in current.children: queue.append((i,dist+1)) return groups
n-ary-tree-level-order-traversal
python Faster than 78%
nisal_sasmitha
1
51
n ary tree level order traversal
429
0.706
Medium
7,566
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/1642817/While-loop-97-speed
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] ans = [] level = [root] while level: new_level = [] level_values = [] for node in level: level_values.append(node.val) if node.children: new_level.extend(node.children) ans.append(level_values) level = new_level return ans
n-ary-tree-level-order-traversal
While loop, 97% speed
EvgenySH
1
90
n ary tree level order traversal
429
0.706
Medium
7,567
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/1387969/Super-simple-Python-solution
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] output=[] level=[root] while level: currLevel=[] nextLevel=[] for node in level: currLevel.append(node.val) for child in node.children: nextLevel.append(child) output.append(currLevel) level=nextLevel return output
n-ary-tree-level-order-traversal
Super simple Python 🐍 solution
InjySarhan
1
90
n ary tree level order traversal
429
0.706
Medium
7,568
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/840366/Python3-BFS
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: ans = [] if root: queue = [root] while queue: newq, vals = [], [] for x in queue: vals.append(x.val) newq.extend(x.children) ans.append(vals) queue = newq return ans
n-ary-tree-level-order-traversal
[Python3] BFS
ye15
1
41
n ary tree level order traversal
429
0.706
Medium
7,569
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/302450/Python-beats-98-recursive
class Solution: def levelOrder(self, root) -> List[List[int]]: output = [] if root is not None: output.append([root.val]) self.trav(root.children, 0, output) output.pop() return output def trav(self, node, deep, output): deep += 1 if (len(output) - 1 < deep): output.append([]) for x in node: output[deep].append(x.val) if x.children is not None: self.trav(x.children, deep, output)
n-ary-tree-level-order-traversal
Python beats 98% recursive
ht921005
1
444
n ary tree level order traversal
429
0.706
Medium
7,570
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2765535/Python-solution-or-BFS
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: levels = [] def bfs(node, level): if node: if level >= len(levels): levels.append([]) levels[level].append(node.val) for child in node.children: bfs(child, level + 1) bfs(root, 0) return levels
n-ary-tree-level-order-traversal
Python solution | BFS
maomao1010
0
2
n ary tree level order traversal
429
0.706
Medium
7,571
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2718603/N-ary-Tree-Level-Order-Traversal-in-Python
class Solution(object): def levelOrder(self, root): if not root: return [] output=[] queue=[root] while queue: b=[] for i in range(len(queue)): a=queue.pop(0) b.append(a.val) for j in a.children: queue.append(j) output.append(b) return output
n-ary-tree-level-order-traversal
N-ary Tree Level Order Traversal in Python
siddharth2205
0
3
n ary tree level order traversal
429
0.706
Medium
7,572
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2543182/C%2B%2BPython-or-Easy-solution-or-BFS
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root : return [] ans, queue = [], [root] while queue : row = [] N = len(queue) for _ in range(N) : t = queue.pop(0) for node in t.children : queue.append(node) row.append(t.val) ans.append(row) return ans
n-ary-tree-level-order-traversal
[C++/Python] | Easy solution | BFS
prakharrai1609
0
7
n ary tree level order traversal
429
0.706
Medium
7,573
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2536155/python-oror-easy-oror-default-dict-oror-beginner-friendly
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: d=defaultdict(list) ans=[] def solve(root,level): if root==None: return else: d[level].append(root.val) for c in root.children: solve(c,level+1) solve(root,0) for key,value in d.items(): ans.append(value) return ans
n-ary-tree-level-order-traversal
python || easy || default dict || beginner friendly
minato_namikaze
0
4
n ary tree level order traversal
429
0.706
Medium
7,574
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2535711/Python-or-Queue
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: def levelOrderTrav(root): if not root: return [] q = collections.deque() q.append(root) res = [] while q: curLevel = [] for _ in range(len(q)): curNode = q.popleft() for node in curNode.children: q.append(node) curLevel.append(curNode.val) res.append(curLevel) return res return levelOrderTrav(root)
n-ary-tree-level-order-traversal
Python | Queue
Mark5013
0
9
n ary tree level order traversal
429
0.706
Medium
7,575
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2535446/Python-Solution-with-Dynamic-Programming
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: children = [root] result = [] while not all(i is None for i in children): level_values = [] new_children = [] for node in children: level_values.append(node.val) for child in node.children: new_children.append(child) result.append(level_values) children = new_children return result
n-ary-tree-level-order-traversal
Python Solution with Dynamic Programming
DyHorowitz
0
3
n ary tree level order traversal
429
0.706
Medium
7,576
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2535446/Python-Solution-with-Dynamic-Programming
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: children = [root] result = [] while not all(i is None for i in children): new_children = [] for node in children: for child in node.children: new_children.append(child) result.append([x.val for x in children]) children = new_children return result
n-ary-tree-level-order-traversal
Python Solution with Dynamic Programming
DyHorowitz
0
3
n ary tree level order traversal
429
0.706
Medium
7,577
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2534420/Python3-DFS-48ms-faster-than-98
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: def helper(root, level, ans): if not root: return [] if len(ans)<level: ans.append([]) ans[level-1].append(root.val) for child in root.children: helper(child, level+1, ans) ans=[] helper(root, 1, ans) return ans
n-ary-tree-level-order-traversal
Python3 DFS 48ms faster than 98%
mrprashantkumar
0
6
n ary tree level order traversal
429
0.706
Medium
7,578
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2534374/Simple-Python-Solution-oror-BFS
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: ans = [] cur_level, cur_level_nodes = 0, [] # initialise and add root in queue with level as 0 q = deque() q.append((root, 0)) while q: # get first element from the queue and its resp. level node, level = q.popleft() if node is None: continue # if level is same, append nodes value # else change level and append nodes value if level == cur_level: cur_level_nodes.append(node.val) else: ans.append(cur_level_nodes) cur_level = level cur_level_nodes = [node.val] # add children in queue with level as parent's level + 1 for child in node.children: q.append((child, level + 1)) if len(cur_level_nodes): ans.append(cur_level_nodes) return ans
n-ary-tree-level-order-traversal
Simple Python Solution || BFS
wilspi
0
7
n ary tree level order traversal
429
0.706
Medium
7,579
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2534089/Python-easy-to-understand-BFS-iterative-stack
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] result = [] stack = [(root,)] while stack: new_level = [] local_result = [] nodes = stack.pop() if not nodes: continue for node in nodes: local_result.append(node.val) for child in node.children: new_level.append(child) result.append(local_result) stack.append(new_level) return result
n-ary-tree-level-order-traversal
[Python] easy to understand BFS iterative stack
dlog
0
3
n ary tree level order traversal
429
0.706
Medium
7,580
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2533626/Python-BFS-using-queue
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return root que = deque() que.append(root) result = [] while que: res = [] for i in range(len(que)): node = que.popleft() if node: res.append(node.val) if node.children: for child in node.children: que.append(child) result.append(res) return result
n-ary-tree-level-order-traversal
Python - BFS using queue
supersid1695
0
9
n ary tree level order traversal
429
0.706
Medium
7,581
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2533115/Python-or-bfs-or-O(n)-Time-or-O(n)-Space
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] stack = [] stack.append(root) ans = [] while len(stack): size = len(stack) l = [] while size: node = stack[0] del stack[0] l.append(node.val) for i in node.children: stack.append(i) size -= 1 ans.append(l) return ans
n-ary-tree-level-order-traversal
Python | bfs | O(n) Time | O(n) Space
coolakash10
0
3
n ary tree level order traversal
429
0.706
Medium
7,582
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2533056/Python-solution-easy-to-understand-bfs
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] node = [root] res = [] while(node): currLvl = [] nxtNode = [] for x in range(len(node)): currLvl.append(node[x].val) nxtNode.extend(node[x].children) res.append(currLvl) node = nxtNode return res
n-ary-tree-level-order-traversal
Python solution - easy to understand - bfs
MacPatil23
0
3
n ary tree level order traversal
429
0.706
Medium
7,583
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2533012/EASY-PYTHON3-SOLUTION
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: result = [] q = deque([root]) if root else None while q: level = [] len_ = len(q) for _ in range(len_): node = q.popleft() level.append(node.val) for child in node.children: q.append(child) result.append(level) return result
n-ary-tree-level-order-traversal
🔥 EASY PYTHON3 SOLUTION 🔥
rajukommula
0
1
n ary tree level order traversal
429
0.706
Medium
7,584
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532490/Python3-90.32-or-O(N)-BFS-Solution-or-Beginner-Friendly-Pythonic
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: # edge: if not root: return [] bfs_q = [root] ans = [] while bfs_q: lvl_leng = len(bfs_q) lvl = [] for _ in range(lvl_leng): node = bfs_q[0] bfs_q = bfs_q[1:] lvl.append(node.val) bfs_q += node.children ans.append(lvl) return ans
n-ary-tree-level-order-traversal
Python3 90.32% | O(N) BFS Solution | Beginner Friendly, Pythonic
doneowth
0
3
n ary tree level order traversal
429
0.706
Medium
7,585
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532341/Python-bfs
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] ans = [] queue = deque() queue.append(root) while queue: nq = deque() temp = [] while queue: node = queue.popleft() nq+= node.children temp.append(node.val) queue = nq ans.append(temp) return ans
n-ary-tree-level-order-traversal
Python bfs
li87o
0
5
n ary tree level order traversal
429
0.706
Medium
7,586
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532219/Python-BFS-better-than-90.40
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] out=[] queue=deque([root]) while queue: size = len(queue) temp=[] while size>0: node = queue.popleft() temp.append(node.val) for i in range(len(node.children)): queue.append(node.children[i]) size-=1 out.append(temp) return out
n-ary-tree-level-order-traversal
Python, BFS better than 90.40%
omarihab99
0
10
n ary tree level order traversal
429
0.706
Medium
7,587
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532162/Python3-or-Easy-to-Understand-or-BFS-or-Efficient
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] q = deque([root]) traversal = [] while q: level = [] for _ in range(len(q)): node = q.popleft() level.append(node.val) if node.children: for child in node.children: q.append(child) traversal.append(level) return traversal
n-ary-tree-level-order-traversal
✅Python3 | Easy to Understand | BFS | Efficient
thesauravs
0
8
n ary tree level order traversal
429
0.706
Medium
7,588
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532124/Python-or-BFS
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: ans = [] def bfs(node, lvl): nonlocal ans if not node: return ## If this is a new level, we make a blank array inside ans if len(ans) < lvl + 1: ans.append([]) ans[lvl].append(node.val) ## Traverse for each child for c in node.children: bfs(c, lvl + 1) bfs(root, 0) return ans
n-ary-tree-level-order-traversal
Python | BFS
prithuls
0
4
n ary tree level order traversal
429
0.706
Medium
7,589
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2531986/Python-or-FIFO-Queue
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if root is None: return [] nodeQueue = deque([(root, 0)]); LOT = [] while nodeQueue: currentNode, level = nodeQueue.popleft() if len(LOT) == level: LOT.append([currentNode.val]) else: LOT[level].append(currentNode.val) for node in currentNode.children: if node is not None: nodeQueue.append((node, level + 1)) return LOT
n-ary-tree-level-order-traversal
Python | FIFO Queue
sr_vrd
0
6
n ary tree level order traversal
429
0.706
Medium
7,590
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2355456/Python3-O(n)-Solution-or-O(nlgn)-Space-though
class Solution: #Time-Complexity: LevelOrder function always traverse each and every node in #n-ary tree input! Also, helper function traverses each and every non-null node #once in dfs manner! -> O(n), where n is number of nodes in n-ary tree input! #Space-Complexity: O(n + (lgn - 1)* n), since answer array has lgn number of #1d arrays and each of them in worst case has at most lgn -1 * n nodes for #the last level in tree! -> O(nlgn) def levelOrder(self, root: 'Node') -> List[List[int]]: #base case: empty tree! if(not root): return [] #in our queue, we will store the node as well as the edges it is away #from the root node! #queue[i] = [node, edges_it_took] queue = collections.deque() levels_in_tree = self.helper(root) answer = [[] for _ in range(levels_in_tree)] queue.append([root, 0]) #do bfs while queue is non-empty! while queue: cur_node, edges_away = queue.popleft() #process current node! answer[edges_away] = answer[edges_away] + [cur_node.val] #iterate through each of the current node's children and add to queue #to be processed later! for children in cur_node.children: queue.append([children, edges_away + 1]) return answer #we need to height of the tree! def helper(self, root): #base case: root is empty! if(not root): return #leaf node case! if(not root.children): return 1 else: max_height = 0 for children in root.children: max_height = max(max_height, self.helper(children)) return max_height + 1
n-ary-tree-level-order-traversal
Python3 O(n) Solution | O(nlgn) Space though
JOON1234
0
15
n ary tree level order traversal
429
0.706
Medium
7,591
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2349746/Python-3-oror-98-oror-Recursive
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: lst = [] def traversal(root,height): if root == None: return if height > len(lst)-1: lst.append([]) lst[height].append(root.val) for child in root.children: traversal(child,height+1) traversal(root,0) return lst
n-ary-tree-level-order-traversal
Python 3 || 98% || Recursive
tq326
0
32
n ary tree level order traversal
429
0.706
Medium
7,592
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2210233/Python-Simple-solution
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: res = [] if not root: return res q = deque([root]) while q: temp = [] for _ in range(len(q)): node = q.popleft() if node: temp.append(node.val) for child in node.children: q.append(child) res.append(temp) return res
n-ary-tree-level-order-traversal
Python Simple solution
Gp05
0
13
n ary tree level order traversal
429
0.706
Medium
7,593
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2053316/Python-%22DFS%22-94-Memory
class Solution: def __init__(self): self.res = [] def levelOrder(self, root: 'Node') -> List[List[int]]: def dfs(root, stage): if not root: return if len(self.res)-1 < stage: self.res.append([root.val]) else: self.res[stage].append(root.val) for node in root.children: dfs(node, stage+1) dfs(root, 0) return self.res
n-ary-tree-level-order-traversal
Python "DFS" 94% Memory
codeee5141
0
31
n ary tree level order traversal
429
0.706
Medium
7,594
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/1964100/Python3-simple-solution
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] q = [root] res = [[root.val]] while q: x = [] c = len(q) for i in range(c): z = q.pop(0) if z.children: for j in z.children: x += [j.val] q += z.children if x: res.append(x) return res
n-ary-tree-level-order-traversal
Python3 simple solution
EklavyaJoshi
0
26
n ary tree level order traversal
429
0.706
Medium
7,595
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/1898063/Python-easy-understanding-solution-with-comment
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return None queue = collections.deque([root]) res = [] while queue: i, l = 0, len(queue) # l is the number of nodes in current level temp_res = [] # temp_res record node.val at current level while i < l: # i: to iterate through this level cur = queue.popleft() temp_res.append(cur.val) for c in cur.children: queue.append(c) i += 1 res.append(temp_res) # After dealing a level, add temp_res which recorded current level to final res return res
n-ary-tree-level-order-traversal
Python easy - understanding solution with comment
byroncharly3
0
33
n ary tree level order traversal
429
0.706
Medium
7,596
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1550377/Python-Recursion%3A-Easy-to-understand-with-Explanation
class Solution: def flatten(self, head: 'Node') -> 'Node': def getTail(node): prev = None while node: _next = node.next if node.child: # ... <-> node <-> node.child <-> ... node.next = node.child node.child = None node.next.prev = node # get the end node of the node.child list prev = getTail(node.next) if _next: # ... <-> prev (end node) <-> _next (originally node.next) <-> ... _next.prev = prev prev.next = _next else: prev = node node = _next # loop through the list of nodes return prev # return end node getTail(head) return head
flatten-a-multilevel-doubly-linked-list
Python Recursion: Easy-to-understand with Explanation
zayne-siew
6
501
flatten a multilevel doubly linked list
430
0.595
Medium
7,597
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/645406/Python-sol-by-recursion.-80%2B-w-Visualization
class Solution: def flatten(self, head: 'Node') -> 'Node': def helper(head) -> 'None': prev, current_node = None, head while current_node: if current_node.child: # flatten child linked list current_child, current_tail = current_node.child, helper(current_node.child) # After next level flattening is completed # Handle for the concatenation between current linked list and child linked list # current node's child points to None after flattening current_node.child = None ## Update the linkage between original next and current tail original_next = current_node.next if original_next: original_next.prev = current_tail current_tail.next = original_next ## Update the linkage between current node and current child current_node.next, current_child.prev = current_child, current_node # update prev and cur, move to next position prev, current_node = current_tail, original_next else: # update prev and cur, move to next position prev, current_node = current_node, current_node.next # return tail node return prev # ------------------------------------------------------------------------------ helper(head) return head
flatten-a-multilevel-doubly-linked-list
Python sol by recursion. 80%+ [w/ Visualization ]
brianchiang_tw
5
756
flatten a multilevel doubly linked list
430
0.595
Medium
7,598
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/652275/Python3-recursive-and-iterative-solution
class Solution: def flatten(self, head: 'Node') -> 'Node': def fn(node): """Recursively flatten doubly-linked list.""" if not node: return tail = node if node.child: tail = fn(node.child) tail.next = node.next if node.next: node.next.prev = tail node.next = node.child node.child.prev = node node.child = None return fn(node.next) or tail fn(head) return head
flatten-a-multilevel-doubly-linked-list
[Python3] recursive & iterative solution
ye15
3
118
flatten a multilevel doubly linked list
430
0.595
Medium
7,599