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/fair-candy-swap/discuss/1368022/Python3-dollarolution | class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
x, y, j = sum(aliceSizes), sum(bobSizes), set(bobSizes)
s = (x + y)//2
for i in aliceSizes:
z = s - (x - i)
if z in j:
return [i,z] | fair-candy-swap | Python3 $olution | AakRay | 0 | 147 | fair candy swap | 888 | 0.605 | Easy | 14,400 |
https://leetcode.com/problems/fair-candy-swap/discuss/1100675/Python3-simple-solution-using-set | class Solution:
def fairCandySwap(self, A, B):
Sa = sum(A)
Sb = sum(B)
setB = set(B)
for x in A:
if x + (Sb - Sa) / 2 in setB:
return [x, x + (Sb - Sa) / 2] | fair-candy-swap | Python3 simple solution using set | EklavyaJoshi | 0 | 200 | fair candy swap | 888 | 0.605 | Easy | 14,401 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/946726/Python3-consistent-soln-for-105-106-and-889 | class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
mp = {x: i for i, x in enumerate(inorder)} # relative position
root = None
stack = []
for x in preorder:
if not root: root = node = TreeNode(x)
elif mp[x] < mp[stack[-1].val]: stack[-1].left = node = TreeNode(x)
else:
while stack and mp[stack[-1].val] < mp[x]: node = stack.pop() # retrace
node.right = node = TreeNode(x)
stack.append(node)
return root | construct-binary-tree-from-preorder-and-postorder-traversal | [Python3] consistent soln for 105, 106 and 889 | ye15 | 3 | 128 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,402 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/946726/Python3-consistent-soln-for-105-106-and-889 | class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
mp = {x: i for i, x in enumerate(inorder)} # relative position
root = None
stack = []
for x in reversed(postorder):
if not root: root = node = TreeNode(x)
elif mp[x] > mp[stack[-1].val]: stack[-1].right = node = TreeNode(x)
else:
while stack and mp[stack[-1].val] > mp[x]: node = stack.pop() # retrace
node.left = node = TreeNode(x)
stack.append(node)
return root | construct-binary-tree-from-preorder-and-postorder-traversal | [Python3] consistent soln for 105, 106 and 889 | ye15 | 3 | 128 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,403 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/946726/Python3-consistent-soln-for-105-106-and-889 | class Solution:
def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:
mp = {x: i for i, x in enumerate(post)}
root = None
stack = []
for x in pre:
if not root: root = node = TreeNode(x)
elif mp[x] < mp[stack[-1].val]: stack[-1].left = node = TreeNode(x)
else:
while mp[stack[-1].val] < mp[x]: stack.pop() # retrace
stack[-1].right = node = TreeNode(x)
stack.append(node)
return root | construct-binary-tree-from-preorder-and-postorder-traversal | [Python3] consistent soln for 105, 106 and 889 | ye15 | 3 | 128 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,404 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/2242505/Python3-Same-template-to-solve-3-Binary-tree-construction-problems | class Solution:
def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not preorder or not postorder:
return
root = TreeNode(preorder[0])
if len(preorder) == 1:
return root
index = postorder.index(preorder[1])
root.left = self.constructFromPrePost(preorder[1:index+2], postorder[:index+1])
root.right = self.constructFromPrePost(preorder[index+2:], postorder[index+1:-1])
return root | construct-binary-tree-from-preorder-and-postorder-traversal | [Python3] Same template to solve 3 Binary tree construction problems | Gp05 | 1 | 60 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,405 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/2242505/Python3-Same-template-to-solve-3-Binary-tree-construction-problems | class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if not preorder or not inorder:
return
root = TreeNode(preorder[0])
mid = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1: mid+1], inorder[:mid])
root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:])
return root | construct-binary-tree-from-preorder-and-postorder-traversal | [Python3] Same template to solve 3 Binary tree construction problems | Gp05 | 1 | 60 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,406 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/2242505/Python3-Same-template-to-solve-3-Binary-tree-construction-problems | class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not postorder or not inorder:
return
root = TreeNode(postorder[-1])
mid = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:mid], postorder[:mid])
root.right = self.buildTree(inorder[mid+1:], postorder[mid:-1])
return root | construct-binary-tree-from-preorder-and-postorder-traversal | [Python3] Same template to solve 3 Binary tree construction problems | Gp05 | 1 | 60 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,407 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/1940467/Python-3-reursive-9-line | class Solution:
def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not preorder: return None
n = len(preorder)
if n == 1:
return TreeNode(preorder[0])
root = TreeNode(preorder[0])
idx = postorder.index(preorder[1])
root.left = self.constructFromPrePost(preorder[1:idx + 2], postorder[:idx + 1])
root.right = self.constructFromPrePost(preorder[idx + 2:], postorder[idx + 1:- 1])
return root | construct-binary-tree-from-preorder-and-postorder-traversal | Python 3 reursive 9-line | gulugulugulugulu | 1 | 162 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,408 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/946704/Python3-stack-O(N) | class Solution:
def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:
mp = {x: i for i, x in enumerate(post)}
root = None
stack = []
for x in pre:
if not root: root = node = TreeNode(x)
elif mp[x] < mp[stack[-1].val]: stack[-1].left = node = TreeNode(x)
else:
while mp[stack[-1].val] < mp[x]: stack.pop()
stack[-1].right = node = TreeNode(x)
stack.append(node)
return root | construct-binary-tree-from-preorder-and-postorder-traversal | [Python3] stack O(N) | ye15 | 1 | 86 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,409 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/2190054/Python-O(n)-approach | class Solution:
def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
def helper(pstart,pend):
if pstart>pend: # base case
return None
if pstart==pend: # whenever there is single node
node = TreeNode(postorder[pstart]) # no need to move left, so return the node
self.preIndex+=1
return node
root = TreeNode(preorder[self.preIndex])
self.preIndex+=1
left = preorder[self.preIndex]
index = indices[left]
root.left = helper(pstart,index) #forms left part in post order traversal
root.right = helper(index+1,pend-1) # forms right part in post order traversal
return root
self.preIndex = 0 # used to find root
indices = {val:ind for ind,val in enumerate(postorder)} # value:index dictionary
return helper(0,len(postorder)-1)
# TC: O(n) and SC:O(n) | construct-binary-tree-from-preorder-and-postorder-traversal | Python O(n) approach | dsalgobros | 0 | 34 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,410 |
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/1361864/Python-3-preorder-or-O(n)-T-or-O(n)-S | class Solution:
def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> TreeNode:
pre_index, post_index = 0, 0
def dfs(prev_val):
nonlocal pre_index
nonlocal post_index
if prev_val == postorder[post_index]:
return None
node = TreeNode(preorder[pre_index])
pre_index += 1
node.left = dfs(node.val)
node.right = dfs(node.val)
post_index += 1
return node
return dfs(-1) | construct-binary-tree-from-preorder-and-postorder-traversal | Python 3 preorder | O(n) T | O(n) S | CiFFiRO | 0 | 165 | construct binary tree from preorder and postorder traversal | 889 | 0.708 | Medium | 14,411 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/500786/Python-O(-nk-)-sol.-by-pattern-matching.-80%2B-With-explanation | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def helper( s ):
# dictionary
# key : character
# value : serial number in string type
char_index_dict = dict()
# given each unique character a serial number
for character in s:
if character not in char_index_dict:
char_index_dict[character] = str( len(char_index_dict) )
# gererate corresponding pattern string
return ''.join( map(char_index_dict.get, s) )
#--------------------------------------------------------
pattern_string = helper(pattern)
return [ word for word in words if helper(word) == pattern_string ] | find-and-replace-pattern | Python O( nk ) sol. by pattern matching. 80%+ [ With explanation ] | brianchiang_tw | 9 | 835 | find and replace pattern | 890 | 0.779 | Medium | 14,412 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2348887/Easy-Solution-using-Dictionary-in-Python | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
result = []
for word in words:
if len(set(pattern)) == len(set(word)):
tempDict = {}
Flag = False
for i in range(len(pattern)):
if pattern[i] not in tempDict:
Flag= True
tempDict[pattern[i]] = word[i]
elif pattern[i] in tempDict and tempDict[pattern[i]] != word[i]:
Flag = False
break
if Flag== True:
result.append(word)
return result | find-and-replace-pattern | Easy Solution using Dictionary in Python | AY_ | 5 | 366 | find and replace pattern | 890 | 0.779 | Medium | 14,413 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/1222425/Python-Convert-word-to-number-easy-solution | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
pattern = self.word2Num(pattern)
return [word for word in words if self.word2Num(word) == pattern]
def word2Num(self, word):
ch2Digit = {}
digits = []
for ch in word:
if ch not in ch2Digit: ch2Digit[ch] = len(ch2Digit)
digits.append(ch2Digit[ch])
return digits | find-and-replace-pattern | [Python] Convert word to number easy solution | trungnguyen276 | 3 | 333 | find and replace pattern | 890 | 0.779 | Medium | 14,414 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/1221216/PythonPython3-solution-with-exlanation-easy-understanding | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
patternIndex = "" #To store the index of the pattern
for i in pattern: #Traverse the pattern string and add the index.
patternIndex += str(pattern.index(i))
#print(patternIndex)
wordLisIndex = [] #To store the index of the pattern of each word in the list
for i in words: #Traverse the words list
patIndex = "" #To store the index of the i
for j in i: #Traverse the i string and add the index.
patIndex += str(i.index(j))
wordLisIndex.append(patIndex)#Append the pat
#print(wordLisIndex)
patternMatch = [] #To store the matched pattern
for pat in range(len(wordLisIndex)): #Traverse the wordLisIndex
if patternIndex == wordLisIndex[pat]:#If their is a match append in patternMatch
patternMatch.append(words[pat])
return patternMatch | find-and-replace-pattern | Python/Python3 solution with exlanation easy understanding | prasanthksp1009 | 3 | 146 | find and replace pattern | 890 | 0.779 | Medium | 14,415 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/1100914/PythonPython3-Find-and-Replace-Pattern | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
return (word for word in words if (len(set(zip(word, pattern))) == len(set(pattern)) == len(set(word)))) | find-and-replace-pattern | [Python/Python3] Find and Replace Pattern | newborncoder | 3 | 303 | find and replace pattern | 890 | 0.779 | Medium | 14,416 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/898044/index-solution-beat-97.74-and-100-python3 | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
ans = []
for i in range(len(words)):
if self.check(words[i], pattern):
ans.append(words[i])
return ans
def check(self, word, pattern):
if len(word) != len(pattern):
return False
for i in range(len(word)):
if word.find(word[i]) != pattern.find(pattern[i]):
return False
return True | find-and-replace-pattern | index solution beat 97.74% and 100% python3 | dqdwsdlws | 3 | 105 | find and replace pattern | 890 | 0.779 | Medium | 14,417 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2349880/Python3-or-Easy-Solution-or-Using-defaultdict | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
pat = defaultdict(list)
res = []
for i, v in enumerate(pattern):
pat[v].append(i)
for word in words:
word_pat = defaultdict(list)
for i, v in enumerate(word):
word_pat[v].append(i)
if list(word_pat.values()) == list(pat.values()):
res.append(word)
return res | find-and-replace-pattern | Python3 | Easy Solution | Using defaultdict | Petticoat | 1 | 28 | find and replace pattern | 890 | 0.779 | Medium | 14,418 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/1221053/Python-Solution | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
n = len(pattern)
ans = []
for word in words:
bij = {}
good = True
for i in range(n):
if word[i] in bij:
if bij[word[i]] != pattern[i]:
good = False
break
else:
if pattern[i] in bij.values():
good = False
break
bij[word[i]] = pattern[i]
if good:
ans.append(word)
return ans | find-and-replace-pattern | Python Solution | mariandanaila01 | 1 | 119 | find and replace pattern | 890 | 0.779 | Medium | 14,419 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/1061671/Easy-to-understand-less-memory | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def mapping(s):
map = {}
res = ''
i = 0
for ch in s:
if ch not in map:
map[ch]=i
i+=1
map[ch]=map[ch]
res += str(map[ch])
return res
output = []
p = mapping(pattern)
for s in words:
mapp = mapping(s)
if mapp==p:
output.append(s)
return output | find-and-replace-pattern | Easy to understand, less memory | PandaGullu | 1 | 103 | find and replace pattern | 890 | 0.779 | Medium | 14,420 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/946880/Python3-3-approaches | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def fn(word):
"""Return True if word matches pattern."""
mpw, mpp = {}, {}
for i, (w, p) in enumerate(zip(word, pattern)):
if mpw.get(w) != mpp.get(p): return False
mpw[w] = mpp[p] = i
return True
return [word for word in words if fn(word)] | find-and-replace-pattern | [Python3] 3 approaches | ye15 | 1 | 132 | find and replace pattern | 890 | 0.779 | Medium | 14,421 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/946880/Python3-3-approaches | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
return [word for word in words if len(set(zip(word, pattern))) == len(set(word)) == len(set(pattern))] | find-and-replace-pattern | [Python3] 3 approaches | ye15 | 1 | 132 | find and replace pattern | 890 | 0.779 | Medium | 14,422 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/946880/Python3-3-approaches | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
fn = lambda x: tuple(map({}.setdefault, x, range(len(x))))
pattern = fn(pattern)
return [word for word in words if fn(word) == pattern] | find-and-replace-pattern | [Python3] 3 approaches | ye15 | 1 | 132 | find and replace pattern | 890 | 0.779 | Medium | 14,423 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/298309/Python-faster-than-97-16-ms | class Solution(object):
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
a = []
for word in words:
d = dict()
used = set()
new_word = ''
for i in range(len(word)):
if word[i] in d:
new_word += d[word[i]]
else:
if pattern[i] in used:
break
else:
d[word[i]] = pattern[i]
used.add(pattern[i])
new_word += pattern[i]
if new_word==pattern:
a.append(word)
return a | find-and-replace-pattern | Python - faster than 97%, 16 ms | il_buono | 1 | 269 | find and replace pattern | 890 | 0.779 | Medium | 14,424 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/291875/Python3-Beats-99.65-submissions-16-Line-code | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def createFreq(s):
dic = {}
for i,char in enumerate(s):
if char in dic:
dic[char][0] += 1
else:
dic[char] = [1,i]
r = []
for char in s:
r.append(dic[char])
return r
filteredWords = list(filter(lambda x: len(x) == len(pattern), words))
freqP = createFreq(pattern)
return list(filter(lambda x: createFreq(x) == freqP, filteredWords)) | find-and-replace-pattern | Python3 Beats 99.65% submissions 16 Line code | taneja | 1 | 180 | find and replace pattern | 890 | 0.779 | Medium | 14,425 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2795860/Python-or-Easy-to-understand-functional-solution | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def is_valid_pattern(word):
hash = {}
values = set()
for k, v in zip(word, pattern):
if (k not in hash and v in values) or (k in hash and hash[k] != v):
return False
else:
hash[k] = v
values.add(v)
return True
return [x for x in words if is_valid_pattern(x)] | find-and-replace-pattern | Python | Easy to understand functional solution | xyp7x | 0 | 5 | find and replace pattern | 890 | 0.779 | Medium | 14,426 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2768411/Simple-Approach | class Solution:
def findAndReplacePattern(self, W: List[str], P: str) -> List[str]:
ans = []
dp = defaultdict(list)
for i, c in enumerate(P):
dp[c].append(i)
dp = list(dp.values())
for w in W:
dw = defaultdict(list)
for i, c in enumerate(w):
dw[c].append(i)
if dp == list(dw.values()):
ans.append(w)
return ans | find-and-replace-pattern | Simple Approach | Mencibi | 0 | 2 | find and replace pattern | 890 | 0.779 | Medium | 14,427 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2515197/Python-or-2-versions-Conversion-to-integers | class Solution:
def convert(self, word: str) -> str:
num_iter = iter(range(len(word)))
for char in dict.fromkeys(word).keys():
word = word.replace(char, str(next(num_iter)))
return word
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
pattern = self.convert(pattern)
return [w for w in words if self.convert(w) == pattern] | find-and-replace-pattern | Python | 2 versions - Conversion to integers | Wartem | 0 | 19 | find and replace pattern | 890 | 0.779 | Medium | 14,428 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2515197/Python-or-2-versions-Conversion-to-integers | class Solution:
def convert(self, word: str) -> str:
num_iter = iter(range(len(word)))
translate = {}
for char in dict.fromkeys(word).keys():
translate.update({char: str(next(num_iter))})
return [translate[char] for char in word]
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
pattern = self.convert(pattern)
return [w for w in words if self.convert(w) == pattern] | find-and-replace-pattern | Python | 2 versions - Conversion to integers | Wartem | 0 | 19 | find and replace pattern | 890 | 0.779 | Medium | 14,429 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2473468/Easy-Python-Solution-Using-Only-Built-in-Methods | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def mapping(word):
d = dict(zip(word, range(len(word))))
return [str(d[i]) for i in word]
return [w for w in words if mapping(w) == mapping(pattern)] | find-and-replace-pattern | Easy Python Solution Using Only Built-in Methods | yhc22593 | 0 | 10 | find and replace pattern | 890 | 0.779 | Medium | 14,430 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2457833/Python-simple-and-faster-that-93 | class Solution:
def pattern(self,w):
dic = {}
a = []
count = 0
for i in w:
if i not in dic:
dic[i] = count
count += 1
a.append(dic[i])
return a
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
p = self.pattern(pattern)
return [word for word in words if self.pattern(word) == p] | find-and-replace-pattern | Python simple and faster that 93% | aruj900 | 0 | 35 | find and replace pattern | 890 | 0.779 | Medium | 14,431 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2357525/WEEB-DOES-PYTHONC%2B%2B | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
hashmap = {}
ans = ""
result = []
for i in range(len(pattern)):
if pattern[i] in hashmap: ans += hashmap[pattern[i]]
else:
ans += str(i)
hashmap[pattern[i]] = str(i)
result = []
for word in words:
temp = ""
hashmap.clear()
for i in range(len(word)):
if word[i] in hashmap: temp += hashmap[word[i]]
else:
temp += str(i)
hashmap[word[i]] = str(i)
if temp == ans: result.append(word)
return result | find-and-replace-pattern | WEEB DOES PYTHON/C++ | Skywalker5423 | 0 | 17 | find and replace pattern | 890 | 0.779 | Medium | 14,432 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2352300/Find-and-Replace-Pattern-Python-or-Easy-Understandable-or-JulyDay-29Daily-Challenge | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def makePattern(word):
dictionary,list_of_patterns,count = {},[],0
for character in word: # for each char in word
if character not in dictionary: #if char not in the dictionary
dictionary[character] = count #take the character and give it a value of the count
count += 1 # increment count for the next character
list_of_patterns.append(dictionary[character])
return list_of_patterns
pattern_obtained = makePattern(pattern)
return [word for word in words if makePattern(word) == pattern_obtained] | find-and-replace-pattern | Find and Replace Pattern - Python | Easy Understandable | July,Day 29,Daily Challenge | phanee16 | 0 | 5 | find and replace pattern | 890 | 0.779 | Medium | 14,433 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2351787/Python-Simple-2-Liner-Top-100-With-Explanation | class Solution:
# Turn letters into numbers
def serialize(self,word):
# Maintain hashmap and count letters
c = count()
# Hashmap
d = defaultdict(int)
# Serialized word
new_word = ""
# Iterate over letters
for letter in word:
# Check if we've seen the letter before
if letter in d:
# Add number to new string
new_word += d[letter]
else:
# Set new letter to next number in map then add it
d[letter] = str(next(c))
new_word += d[letter]
return new_word
def findAndReplacePattern(self, words: List[satr], pattern: str) -> List[str]:
# Serialize pattern
s_pattern = self.serialize(pattern)
# Serialize words and check for matches with list comprehension
return([word for word in words if self.serialize(word) == s_pattern]) | find-and-replace-pattern | Python Simple 2-Liner Top 100% With Explanation | drblessing | 0 | 20 | find and replace pattern | 890 | 0.779 | Medium | 14,434 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2351751/Python3-Runtime%3A-30-ms-faster-than-97.40 | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
li={}
lk = []
for i in range(len(pattern)):
if pattern[i] in li:
li[pattern[i]].append(i)
else:
li[pattern[i]] = [i]
for word in words:
xxx = True
tested = []
for key, value in li.items():
if word[value[0]] not in tested:
tested.append(word[value[0]])
for j in value:
if word[j] != word[value[0]]:
xxx = False
break
if xxx == False:
break
else:
xxx = False
if xxx:
lk.append(word)
return lk | find-and-replace-pattern | Python3 Runtime: 30 ms, faster than 97.40% | codewithsonukumar | 0 | 11 | find and replace pattern | 890 | 0.779 | Medium | 14,435 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2351496/My-idiotic-simple-approach-or-Python | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
r = []
for word in words:
d = {}
is_valid = True
for index, ch in enumerate(word):
if pattern[index] in d:
val = d[pattern[index]]
if val != ch:
is_valid = False
break
else:
if ch in d.values():
is_valid = False
break
d[pattern[index]] = ch
if is_valid:
r.append(word)
return r | find-and-replace-pattern | My idiotic simple approach | Python | prameshbajra | 0 | 16 | find and replace pattern | 890 | 0.779 | Medium | 14,436 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2351073/First-attempt-O(kn)-time-O(k-%2B-n)-space-complexity | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
# define empty list of words to return
result = []
# define a permutation helper function that maps the pattern to a list of integers
# first letter seen is always 0, second unique letter is 1, third is 2, etc.
# Examples:
# aab => [0, 0, 1]
# abc => [0, 1, 2]
# aba => [0, 1, 0]
def getPermutation(word: str):
perm = []
index = 0
charIndexMap = dict()
for char in word:
if char not in charIndexMap.keys():
charIndexMap[char] = index
index +=1
perm.append(charIndexMap[char])
return perm
# map pattern to list of integers
patternPerm = getPermutation(pattern)
# loop through words
for word in words:
# if word permuation matches pattern permutation
if getPermutation(word) == patternPerm:
# append word to result list
result.append(word)
# return list of matched words
return result | find-and-replace-pattern | First attempt O(kn) time, O(k + n) space complexity | preformIO | 0 | 7 | find and replace pattern | 890 | 0.779 | Medium | 14,437 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2349777/Python-Solution-using-2-hashmap-88-faster | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
res = []
def is_pattern_matching(word):
w_to_p, p_to_w = {}, {}
for w, p in zip(word, pattern):
if w not in w_to_p:
w_to_p[w] = p
if p not in p_to_w:
p_to_w[p] = w
if p_to_w[p]!=w or w_to_p[w]!=p:
return False
return True
for word in words:
if is_pattern_matching(word):
res.append(word)
return res | find-and-replace-pattern | Python Solution using 2 hashmap, 88% faster | pradeep288 | 0 | 13 | find and replace pattern | 890 | 0.779 | Medium | 14,438 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2349762/Python-Simple-Faster-Solution-2-Hash-Maps-oror-Documented | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
dict = {}; dict2 = {}; result = []
for w in words:
success = True
# start mapping: pattern -> word and word -> pattern
for i, pc in enumerate(pattern):
dict[pc] = w[i] # pattern -> word
# if character is already mapped with other, break the loop
if w[i] in dict2 and dict2[w[i]] != pc:
success = False
break
dict2[w[i]] = pc # word -> pattern
# if character mapping is overwritten, break the loop
if len(dict) != len(dict2):
success = False
break
# if mapping is done successfully, add the word to result
if success:
result.append(w)
# prepare for next word
dict.clear(); dict2.clear()
return result | find-and-replace-pattern | [Python] Simple Faster Solution - 2 Hash Maps || Documented | Buntynara | 0 | 6 | find and replace pattern | 890 | 0.779 | Medium | 14,439 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2349649/Python-Solution-oror-Dictionaries-oror | class Solution:
def findAndReplacePattern(self, words, pattern):
def patternList(word):
d = {}
wordpattern = []
c = 0
for i in word:
if i not in d:
c += 1
d[i] = c
wordpattern.append(d[i])
else:
wordpattern.append(d[i])
return wordpattern
result = []
source = patternList(pattern)
for word in words:
wordpattern = patternList(word)
if wordpattern == source:
result.append(word)
return result | find-and-replace-pattern | Python Solution || Dictionaries || | LOKESH_SAANA | 0 | 9 | find and replace pattern | 890 | 0.779 | Medium | 14,440 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2349454/python-O(n)-solution-beats-97 | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
result=[]
for i in words:
if len(i)!=len(pattern):
continue
d={}
values=set()
b=True
for j in range(len(i)):
if pattern[j] in d:
if i[j]==d[pattern[j]]:
values.add(i[j])
else:
b=False
break
else:
if i[j] in values:
b=False
break
d[pattern[j]]=i[j]
values.add(i[j])
if b:
result.append(i)
return result | find-and-replace-pattern | python O(n) solution beats 97% | benon | 0 | 20 | find and replace pattern | 890 | 0.779 | Medium | 14,441 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2349308/GolangPython-O(N)-time-or-O(N)-space | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
output = []
for word in words:
word_dict = {}
pattern_dict = {}
for p,w in zip(pattern,word):
if w not in word_dict:
word_dict[w] = p
if p not in pattern_dict:
pattern_dict[p] = w
if pattern_dict[p] != w or word_dict[w] != p:
break
else:
output.append(word)
return output | find-and-replace-pattern | Golang/Python O(N) time | O(N) space | vtalantsev | 0 | 16 | find and replace pattern | 890 | 0.779 | Medium | 14,442 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2349208/Python-Easy-to-Understand-O(n*m)-solution-Fast-than-73-with-explanation | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
res = []
for word in words:
# map from pattern[i] to word[i]
mapping = {}
# record if we already visited word[i]
visited = set()
for i in range(len(word)):
if not pattern[i] in mapping:
# if word is ccc and pattern is abb
# we should break the loop while occur the second b
# because c in word is already mapping from a in pattern
if word[i] in visited:
break
mapping[pattern[i]] = word[i]
visited.add(word[i])
else:
if mapping[pattern[i]] != word[i]:
break
# if we campare till the last char without break out the loop.
# append to ans
if i == len(word)-1:
res.append(word)
return res | find-and-replace-pattern | Python Easy to Understand O(n*m) solution Fast than 73% with explanation | EnergyBoy | 0 | 10 | find and replace pattern | 890 | 0.779 | Medium | 14,443 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2349125/python3-or-easy-to-understand-or-dict | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
ans = []
for i in words:
p = 0
dic = {}
flag = 1
for j in pattern:
if j not in dic:
if i[p] not in dic.values():
dic[j] = i[p]
p += 1
else:
flag = 0
break
elif dic[j] == i[p]:
p += 1
continue
else:
flag = 0
break
if flag == 1:
ans.append(i)
return ans | find-and-replace-pattern | python3 | easy to understand | dict | jayeshmaheshwari555 | 0 | 2 | find and replace pattern | 890 | 0.779 | Medium | 14,444 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2349051/Easy-Python-oror-Hashing | class Solution(object):
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
res = []
for i in words:
if(self.isPattern(pattern,i)):
res.append(i)
return res
def isPattern(self,w1,w2):
dict1 = {}
for i in range(len(w1)):
if(w1[i] not in dict1):
if(w2[i] in dict1.values()):
return 0
dict1[w1[i]] = w2[i]
else:
if(w2[i] != dict1[w1[i]]):
return 0
# print(dict1)
return 1 | find-and-replace-pattern | Easy Python || Hashing | mridulbhas | 0 | 16 | find and replace pattern | 890 | 0.779 | Medium | 14,445 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2348779/40ms-Python3-one-liner | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
return [word for word in words
for slots in [[pattern.index(c) for c in pattern]]
if [word.index(c) for c in word] == slots] | find-and-replace-pattern | 40ms Python3 one-liner | leetavenger | 0 | 7 | find and replace pattern | 890 | 0.779 | Medium | 14,446 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2348689/Rabin-Kerp-alg-concept-application(96-time-76-memory) | class Solution:
def findAndReplacePattern(self, words, pattern: str):
def replace_word(string):
rp, dic, count = 0, {}, 1
for j in string:
if j not in dic:
dic[j] = count
count += 1
rp = rp*29 + dic[j]
return rp
res = []
for i in range(len(words)):
res.append(replace_word(words[i]))
pattern = replace_word(pattern)
reply = []
for i in range(len(res)):
if pattern == res[i]:
reply.append(words[i])
return reply | find-and-replace-pattern | Rabin-Kerp alg concept application(96% time, 76% memory) | TUL | 0 | 12 | find and replace pattern | 890 | 0.779 | Medium | 14,447 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2348584/Python3-or-Map | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def findPattern(word): # remap: for example 'cdd' --> 'abb'
d = {} # hashmap
count = 0
p = ''
for char in word:
if char not in d:
d[char] = chr(count + 97) # will map first unique letter to 'a' , then map second to 'b', and so on...
count += 1
p += d[char]
return p
res = []
targetPattern = findPattern(pattern)
for word in words:
if findPattern(word) == targetPattern:
res.append(word)
return res | find-and-replace-pattern | ✅Python3 | Map | Hanying2022 | 0 | 4 | find and replace pattern | 890 | 0.779 | Medium | 14,448 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2348564/python-solution-oror-98-faster-oror-easy-understanding | class Solution(object):
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
res = []
val = self.patternFormer(pattern)
for w in words:
if val == self.patternFormer(w):
res.append(w)
return res
def patternFormer(self , word):
res = ""
val = 65
hashmap = {}
for i in word:
if i not in hashmap:
hashmap[i] = chr(val)
val = val + 1
res = res + hashmap[i]
return res | find-and-replace-pattern | python solution || 98% faster || easy understanding | jhaprashant1108 | 0 | 40 | find and replace pattern | 890 | 0.779 | Medium | 14,449 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2348491/Python3-naive-solution-using-maps | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
result = []
for i in words:
if len(i)==len(pattern):
seen = {}
seen1 = {}
flag= 1
for j in range(len(pattern)):
x = seen.get(pattern[j])
y = seen1.get(i[j])
if x==None and y==None:
seen[pattern[j]] = i[j]
seen1[i[j]] = pattern[j]
elif y==None or x==None:
flag=0
break
else:
if seen[y]!=x and seen1[x]!=y:
flag=0
break
if flag:
result.append(i)
return result | find-and-replace-pattern | 📌 Python3 naive solution using maps | Dark_wolf_jss | 0 | 8 | find and replace pattern | 890 | 0.779 | Medium | 14,450 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2348429/Python-Simple-Python-Solution-Using-Dictionary-oror-HashMap | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
result = []
for word in words:
frequency = {}
total_char = 0
for index in range(len(word)):
if pattern[index] not in frequency:
if word[index] not in frequency.values():
frequency[pattern[index]] = word[index]
total_char = total_char + 1
else:
break
else:
if frequency[pattern[index]] == word[index]:
total_char = total_char + 1
if total_char == len(pattern):
result.append(word)
return result | find-and-replace-pattern | [ Python ] ✅✅ Simple Python Solution Using Dictionary || HashMap 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 30 | find and replace pattern | 890 | 0.779 | Medium | 14,451 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2348213/Python3-or-Easy-to-Understand-or-Efficient-or-For-beginners | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
result = []
for word in words:
wordToPat = self.healthy(word, pattern)
patToWord = self.healthy(pattern, word)
if wordToPat and patToWord:
result.append(word)
return result
def healthy(self, w1: str, w2: str) -> bool:
w1Len = len(w1)
w2Len = len(w2)
# length mismatch
if w1Len != w2Len:
return False
mapping = {}
for i in range(w1Len):
if w1[i] not in mapping:
mapping[w1[i]] = w2[i]
else:
# different value for same key
if mapping[w1[i]] != w2[i]:
return False
return True | find-and-replace-pattern | ✅Python3 | Easy to Understand | Efficient | For beginners | thesauravs | 0 | 16 | find and replace pattern | 890 | 0.779 | Medium | 14,452 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2348020/Python-mapping-to-the-first-occurrence | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def getPattern(s):
chars = [0] * 26
cnt = 1
p = [0] * len(s)
for i, c in enumerate(s):
idx = ord(c) - ord('a')
if chars[idx] == 0:
chars[idx] = cnt
cnt += 1
p[i] = chars[idx]
return p
result = []
p = getPattern(pattern)
for w in words:
if getPattern(w) == p:
result.append(w)
return result | find-and-replace-pattern | Python, mapping to the first occurrence | blue_sky5 | 0 | 16 | find and replace pattern | 890 | 0.779 | Medium | 14,453 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/2272984/easy-python-solution | class Solution:
def encode_string(self, word) :
counter, unique_char_mapping = 0, {}
ans = ''
for i in range(len(word)) :
if word[i] not in unique_char_mapping.keys() :
unique_char_mapping[word[i]] = counter
ans += str(counter)
counter += 1
else :
ans += str(unique_char_mapping[word[i]])
return ans
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
encoded_pattern = self.encode_string(pattern)
ans = []
for word in words :
if self.encode_string(word) == encoded_pattern :
ans.append(word)
return ans | find-and-replace-pattern | easy python solution | sghorai | 0 | 49 | find and replace pattern | 890 | 0.779 | Medium | 14,454 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/1619598/python-sol-faster-than-98.5-with-one-dic | class Solution:
def findAndReplacePattern(self, words: List[str], p: str) -> List[str]:
res = []
ln = len(p)
for word in words:
if len(word) != ln:
continue
cnt1 = ''
dic = {}
dic[p[0]] = word[0]
for i in range(ln):
if p[i] in dic:
cnt1 += dic[p[i]]
else:
if word[i] in dic.values():
break
dic[p[i]] = word[i]
cnt1 += dic[p[i]]
if cnt1 == word:
res.append(word)
return res | find-and-replace-pattern | python sol faster than 98.5% with one dic | elayan | 0 | 102 | find and replace pattern | 890 | 0.779 | Medium | 14,455 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/1599118/Convert-String-to-array-and-also-match-the-count | class Solution:
def findAndReplacePattern(self, w: List[str], p: str) -> List[str]:
lp=len(p)
ans,l=[],[]
d={}
for i in p:
if i in d:
d[i]+=1
else:
d[i]=1
l.append(d[i])
for i in w:
f,k={},[]
for j in i:
if j in f:
f[j]+=1
else:
f[j]=1
k.append(f[j])
if l==k:
flag=True
for j in range(lp):
if d[p[j]]!=f[i[j]]:
flag=False
break
if flag:
ans.append(i)
return ans | find-and-replace-pattern | Convert String to array and also match the count | gamitejpratapsingh998 | 0 | 61 | find and replace pattern | 890 | 0.779 | Medium | 14,456 |
https://leetcode.com/problems/find-and-replace-pattern/discuss/1250591/python-or-92.48 | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
ans=[]
for j in words:
if len(j)==len(pattern):
if len(set(j)) == len(set(pattern)):
pe={}
we={}
h=0
for i in range(1,len(pattern)):
if pattern[i]==pattern[i-1]:
if j[i-1]!=j[i]:
h+=1
break
elif pattern[i]!=pattern[i-1]:
if j[i-1]==j[i]:
h+=1
break
if pattern[i] not in pe:
pe[pattern[i]]=1
if j[i] in we:
h+=1
break
else:
we[j[i]]=1
if pattern[i] in pe:
pe[pattern[i]]+=1
if j[i] not in we:
h+=1
break
else:
we[j[i]]+=1
if h==0 and sorted(list(we.values()))==sorted(list(pe.values())):
ans.append(j)
return ans | find-and-replace-pattern | python | 92.48% | chikushen99 | 0 | 112 | find and replace pattern | 890 | 0.779 | Medium | 14,457 |
https://leetcode.com/problems/sum-of-subsequence-widths/discuss/2839381/MATH-%2B-DP | class Solution:
def sumSubseqWidths(self, nums: List[int]) -> int:
MOD = 10**9 + 7
n = len(nums)
nums.sort()
dp = [0] * n
p = 2
temp = nums[0]
for i in range(1, n):
dp[i] = ((dp[i-1] + ((p-1)*nums[i])%MOD)%MOD - temp)%MOD
p = (2*p)%MOD
temp = ((2*temp)%MOD + nums[i])%MOD
return dp[n-1] | sum-of-subsequence-widths | MATH + DP | roboto7o32oo3 | 0 | 2 | sum of subsequence widths | 891 | 0.365 | Hard | 14,458 |
https://leetcode.com/problems/sum-of-subsequence-widths/discuss/1881830/Python-easy-to-read-and-understand-or-sorting | class Solution:
def sumSubseqWidths(self, nums: List[int]) -> int:
nums.sort()
ans = 0
n = len(nums)
for i in range(n):
mx = (2**i)*nums[i]
mn = (2**(n-1-i))*nums[i]
ans += (mx-mn)
return ans%(10**9+7) | sum-of-subsequence-widths | Python easy to read and understand | sorting | sanial2001 | 0 | 71 | sum of subsequence widths | 891 | 0.365 | Hard | 14,459 |
https://leetcode.com/problems/sum-of-subsequence-widths/discuss/1545974/Python3-greedy | class Solution:
def sumSubseqWidths(self, nums: List[int]) -> int:
MOD = 1_000_000_007
nums.sort()
ans = val = 0
p = 1
for i in range(1, len(nums)):
p = p * 2 % MOD
val = (2*val + (nums[i]-nums[i-1])*(p-1)) % MOD
ans = (ans + val) % MOD
return ans | sum-of-subsequence-widths | [Python3] greedy | ye15 | 0 | 103 | sum of subsequence widths | 891 | 0.365 | Hard | 14,460 |
https://leetcode.com/problems/sum-of-subsequence-widths/discuss/1545974/Python3-greedy | class Solution:
def sumSubseqWidths(self, nums: List[int]) -> int:
MOD = 1_000_000_007
ans = 0
for i, x in enumerate(sorted(nums)):
ans += x * (pow(2, i, MOD) - pow(2, len(nums)-i-1, MOD))
return ans % MOD | sum-of-subsequence-widths | [Python3] greedy | ye15 | 0 | 103 | sum of subsequence widths | 891 | 0.365 | Hard | 14,461 |
https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/2329304/Simple-Python-explained | class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
l = len(grid)
area=0
for row in range(l):
for col in range(l):
if grid[row][col]:
area += (grid[row][col]*4) +2 #surface area of each block if blocks werent connected
if row: #row>0
area -= min(grid[row][col],grid[row-1][col])*2 #subtracting as area is common among two blocks
if col: #col>0
area -= min(grid[row][col],grid[row][col-1])*2 #subtracting as area is common among two blocks
return area | surface-area-of-3d-shapes | Simple Python explained | sunakshi132 | 3 | 153 | surface area of 3d shapes | 892 | 0.633 | Easy | 14,462 |
https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/1967396/python-3-oror-clean-and-concise-code-oror-O(n)O(1) | class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
n = len(grid)
def area(i, j):
v = grid[i][j]
if v == 0:
return 0
up = min(v, grid[i - 1][j]) if i else 0
right = min(v, grid[i][j + 1]) if j < n - 1 else 0
down = min(v, grid[i + 1][j]) if i < n - 1 else 0
left = min(v, grid[i][j - 1]) if j else 0
return 2 + 4*v - up - right - down - left
return sum(area(i, j) for i in range(n) for j in range(n)) | surface-area-of-3d-shapes | python 3 || clean and concise code || O(n)/O(1) | dereky4 | 1 | 139 | surface area of 3d shapes | 892 | 0.633 | Easy | 14,463 |
https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/2153680/Python3-simple-solution | class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
n = len(grid)
if n == 1:
return 0 if grid[0][0] == 0 else 2 * (2 * grid[0][0] + 1)
count = 0
for i in range(n):
for j in range(n):
if grid[i][j] != 0:
count += 2 * (2 * grid[i][j] + 1)
for i in range(n):
for j in range(n):
x = 0
if i == 0:
if grid[i+1][j] != 0:
x += min(grid[i+1][j], grid[i][j])
if j == 0:
if grid[i][j+1] != 0:
x += min(grid[i][j], grid[i][j+1])
elif j == n-1:
if grid[i][j-1] != 0:
x += min(grid[i][j], grid[i][j-1])
else:
if grid[i][j+1] != 0:
x += min(grid[i][j], grid[i][j+1])
if grid[i][j-1] != 0:
x += min(grid[i][j], grid[i][j-1])
elif i == n-1:
if grid[i-1][j] != 0:
x += min(grid[i-1][j], grid[i][j])
if j == 0:
if grid[i][j+1] != 0:
x += min(grid[i][j], grid[i][j+1])
elif j == n-1:
if grid[i][j-1] != 0:
x += min(grid[i][j], grid[i][j-1])
else:
if grid[i][j+1] != 0:
x += min(grid[i][j], grid[i][j+1])
if grid[i][j-1] != 0:
x += min(grid[i][j], grid[i][j-1])
else:
if grid[i-1][j] != 0:
x += min(grid[i-1][j], grid[i][j])
if grid[i+1][j] != 0:
x += min(grid[i+1][j], grid[i][j])
if j == 0:
if grid[i][j+1] != 0:
x += min(grid[i][j], grid[i][j+1])
elif j == n-1:
if grid[i][j-1] != 0:
x += min(grid[i][j], grid[i][j-1])
else:
if grid[i][j+1] != 0:
x += min(grid[i][j], grid[i][j+1])
if grid[i][j-1] != 0:
x += min(grid[i][j], grid[i][j-1])
count -= x
return count | surface-area-of-3d-shapes | Python3 simple solution | EklavyaJoshi | 0 | 58 | surface area of 3d shapes | 892 | 0.633 | Easy | 14,464 |
https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/1440421/One-pass-over-cells-96-speed | class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
area = 0
rows1, cols1 = len(grid) - 1, len(grid[0]) - 1
for r, row in enumerate(grid):
for c, height in enumerate(row):
area += 2 * (height > 0)
if r == 0 and c == 0:
area += 2 * height
elif r == 0 and c > 0:
area += height + abs(height - grid[0][c - 1])
elif c == 0 and r > 0:
area += height + abs(height - grid[r - 1][0])
else:
area += (abs(height - grid[r][c - 1]) +
abs(height - grid[r - 1][c]))
if r == rows1 and c == cols1:
area += 2 * height
elif r == rows1 or c == cols1:
area += height
return area | surface-area-of-3d-shapes | One pass over cells, 96% speed | EvgenySH | 0 | 128 | surface area of 3d shapes | 892 | 0.633 | Easy | 14,465 |
https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/1368054/Python3-dollarolution | class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
x, y, s = len(grid), len(grid[0]), 0
for i in range(x):
for j in range(y):
if grid[i][j] != 0:
s += 4 * grid[i][j] + 2
if j < y - 1:
s -= 2 * min(grid[i][j], grid[i][j+1])
if i < x - 1:
s -= 2 * min(grid[i][j], grid[i + 1][j])
return s | surface-area-of-3d-shapes | Python3 $olution | AakRay | 0 | 97 | surface area of 3d shapes | 892 | 0.633 | Easy | 14,466 |
https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/612107/Intuitive-approach-by-calculating-topdown-vertical-and-horizontal-area-separately | class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
R = len(grid)
C = len(grid[0])
area_of_td = 0
''' area of top/down surface'''
area_of_hr = 0
''' area of horizontal surface (row direction)'''
area_of_vc = 0
''' area of vertical surface (column direction)'''
def ga(pv, cv):
return cv * 2 - min(pv, cv) * 2
# Calculate area_of_hr & area_of_td
for ri in range(R):
pv = 0
for ci in range(C):
v = grid[ri][ci]
if v > 0:
area_of_td += 2
area_of_hr += ga(pv, v)
pv = v
# Calculate area_of_vc
for ct in zip(*grid):
pv = 0
for ri in range(R):
v = ct[ri]
if v > 0:
area_of_vc += ga(pv, v)
pv = v
return area_of_td + area_of_hr + area_of_vc | surface-area-of-3d-shapes | Intuitive approach by calculating top/down, vertical and horizontal area separately | puremonkey2001 | 0 | 77 | surface area of 3d shapes | 892 | 0.633 | Easy | 14,467 |
https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/477296/Python3-86.89-(84-ms)100.00-(12.8-MB)-O(n)-timeO(1)-space | class Solution:
def surfaceArea(self, A: List[List[int]]) -> int:
N = len(A)
row_last = column_last = N - 1
area = 0
for row in range(N):
for column in range(N):
if (A[row][column]):
area += 2
if (row == 0):
area += A[row][column]
elif (A[row][column] > A[row - 1][column]):
area += A[row][column] - A[row - 1][column]
else:
pass
if (row == row_last):
area += A[row][column]
elif (A[row][column] > A[row + 1][column]):
area += A[row][column] - A[row + 1][column]
else:
pass
if (column == 0):
area += A[row][column]
elif (A[row][column] > A[row][column - 1]):
area += A[row][column] - A[row][column - 1]
else:
pass
if (column == column_last):
area += A[row][column]
elif (A[row][column] > A[row][column + 1]):
area += A[row][column] - A[row][column + 1]
else:
pass
return area | surface-area-of-3d-shapes | Python3 86.89% (84 ms)/100.00% (12.8 MB) -- O(n) time/O(1) space | numiek_p | 0 | 80 | surface area of 3d shapes | 892 | 0.633 | Easy | 14,468 |
https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/437068/Python-3-(four-lines)-(-O(n)-) | class Solution:
def surfaceArea(self, G: List[List[int]]) -> int:
N, C = len(G), [(1,0),(0,-1),(-1,0),(0,1)]
G, S = [[0]*(N+2)] + [[0]+g+[0] for g in G] + [[0]*(N+2)], 2*N**2 - 2*sum(G,[]).count(0)
for i,j in itertools.product(range(1,N+1),range(1,N+1)): S += sum(max(0,G[i][j]-G[i+x][j+y]) for x,y in C)
return S
- Junaid Mansuri | surface-area-of-3d-shapes | Python 3 (four lines) ( O(n²) ) | junaidmansuri | -1 | 163 | surface area of 3d shapes | 892 | 0.633 | Easy | 14,469 |
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/536199/Python-O(n-*-k-lg-k)-sol.-by-signature.-90%2B-w-Hint | class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
signature = set()
# Use pair of sorted even substring and odd substring as unique key
for idx, s in enumerate(A):
signature.add( ''.join( sorted( s[::2] ) ) + ''.join( sorted( s[1::2] ) ) )
return len( signature ) | groups-of-special-equivalent-strings | Python O(n * k lg k) sol. by signature. 90%+ [w/ Hint] | brianchiang_tw | 8 | 512 | groups of special equivalent strings | 893 | 0.709 | Medium | 14,470 |
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/1069262/Python3-one-liner-solution-faster-than-69 | class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
return len({''.join(sorted(a[::2]) + sorted(a[1::2])) for a in A}) | groups-of-special-equivalent-strings | Python3 one liner solution faster than 69% | mhviraf | 2 | 422 | groups of special equivalent strings | 893 | 0.709 | Medium | 14,471 |
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/512298/Python3-Group-strings-by-sorting-characters-at-even-and-odd-indices | class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
fn = lambda s: "".join(sorted(s[::2]) + sorted(s[1::2]))
return len(set(fn(s) for s in A)) | groups-of-special-equivalent-strings | [Python3] Group strings by sorting characters at even & odd indices | ye15 | 2 | 245 | groups of special equivalent strings | 893 | 0.709 | Medium | 14,472 |
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/1387210/Python3-or-Hashset | class Solution:
def numSpecialEquivGroups(self, words: List[str]) -> int:
hset=set()
for i in range(len(words)):
even=[0]*26
odd=[0]*26
for j in range(len(words[i])):
if j%2==0:
even[ord(words[i][j])-ord('a')]+=1
else:
odd[ord(words[i][j])-ord('a')]+=1
hset.add("".join([str(even[i]) for i in range(len(even))])+"".join([str(odd[i]) for i in range(len(odd))]))
return len(hset) | groups-of-special-equivalent-strings | Python3 | Hashset | swapnilsingh421 | 1 | 138 | groups of special equivalent strings | 893 | 0.709 | Medium | 14,473 |
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/2795531/python-solution | class Solution:
def numSpecialEquivGroups(self, words: List[str]) -> int:
for i in range(len(words)):
even = []
odd = []
word = words[i]
for j in range(len(word)):
if j%2 == 0:
even.append(word[j])
else:
odd.append(word[j])
even.sort()
odd.sort()
words[i] = ''.join(even) + ''.join(odd)
return len(set(words)) | groups-of-special-equivalent-strings | python solution | shingnapure_shilpa17 | 0 | 7 | groups of special equivalent strings | 893 | 0.709 | Medium | 14,474 |
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/2656957/Python-using-defaultdict-and-frozenset | class Solution:
def numSpecialEquivGroups(self, words: List[str]) -> int:
def get_group(s):
even, odd = defaultdict(int), defaultdict(int)
for i in range(len(s)):
if i % 2 == 0:
even[s[i]] += 1
else:
odd[s[i]] += 1
return (frozenset(even.items()), frozenset(odd.items()))
groups = set()
for i in words:
groups.add(get_group(i))
return len(groups) | groups-of-special-equivalent-strings | Python - using defaultdict and frozenset | phantran197 | 0 | 1 | groups of special equivalent strings | 893 | 0.709 | Medium | 14,475 |
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/2209011/Python-1-Liner | class Solution:
def numSpecialEquivGroups(self, words) -> int:
return len(set([(''.join(sorted(i[::2])),''.join(sorted(i[1::2]))) for i in words])) | groups-of-special-equivalent-strings | Python 1-Liner | XRFXRF | 0 | 39 | groups of special equivalent strings | 893 | 0.709 | Medium | 14,476 |
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/1187087/Python3-simple-solution-using-dictionary | class Solution:
def numSpecialEquivGroups(self, A):
d = {}
for word in A:
odd = []
even = []
for i,letter in enumerate(word):
if i%2 == 0:
even.append(letter)
else:
odd.append(letter)
odd = tuple(sorted(odd))
even = tuple(sorted(even))
x = tuple([odd,even])
d[x] = d.get(x,0)+1
return len(d) | groups-of-special-equivalent-strings | Python3 simple solution using dictionary | EklavyaJoshi | 0 | 222 | groups of special equivalent strings | 893 | 0.709 | Medium | 14,477 |
https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/752116/Python-One-Liner | class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
return len(set(''.join(sorted(stri[i] for i in range(len(stri)) if i%2==0)) + ''.join(sorted(stri[i] for i in range(len(stri)) if i%2!=0)) for stri in A)) | groups-of-special-equivalent-strings | Python One Liner | frank_paul | -5 | 251 | groups of special equivalent strings | 893 | 0.709 | Medium | 14,478 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/339611/Python-solution-without-recursion-beets-100-speed | class Solution:
def allPossibleFBT(self, N: int) -> List[TreeNode]:
# Any full binary trees should contain odd number of nodes
# therefore, if N is even, return 0
if N % 2 == 0:
return []
# for all odd n that are less than N, store all FBTs
trees_all = collections.defaultdict(list)
#when there is one node, only one tree is available
trees_all[1] = [TreeNode(0)]
for n in range(3, N+1, 2):
for k in range(1, n, 2):
# trees with k nodes on the left
# trees with n - k - 1 nodes on the right
# consider all potential pairs
for tree1, tree2 in itertools.product(trees_all[k],
trees_all[n-k-1]):
tree = TreeNode(0)
tree.left = tree1
tree.right = tree2
trees_all[n].append(tree)
return trees_all[N] | all-possible-full-binary-trees | Python solution without recursion, beets 100% speed | KateMelnykova | 8 | 825 | all possible full binary trees | 894 | 0.8 | Medium | 14,479 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/1944663/Python3-oror-simple-easy-recursive | class Solution:
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
output = []
if not n % 2:
return output
def FBT(m):
if m == 1:
return [TreeNode(0)]
res = []
for i in range(1, m - 1):
for left in FBT(i):
for right in FBT(m - 1 - i):
root = TreeNode(0, left, right)
res.append(root)
return res
return FBT(n) | all-possible-full-binary-trees | Python3 || simple easy recursive | gulugulugulugulu | 3 | 254 | all possible full binary trees | 894 | 0.8 | Medium | 14,480 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/1538450/Python-easy-memoization-solution | class Solution:
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
if n %2 == 0:
return []
@lru_cache
def helper(m): # m = 2k + 1
if m == 1:
return [TreeNode(0)]
elif m >1:
res = []
for i in range(1, m, 2):
candleft = helper(i)
candright = helper(m-1-i)
for l in candleft:
for r in candright:
node = TreeNode(0)
node.left = l
node.right = r
res.append(node)
return res
return helper(n) | all-possible-full-binary-trees | Python easy memoization solution | byuns9334 | 1 | 164 | all possible full binary trees | 894 | 0.8 | Medium | 14,481 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/947011/Python3-memoized-recursion | class Solution:
def allPossibleFBT(self, N: int) -> List[TreeNode]:
@lru_cache(None)
def fn(n):
"""Return all full binary trees of n nodes."""
if n == 1: return [TreeNode()]
ans = []
for nn in range(1, n, 2):
for left in fn(nn):
for right in fn(n-1-nn):
ans.append(TreeNode(left=left, right=right))
return ans
return fn(N) | all-possible-full-binary-trees | [Python3] memoized recursion | ye15 | 1 | 281 | all possible full binary trees | 894 | 0.8 | Medium | 14,482 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/2844272/Python-Dynamic-Programming | class Solution:
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
d = {}
d[0] = [None]
for i in range(1, n+1):
d[i] = []
for i in range(1, n+1):
for li in range(i):
left_len = li
right_len = i - li - 1
for left_node in d[left_len]:
for right_node in d[right_len]:
if left_node == None and right_node != None or left_node != None and right_node == None:
continue
d[i].append(TreeNode(0, left_node, right_node))
return d[n] | all-possible-full-binary-trees | Python Dynamic Programming | gne931 | 0 | 2 | all possible full binary trees | 894 | 0.8 | Medium | 14,483 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/2763228/3-Approaches%3A-with-and-without-DP | class Solution:
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
if n == 1: return [TreeNode(0)]
ans = []
for i in range(1, n, 2):
for l in self.allPossibleFBT(i):
for r in self.allPossibleFBT(n-i-1):
root = TreeNode(0)
root.left = l
root.right = r
ans.append(root)
return ans | all-possible-full-binary-trees | 3 Approaches: with and without DP | Mencibi | 0 | 16 | all possible full binary trees | 894 | 0.8 | Medium | 14,484 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/2763228/3-Approaches%3A-with-and-without-DP | class Solution:
dp = {}
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
if n in self.dp: return self.dp[n]
if n == 1:
self.dp[n] = [TreeNode(0)]
return self.dp[n]
ans = []
for i in range(1, n, 2):
for l in self.allPossibleFBT(i):
for r in self.allPossibleFBT(n-i-1):
root = TreeNode(0)
root.left = l
root.right = r
ans.append(root)
self.dp[n] = ans
return ans | all-possible-full-binary-trees | 3 Approaches: with and without DP | Mencibi | 0 | 16 | all possible full binary trees | 894 | 0.8 | Medium | 14,485 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/2763228/3-Approaches%3A-with-and-without-DP | class Solution:
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
if not n % 2: return []
if n == 1: return [TreeNode(0)]
if n == 3:
root = TreeNode(0)
root.left = TreeNode(0)
root.right = TreeNode(0)
return [root]
ans = []
for i in range(1, n//2, 2):
for l in self.allPossibleFBT(i):
for r in self.allPossibleFBT(n-i-1):
root = TreeNode(0)
root.left = l
root.right = r
ans.append(root)
root = TreeNode(0)
root.left = r
root.right = l
ans.append(root)
if n > 3:
ret = self.allPossibleFBT(n//2)
for l in ret:
for r in ret:
root = TreeNode(0)
root.left = l
root.right = r
ans.append(root)
return ans | all-possible-full-binary-trees | 3 Approaches: with and without DP | Mencibi | 0 | 16 | all possible full binary trees | 894 | 0.8 | Medium | 14,486 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/2295067/recursion-with-backtracking | class Solution:
def allPossibleFBT(self, N: int) -> List[Optional[TreeNode]]:
if (N-1)% 2: return []
ans = []
root = TreeNode(); leaves = []
def updateTreeList(node, leaves, n):
if n == 0:
ans.append(copy.deepcopy(root))
return
node.left = TreeNode()
node.right = TreeNode()
leaves.append(node.left)
leaves.append(node.right)
n-= 2
# for backtracking in below while loop
sz = len(leaves) - 1
while leaves:
cur_node = leaves.pop()
updateTreeList(cur_node, leaves[:sz], n)
# backtrack
cur_node.left = cur_node.right = None
if n == 0: break
updateTreeList(root, leaves, N-1)
return ans | all-possible-full-binary-trees | recursion with backtracking | sinha_meenu | 0 | 132 | all possible full binary trees | 894 | 0.8 | Medium | 14,487 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/2253533/Python3-Recursive-solution-with-comments | class Solution:
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
if n % 2 == 0:
return []
if n == 1:
return [TreeNode(0)]
ans = []
# on left side, we have i nodes. on right side we have (n-i-1) nodes. the extra 1 subtraction is root node.
# on the left and right side, we can have 1, 3, 5, 7 .... nodes
for i in range(1, n, 2):
leftNode = self.allPossibleFBT(i)
# loop will go till n-2, so at last case, # of nodes in right side will be (n - n - 2 - 1) ==> 1
rightNode = self.allPossibleFBT(n-1-i)
for left in leftNode:
for right in rightNode:
node = TreeNode(0, left, right)
ans.append(node)
return ans | all-possible-full-binary-trees | [Python3] Recursive solution with comments | Gp05 | 0 | 51 | all possible full binary trees | 894 | 0.8 | Medium | 14,488 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/2229147/Python-recursive | class Solution:
def allPossibleFBT(self, n: int, memo={1: [TreeNode()]}) -> List[Optional[TreeNode]]:
if n in memo:
return memo[n]
result = []
for m in range(1, n, 2):
left_list = self.allPossibleFBT(m)
right_list = self.allPossibleFBT(n - m - 1)
for left in left_list:
for right in right_list:
result.append(TreeNode(0, left, right))
memo[n] = result
return result | all-possible-full-binary-trees | Python, recursive | blue_sky5 | 0 | 65 | all possible full binary trees | 894 | 0.8 | Medium | 14,489 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/1631606/Python-or-DFS | class Solution:
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
def dfs(num,ind):
if num%2==0:
return None
if num>0:
l,r=None,None
tmp=[]
for i in range(1,num):
l=dfs(i,ind+1)
r=dfs(num-i-1,ind+1)
if l and r:
for t1 in l:
for t2 in r:
tmp.append(TreeNode(0,t1,t2))
if not tmp:
return [TreeNode(0)]
return tmp
return dfs(n,0) | all-possible-full-binary-trees | Python | DFS | heckt27 | 0 | 117 | all possible full binary trees | 894 | 0.8 | Medium | 14,490 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/1370397/Python3-recursive-solution-with-caching | class Solution:
builded_tree = {0: [], 1: [TreeNode(0)]}
def allPossibleFBT(self, n: int) -> List[TreeNode]:
if n not in Solution.builded_tree:
sub_trees = []
for idx in range(n):
lefts = self.allPossibleFBT(n - idx - 1)
rights = self.allPossibleFBT(idx)
for left in lefts:
for right in rights:
sub_trees.append(TreeNode(0, left, right))
Solution.builded_tree[n] = sub_trees
return Solution.builded_tree[n] | all-possible-full-binary-trees | [Python3] recursive solution with caching | maosipov11 | 0 | 75 | all possible full binary trees | 894 | 0.8 | Medium | 14,491 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/438811/Another-straightforward-bottom-up-python-solution-beats-99.59 | class Solution:
def allPossibleFBT(self, N: int) -> List[TreeNode]:
if N % 2 == 0:
return []
if N == 1:
return [TreeNode(0)]
trees = [[TreeNode(0)]]
for i in range(0, (N - 1) // 2): # build trees with (i + 1) * 2 + 1 nodes, no need to consider even number of nodes
ar = []
for n, group_n in enumerate(trees): # consider all possible number of nodes for the first (left/right) tree
for tree_1 in group_n:
for tree_2 in trees[i - n]: # then there is only i - n number of nodes for the second (right/left) tree
node = TreeNode(0)
node.left = tree_1
node.right = tree_2
ar.append(node)
trees.append(ar)
return trees[-1] | all-possible-full-binary-trees | Another straightforward bottom-up python solution, beats 99.59% | DrFirestream | 0 | 279 | all possible full binary trees | 894 | 0.8 | Medium | 14,492 |
https://leetcode.com/problems/all-possible-full-binary-trees/discuss/368448/Python3-solution-beats-90-in-speed | class Solution:
def allPossibleFBT(self, N: int) -> List[TreeNode]:
#impossible to satisfy the conditions
if N % 2 == 0:
return []
full_list = {}
#base cases
full_list[1] = [TreeNode(0)]
temp = TreeNode(0)
temp.left = full_list[1][0]
temp.right = full_list[1][0]
full_list[3] = [temp]
for x in range(5, N+1, 2):
full_list[x] = []
n_left = 1
n_right = (x - 1) - n_left # x-1 to exclude the root node
#go through all combinations of children trees that add to x-1
while n_right >= 1:
for l_tree in full_list[n_left]:
for r_tree in full_list[n_right]:
temp = TreeNode(0)
temp.left = l_tree
temp.right = r_tree
#print(temp)
full_list[x].append(temp)
n_left += 2
n_right -= 2
#print(len(full_list[N]))
return full_list[N] | all-possible-full-binary-trees | Python3 solution, beats 90% in speed | wertylop5 | 0 | 425 | all possible full binary trees | 894 | 0.8 | Medium | 14,493 |
https://leetcode.com/problems/monotonic-array/discuss/501946/Python-and-Java-Solution-beat-96-and-100 | class Solution:
def isMonotonic(self, A: List[int]) -> bool:
if A[-1] < A[0]:
A = A[::-1]
for i in range(1, len(A)):
if A[i] < A[i-1]:
return False
return True | monotonic-array | Python and Java Solution beat 96% and 100% | justin801514 | 17 | 1,800 | monotonic array | 896 | 0.583 | Easy | 14,494 |
https://leetcode.com/problems/monotonic-array/discuss/2355132/Python-Easy-Solution-oror-Beats-97.24 | class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
a = sorted(nums)
b = sorted(nums,reverse=True)
if nums == a or nums == b:
return True
return False | monotonic-array | Python Easy Solution || Beats 97.24% | Shivam_Raj_Sharma | 3 | 99 | monotonic array | 896 | 0.583 | Easy | 14,495 |
https://leetcode.com/problems/monotonic-array/discuss/1200898/So-much-Simple-solution-%3A) | class Solution:
def isMonotonic(self, A: List[int]) -> bool:
if sorted(A)==A or sorted(A,reverse=True)==A:
return True
return False | monotonic-array | So much Simple solution :) | _jorjis | 2 | 212 | monotonic array | 896 | 0.583 | Easy | 14,496 |
https://leetcode.com/problems/monotonic-array/discuss/2027176/Python-One-Line! | class Solution:
def isMonotonic(self, nums):
return all(a >= b for a,b in pairwise(nums)) or all(b >= a for a,b in pairwise(nums)) | monotonic-array | Python - One-Line! | domthedeveloper | 1 | 78 | monotonic array | 896 | 0.583 | Easy | 14,497 |
https://leetcode.com/problems/monotonic-array/discuss/1889226/Python-one-line-solution | class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
return sorted(nums) == nums or sorted(nums, reverse=True) == nums | monotonic-array | Python one line solution | alishak1999 | 1 | 73 | monotonic array | 896 | 0.583 | Easy | 14,498 |
https://leetcode.com/problems/monotonic-array/discuss/1844612/Python-O(N)-oror-Easy | class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
inc = dec = False
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
inc = True
if nums[i] < nums[i-1]:
dec = True
return False if inc and dec else True
# TC: O(N)
# SC: O(1) | monotonic-array | Python O(N) || Easy | airksh | 1 | 78 | monotonic array | 896 | 0.583 | Easy | 14,499 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.