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/reverse-odd-levels-of-binary-tree/discuss/2590340/Mind-blowing-Python-Answer-BFS-%2B-Queue
class Solution: def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: q = Deque() q.append(root) level = 1 while q: lev = [] for _ in range(len(q)): n = q.popleft() if n.left is not None: q.append(n.left) lev.append(n.left) if n.right is not None: q.append(n.right) lev.append(n.right) if level %2 == 1: tot = len(lev) for i,l in enumerate(lev): if i >= tot //2: break lev[i].val, lev[tot-1-i].val = lev[tot-1-i].val, lev[i].val level += 1 return root
reverse-odd-levels-of-binary-tree
[Mind 🀯 blowing Python AnswerπŸ€«πŸπŸ‘ŒπŸ˜] BFS + Queue
xmky
0
24
reverse odd levels of binary tree
2,415
0.757
Medium
33,000
https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/discuss/2590277/python3-Detailed-explanation-or-intuitive-approach-or-bfs-to-get-nodes-or-update-value-IN-PLACE
class Solution: def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: bfs_traversal = self.bfs(root) for level in range(len(bfs_traversal)): if level % 2 == 0: continue reversed_values = [node.val for node in reversed(bfs_traversal[level])] for index, node in enumerate(bfs_traversal[level]): node.val = reversed_values[index] return root def bfs(self, root): traversal = [] queue = deque() queue.append(root) while queue: current = [] for _ in range(len(queue)): node = queue.popleft() if not node: continue current.append(node) if node.left: queue.append(node.left) if node.right: queue.append(node.right) traversal.append(current) return traversal
reverse-odd-levels-of-binary-tree
[python3] Detailed explanation | intuitive approach | bfs to get nodes | update value IN PLACE
_snake_case
0
31
reverse odd levels of binary tree
2,415
0.757
Medium
33,001
https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/discuss/2590180/Python-or-Hashmap-of-odd-level-lists
class Solution: def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def reverseLevel(nodes: List[Optional[TreeNode]]) -> None: for i in range(len(nodes) // 2): nodes[i].val, nodes[~i].val = nodes[~i].val, nodes[i].val levels = defaultdict(list) nodeQueue = [(root, 0)] while nodeQueue: node, level = nodeQueue.pop() if level % 2 == 1: levels[level].append(node) for child in [node.left, node.right]: if child is not None: nodeQueue.append((child, level + 1)) for level in levels.values(): reverseLevel(level) return root
reverse-odd-levels-of-binary-tree
Python | Hashmap of odd level lists
sr_vrd
0
7
reverse odd levels of binary tree
2,415
0.757
Medium
33,002
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590687/Python-Simple-Python-Solution-Using-Dictionary
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: d = defaultdict(int) for word in words: for index in range(1, len(word) + 1): d[word[:index]] += 1 result = [] for word in words: current_sum = 0 for index in range(1, len(word) + 1): current_sum = current_sum + d[word[:index]] result.append(current_sum) return result
sum-of-prefix-scores-of-strings
[ Python ] βœ…βœ… Simple Python Solution Using Dictionary πŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
1
70
sum of prefix scores of strings
2,416
0.426
Hard
33,003
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590476/Easy-Python-Solution-With-Dictionary
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: d = dict() for i in words: s="" for j in range(len(i)): s+=i[j] if s in d: d[s]+=1 else: d[s]=1 l=[] for i in words: c = 0 s="" for j in range(len(i)): s+=i[j] c+=d[s] l.append(c) return l
sum-of-prefix-scores-of-strings
Easy Python Solution With Dictionary
a_dityamishra
1
61
sum of prefix scores of strings
2,416
0.426
Hard
33,004
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590174/Not-optimal-but-easy-to-understanding
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: prefs = {} ans = [] for w in words: for i in range(1, len(w)+1): if w[0:i] not in prefs: prefs[w[0:i]] = 1 else: prefs[w[0:i]] += 1 for i, w in enumerate(words): for j in range(1, len(w)+1): if i >= len(ans): ans.append(prefs[w[0:j]]) else: ans[i] += prefs[w[0:j]] return ans
sum-of-prefix-scores-of-strings
Not optimal, but easy to understanding
fuglaeff
1
44
sum of prefix scores of strings
2,416
0.426
Hard
33,005
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2789995/Python-Trie%3A-70-time-12-space
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: trie = {} def populateTrie(trie, word): for i in range(len(word)): letter = word[i] if letter in trie: trie[letter]['count'] += 1 else: trie[letter] = {} trie[letter]['count'] = 1 trie = trie[letter] for word in words: populateTrie(trie, word) def countPrefix(trie, word): count = 0 for i in range(len(word)): letter = word[i] count += trie[letter]['count'] trie = trie[letter] return count output = [] for word in words: output.append(countPrefix(trie, word)) return output
sum-of-prefix-scores-of-strings
Python Trie: 70% time, 12% space
hqz3
0
1
sum of prefix scores of strings
2,416
0.426
Hard
33,006
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2690996/My-Python-Trie-solution
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: trie = {} for w in words: node = trie for ch in w: if ch in node: node = node[ch] node["$"] += 1 else: node[ch] = {"$": 1} node = node[ch] result = [] for w in words: node = trie total = 0 for ch in w: total += node[ch]["$"] node = node[ch] result.append(total) return result
sum-of-prefix-scores-of-strings
My Python Trie solution
MonQiQi
0
7
sum of prefix scores of strings
2,416
0.426
Hard
33,007
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2690995/My-Python-Trie-solution
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: trie = {} for w in words: node = trie for ch in w: if ch in node: node = node[ch] node["$"] += 1 else: node[ch] = {"$": 1} node = node[ch] result = [] for w in words: node = trie total = 0 for ch in w: total += node[ch]["$"] node = node[ch] result.append(total) return result
sum-of-prefix-scores-of-strings
My Python Trie solution
MonQiQi
0
3
sum of prefix scores of strings
2,416
0.426
Hard
33,008
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2591170/python3-Trie-sol-for-reference
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: T = {} z = [] for w in words: t = T for c in w: if c not in t: t[c] = {'cnt': 0} t = t[c] t['cnt'] += 1 for w in words: acc = 0 t = T for c in w: t = t[c] acc += t['cnt'] z.append(acc) return z
sum-of-prefix-scores-of-strings
[python3] Trie sol for reference
vadhri_venkat
0
10
sum of prefix scores of strings
2,416
0.426
Hard
33,009
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590425/PYTHON-Using-Dictionary
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: # words=['a'*1000 for i in range(1000)] ans=[0 for w in words] d={} for w in words: for i in range(len(w)): c=w[:i+1] if not c in d: d[c]=1 else: d[c]+=1 for i in range(len(words)): for j in range(len(words[i])): c=words[i][:j+1] if c in d.keys(): ans[i]+=d[c] else: break return ans
sum-of-prefix-scores-of-strings
[PYTHON] Using Dictionary
shreyasjain0912
0
9
sum of prefix scores of strings
2,416
0.426
Hard
33,010
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590389/Python3-trie
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: root = {} for word in words: node = root for ch in word: node = node.setdefault(ch, {}) node['#'] = node.get('#', 0) + 1 ans = [] for word in words: val = 0 node = root for ch in word: node = node[ch] val += node['#'] ans.append(val) return ans
sum-of-prefix-scores-of-strings
[Python3] trie
ye15
0
10
sum of prefix scores of strings
2,416
0.426
Hard
33,011
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590237/Clever-Python-Solution-Special-Trie
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: class TrieNode(): def __init__(self): self.children = defaultdict(TrieNode) self.isWord = False self.count = 0 class Trie(): def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for w in word: node.count += 1 node = node.children[w] node.count += 1 node.isWord = True def searchCC(self, word): tot = 0 node = self.root for w in word: node = node.children.get(w) if not node: return tot tot += node.count return tot t = Trie() for w in words: t.insert(w) r = [] for w in words: r.append( t.searchCC(w) ) return r
sum-of-prefix-scores-of-strings
[Clever Python SolutionπŸ€«πŸπŸ‘ŒπŸ˜] Special Trie
xmky
0
12
sum of prefix scores of strings
2,416
0.426
Hard
33,012
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590114/O(n)-using-HashMap-of-all-prefix-words-(Example-Illustrations)
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: keys = {} values = [] windex = [] for word in words: w = [] for i in range(len(word)): prefix = word[:i+1] key = keys.get(prefix, -1) if key == -1: keys[prefix] = len(values) key = keys[prefix] values.append(1) else: values[key] += 1 w.append(key) windex.append(w) print("words:", words) print("keys:", keys) print("values:", values) print("word index:", windex) ans = [] for wi in windex: t = 0 for idx in wi: t += values[idx] ans.append(t) print("ans:", ans) print("="*20, "\n") return ans print = lambda *a, **aa: ()
sum-of-prefix-scores-of-strings
O(n) using HashMap of all prefix words (Example Illustrations)
dntai
0
42
sum of prefix scores of strings
2,416
0.426
Hard
33,013
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590037/Python3-Brute-Force
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: cnter = defaultdict(int) res = [] #Adding all prefixes to counter for word in words: for idx in range(1, len(word) + 1): cnter[word[:idx]] += 1 #Adding up occurrences for word in words: cnt = 0 for idx in range(1, len(word) + 1): cnt += cnter[word[:idx]] res.append(cnt) return res
sum-of-prefix-scores-of-strings
[Python3] Brute Force
0xRoxas
0
33
sum of prefix scores of strings
2,416
0.426
Hard
33,014
https://leetcode.com/problems/sort-the-people/discuss/2627285/python3-oror-2-lines-with-example-oror-TM-42ms14.3MB
class Solution: # Ex: names = ["Larry","Curly","Moe"] heights = [130,125,155] def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: _,names = zip(*sorted(zip(heights,names), reverse = True)) # zipped --> [(130,"Larry"), (125,"Curly"), (155,"Moe") ] # sorted --> [(155,"Moe" ), (130,"Larry"), (125,"Curly")] # unzipped --> _ = (155,130,125) , names = ("Moe","Larry","Curly") return list(names) # list(names) = ["Moe","Larry","Curly"]
sort-the-people
python3 || 2 lines with example || T/M = 42ms/14.3MB
warrenruud
7
575
sort the people
2,418
0.82
Easy
33,015
https://leetcode.com/problems/sort-the-people/discuss/2627803/Python-Elegant-and-Short-or-One-line
class Solution: """ Time: O(n*log(n)) Memory: O(n) """ def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [name for _, name in sorted(zip(heights, names), reverse=True)]
sort-the-people
Python Elegant & Short | One line
Kyrylo-Ktl
5
240
sort the people
2,418
0.82
Easy
33,016
https://leetcode.com/problems/sort-the-people/discuss/2670358/PYTHON-or-ONE-LINER-or-99.01-SPEED
class Solution: def sortPeople(self, n: List[str], h: List[int]) -> List[str]: return [c for _, c in sorted(zip(h, n), reverse=True)]
sort-the-people
PYTHON | ONE LINER | 99.01% SPEED
omkarxpatel
4
130
sort the people
2,418
0.82
Easy
33,017
https://leetcode.com/problems/sort-the-people/discuss/2648273/Python-is-your-friend
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [b for a, b in sorted(zip(heights, names), reverse=True)]
sort-the-people
Python is your friend
votrubac
4
310
sort the people
2,418
0.82
Easy
33,018
https://leetcode.com/problems/sort-the-people/discuss/2656840/Simple-Python-solution-using-sorting
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: comb = zip(names,heights) res = [] comb = sorted(comb, key =lambda x: x[1],reverse=True) for i in comb: res.append(i[0]) return res
sort-the-people
Simple Python solution using sorting
aruj900
3
203
sort the people
2,418
0.82
Easy
33,019
https://leetcode.com/problems/sort-the-people/discuss/2620548/Python-Simple-Python-Solution-Using-Sorting
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: result = [] sort_heights = sorted(heights, reverse = True) for height in sort_heights: index = heights.index(height) result.append(names[index]) return result
sort-the-people
[ Python ] βœ…βœ… Simple Python Solution Using Sorting πŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
3
216
sort the people
2,418
0.82
Easy
33,020
https://leetcode.com/problems/sort-the-people/discuss/2774379/Easy-Python-Solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: l=[] for i in range(len(heights)): l.append([heights[i],names[i]]) l.sort(reverse=True) k=[] for i in l: k.append(i[1]) return k
sort-the-people
Easy Python Solution
Vistrit
2
480
sort the people
2,418
0.82
Easy
33,021
https://leetcode.com/problems/sort-the-people/discuss/2837222/Easy-Python-One-Line-Solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [j for i,j in sorted([(h,n) for h,n in zip(heights,names)],reverse=True)]
sort-the-people
Easy Python One Line Solution
rpatra332
1
39
sort the people
2,418
0.82
Easy
33,022
https://leetcode.com/problems/sort-the-people/discuss/2835936/Python-or-Sorted-ReverseTrueor-Simple-solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: hgts=sorted(heights,reverse=True) p=[] for i in hgts: p.append(names[heights.index(i)]) return p
sort-the-people
Python | Sorted Reverse=True| Simple solution
priyanshupriyam123vv
1
27
sort the people
2,418
0.82
Easy
33,023
https://leetcode.com/problems/sort-the-people/discuss/2804691/Python-Fast-O(n-log-n)-solution-using-sorting
class Solution: def sortPeople(self, names: list[str], heights: list[int]) -> list[str]: l = zip(names, heights) l = sorted(l, key=lambda x: x[1], reverse=True) return [i[0] for i in l]
sort-the-people
[Python] Fast O(n log n) solution using sorting
Mark_computer
1
8
sort the people
2,418
0.82
Easy
33,024
https://leetcode.com/problems/sort-the-people/discuss/2638062/Python3-easy-solution-with-explanation
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: hash = dict(zip(heights,names)) res = [] heights.sort(reverse=True) for h in heights: res.append(hash[h]) return res
sort-the-people
Python3 easy solution with explanation
khushie45
1
82
sort the people
2,418
0.82
Easy
33,025
https://leetcode.com/problems/sort-the-people/discuss/2623427/Simple-Python-Dictionary
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: myDict = {} res=[] #add key value pairs to dictionary for i in range(len(heights)): myDict[heights[i]] = names[i] #sort the keys in order of height myList = sorted(myDict.keys()) #add names using key/value pair from myDict and the sorted list of keys for i in myList: res.append(myDict[i]) #because names are appended to the end of res, the answer must be reversed before being returned return res[::-1]
sort-the-people
Simple Python Dictionary
Gooby
1
38
sort the people
2,418
0.82
Easy
33,026
https://leetcode.com/problems/sort-the-people/discuss/2623421/Dictionary-height%3A-name
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: dict_hn = {h: n for h, n in zip(heights, names)} heights.sort(reverse=True) return [dict_hn[h] for h in heights]
sort-the-people
Dictionary height: name
EvgenySH
1
20
sort the people
2,418
0.82
Easy
33,027
https://leetcode.com/problems/sort-the-people/discuss/2621567/Python3-or-n(log(n)-or-one-liner-or-beginner-friendly!
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: #beginner friendly! #creating tuple (packing) of height & names. #Tips: We have to sort according to height so put hieght first then name HeightNameTup = [] for height,name in zip(heights,names): HeightNameTup.append((height,name)) # print(HeightNameTup) #just sort HeightNameTup.sort() #unpacking return list of name only ls=[] for height, name in HeightNameTup: ls.append(name) #return list return ls[::-1]
sort-the-people
Python3 | n(log(n) | one liner | beginner friendly!
YaBhiThikHai
1
79
sort the people
2,418
0.82
Easy
33,028
https://leetcode.com/problems/sort-the-people/discuss/2850579/Python-Solution-using-Bubble-Sort
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: for i in range(len(heights)): for j in range(len(heights)-1): if heights[j] < heights[j+1]: heights[j], heights[j + 1] = heights[j + 1], heights[j] names[j], names[j+1] = names[j+1], names[j] return names
sort-the-people
Python Solution using Bubble Sort
nikhilthoratofficial
0
2
sort the people
2,418
0.82
Easy
33,029
https://leetcode.com/problems/sort-the-people/discuss/2847777/Fastest-and-simple-Python-Solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: res = {} l = 0 for i in heights: if i not in res: res[i] = names[l] l+=1 heights.sort(reverse = True) for i in range(0,len(names)): names[i] = res[heights[i]] return names
sort-the-people
Fastest and simple Python Solution
khanismail_1
0
2
sort the people
2,418
0.82
Easy
33,030
https://leetcode.com/problems/sort-the-people/discuss/2846707/sortPerson
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: #names : List[str] #heights : List[int] #rtype : List[str] d={} for i in range(len(names)): d[heights[i]]=names[i] heights.sort(reverse=True) answer=[] for height in heights: answer.append(d.get(height)) return answer
sort-the-people
sortPerson
happyhillll
0
1
sort the people
2,418
0.82
Easy
33,031
https://leetcode.com/problems/sort-the-people/discuss/2846638/Python-or-Simple-solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: i = 0 # Saving zipped pairs of (name, height) for name, height in zip(names, heights): names[i] = (name, height) i += 1 # Sorting names according to heights value names.sort(key=lambda x:x[1], reverse=True) # Extracting names from zipped pairs of (name, height) result = [name[0] for name in names] return result
sort-the-people
Python | Simple solution
pawangupta
0
1
sort the people
2,418
0.82
Easy
33,032
https://leetcode.com/problems/sort-the-people/discuss/2834742/One-liner-in-Python
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [names for heights, names in sorted(zip(heights,names), reverse=True)]
sort-the-people
One liner in Python
ksinar
0
2
sort the people
2,418
0.82
Easy
33,033
https://leetcode.com/problems/sort-the-people/discuss/2817127/python-hash-map-and-merge-sort
class Solution: def mergeSort(self,arr): if len(arr)>1: mid = len(arr)//2 left = arr[:mid] right = arr[mid:] self.mergeSort(left) self.mergeSort(right) i = 0 j = 0 k = 0 while i<len(left) and j<len(right): if left[i]>=right[j]: arr[k]=left[i] i+=1 k+=1 else: arr[k]=right[j] j+=1 k+=1 while i<len(left): arr[k]=left[i] i+=1 k+=1 while j<len(right): arr[k]=right[j] j+=1 k+=1 def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: hashmap = {} for i in range(len(names)): hashmap[heights[i]] = names[i] self.mergeSort(heights) result = [hashmap[i] for i in heights] return result
sort-the-people
python hash map and merge sort
sudharsan1000m
0
2
sort the people
2,418
0.82
Easy
33,034
https://leetcode.com/problems/sort-the-people/discuss/2816815/easy-python-using-dictionary
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: mydict=dict(zip(heights,names)) l=[] heights.sort(reverse=True) for i in heights: l.append(mydict[i]) return l
sort-the-people
easy python using dictionary
giftyaustin
0
4
sort the people
2,418
0.82
Easy
33,035
https://leetcode.com/problems/sort-the-people/discuss/2812001/Bubble-Sort-Method-Easy-Solution-Beginner
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: l = len(heights) while l: l-=1 for i in range(len(names)-1): if heights[i] < heights[i+1]: heights[i], heights[i+1] =heights[i+1], heights[i] temp = names[i] names[i] = names[i+1] names[i+1] = temp return names
sort-the-people
Bubble Sort Method Easy Solution Beginner
Jashan6
0
4
sort the people
2,418
0.82
Easy
33,036
https://leetcode.com/problems/sort-the-people/discuss/2811192/Python-zip
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: a = [n for h, n in sorted(set(zip(heights, names)))] return a[::-1]
sort-the-people
Python zip
Teyllayka
0
3
sort the people
2,418
0.82
Easy
33,037
https://leetcode.com/problems/sort-the-people/discuss/2809541/python-oror-one-line-solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [names[heights.index(i)] for i in sorted(heights,reverse=True)]
sort-the-people
python || one line solution
Nikhil2532
0
4
sort the people
2,418
0.82
Easy
33,038
https://leetcode.com/problems/sort-the-people/discuss/2801647/Python-or-single-line
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [i[1] for i in sorted(zip(heights,names),reverse = True)]
sort-the-people
Python | single line
SAI_KRISHNA_PRATHAPANENI
0
3
sort the people
2,418
0.82
Easy
33,039
https://leetcode.com/problems/sort-the-people/discuss/2800452/python-easy-solution(well-explained-beginner-friendly)
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: new=list() #taking a new list for i in range(len(names)): new.append([heights[i],names[i]]) #adding heights and names together in our new list #remember we want to sort our list according to heights so heights will be appended first new.sort(reverse=True) #sorting it in decreasing heights res=list() #final list to add only names for our output for i in new: res.append(i[1]) #here i[0]=heights and i[1]=names so output needs only names so adding only names i.e(i[1]) return(res) #return the final list
sort-the-people
python easy solution(well explained beginner friendly)
ZEdd123
0
8
sort the people
2,418
0.82
Easy
33,040
https://leetcode.com/problems/sort-the-people/discuss/2792885/python3-solution
class Solution(object): def sortPeople(self, names, heights): enum = list(enumerate(heights)) enum.sort(key = lambda x : x[1], reverse = True) res = [] for i in range(len(enum)): idx = enum[i][0] res.append(names[idx]) return res
sort-the-people
python3 solution
rachelchee25
0
6
sort the people
2,418
0.82
Easy
33,041
https://leetcode.com/problems/sort-the-people/discuss/2789412/python-solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: h=sorted(heights,reverse=1) newlist=[] for i in range(len(h)): s=heights.index(h[i]) newlist.append(names[s]) return newlist
sort-the-people
python solution
sindhu_300
0
2
sort the people
2,418
0.82
Easy
33,042
https://leetcode.com/problems/sort-the-people/discuss/2784707/python-zip
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: res = [] for name, height in zip(names, heights): res.append((height, name)) res.sort(key = lambda x: x[0], reverse = True) return [item[1] for item in res]
sort-the-people
python zip
JasonDecode
0
3
sort the people
2,418
0.82
Easy
33,043
https://leetcode.com/problems/sort-the-people/discuss/2779688/Easy-Python-Solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: res = [] list1 = sorted(heights,reverse = True) for i in list1: index = heights.index(i) res.append(names[index]) return res
sort-the-people
Easy Python Solution
dnvavinash
0
3
sort the people
2,418
0.82
Easy
33,044
https://leetcode.com/problems/sort-the-people/discuss/2778812/easy-approach!!
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: list_ = [] for i in range(len(heights)): list_.append([heights[i],names[i]]) list_.sort(reverse=True) output_ = [] for i in list_: output_.append(i[1]) return output_
sort-the-people
easy approach!!
sanjeevpathak
0
1
sort the people
2,418
0.82
Easy
33,045
https://leetcode.com/problems/sort-the-people/discuss/2770247/Python-easy-to-understand-solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: edict={} for i in range(len(heights)): for j in range(len(names)): if i==j: edict.update({heights[i]:names[j]}) new_edict=sorted(edict.items(),reverse = True) print(new_edict) new_list=[] final_list=[] for item in new_edict: new_list.append(item[1]) return new_list
sort-the-people
Python easy to understand solution
user7798V
0
4
sort the people
2,418
0.82
Easy
33,046
https://leetcode.com/problems/sort-the-people/discuss/2760727/Python3-or-Sorted-ZIP
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [x[0] for x in sorted(zip(names, heights), key=lambda x: x[1], reverse=True)]
sort-the-people
Python3 | Sorted ZIP
joshua_mur
0
3
sort the people
2,418
0.82
Easy
33,047
https://leetcode.com/problems/sort-the-people/discuss/2759386/1-line-solution-Python
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [b for a, b in sorted(zip(heights, names), key=lambda x: x[0], reverse=True)]
sort-the-people
1 line solution - Python
avs-abhishek123
0
4
sort the people
2,418
0.82
Easy
33,048
https://leetcode.com/problems/sort-the-people/discuss/2759235/Python-or-Easy-or-HashMap
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: n = len(names) hashMap = {} for i in range(n): hashMap[heights[i]] = names[i] heights.sort(reverse=True) ans = [] for i in range(len(heights)): ans.append(hashMap[heights[i]]) return ans
sort-the-people
Python | Easy | HashMap
LittleMonster23
0
12
sort the people
2,418
0.82
Easy
33,049
https://leetcode.com/problems/sort-the-people/discuss/2759235/Python-or-Easy-or-HashMap
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: hashMap = dict(zip(heights,names)) res = [] heights.sort(reverse=True) for h in heights: res.append(hashMap[h]) return res
sort-the-people
Python | Easy | HashMap
LittleMonster23
0
12
sort the people
2,418
0.82
Easy
33,050
https://leetcode.com/problems/sort-the-people/discuss/2750187/Python3-Solution-with-using-hashmap
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: d = {} for idx, height in enumerate(heights): d[height] = names[idx] heights.sort(reverse=True) res = [] for height in heights: res.append(d[height]) return res
sort-the-people
[Python3] Solution with using hashmap
maosipov11
0
7
sort the people
2,418
0.82
Easy
33,051
https://leetcode.com/problems/sort-the-people/discuss/2741539/PYTHONEASYAPPROACH
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: lookup = dict(zip(heights, names)) hSorted = sorted(lookup.keys(), reverse=True) ans = [] for h in hSorted: ans.append(lookup[h]) return ans
sort-the-people
βœ”PYTHON🐍EASYπŸ’₯APPROACH
shubhamdraj
0
8
sort the people
2,418
0.82
Easy
33,052
https://leetcode.com/problems/sort-the-people/discuss/2721623/One-liner-EZZZ-solution-Python
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [x[0] for x in sorted(list(zip(names,heights)), key = lambda x:x[1], reverse = True)]
sort-the-people
One liner EZZZ solution Python
jacobsimonareickal
0
5
sort the people
2,418
0.82
Easy
33,053
https://leetcode.com/problems/sort-the-people/discuss/2719701/Python-or-Simple-and-faster-solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: height_name_map = {} for i in range(len(names)): height_name_map[heights[i]] = names[i] sorted_height_name_list = sorted(height_name_map.items(), reverse=True) return [v[1] for v in sorted_height_name_list]
sort-the-people
Python | Simple and faster solution
kawamataryo
0
9
sort the people
2,418
0.82
Easy
33,054
https://leetcode.com/problems/sort-the-people/discuss/2718736/One-liner
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [dict(zip(heights, names))[i] for i in sorted(dict(zip(heights, names)).keys())][::-1]
sort-the-people
One liner
iakylbek
0
5
sort the people
2,418
0.82
Easy
33,055
https://leetcode.com/problems/sort-the-people/discuss/2710178/Python3-one-line-solution-with-explanation
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [i[1] for i in sorted(list(zip(heights,names)), key=lambda x:x[0], reverse=True)]
sort-the-people
Python3 one-line solution with explanation
sipi09
0
8
sort the people
2,418
0.82
Easy
33,056
https://leetcode.com/problems/sort-the-people/discuss/2703609/Python-3-Lines-easy-understanding-using-zip-lambda-and-no-for-loop.
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: a = sorted(zip(names, heights), key = lambda t: t[1], reverse=True) ans = list(zip(*a)) return ans[0]
sort-the-people
Python 3 Lines easy understanding using zip lambda and no for loop.
user2800NJ
0
5
sort the people
2,418
0.82
Easy
33,057
https://leetcode.com/problems/sort-the-people/discuss/2698942/python-1-line
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [name for (name, height) in sorted([(name, height) for name, height in zip(names, heights)], key = lambda x: -x[1])]
sort-the-people
python 1-line
emersonexus
0
9
sort the people
2,418
0.82
Easy
33,058
https://leetcode.com/problems/sort-the-people/discuss/2677734/Python-Solution-using-arrays
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: ar, res = [], [] for n , h in zip(names,heights): ar.append([n,h]) ar = sorted(ar, key = lambda x:x[1],reverse = True) for val in ar: res.append(val[0]) return res
sort-the-people
Python Solution using arrays
saumya_0606
0
3
sort the people
2,418
0.82
Easy
33,059
https://leetcode.com/problems/sort-the-people/discuss/2673366/easy-solution-python
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [row[1] for row in sorted(zip(heights, names), reverse = True)]
sort-the-people
easy solution python
MaryLuz
0
1
sort the people
2,418
0.82
Easy
33,060
https://leetcode.com/problems/sort-the-people/discuss/2668241/easy-python-soln-with-explanation
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: d={}#to link the heights with names #ex names=["Amber","Fatima"] #height=[5,2] #then d={5:"Amber,2:"Fatima"} for height in heights: for name in names: d[height]=name#here key would be height and value will be name names.remove(name) break# breaking out of the first loop f=[d[l] for l in sorted(d)[::-1]]# sorting and reversing the key and returning the value assigned to that key return (f)
sort-the-people
easy python soln with explanation
AMBER_FATIMA
0
6
sort the people
2,418
0.82
Easy
33,061
https://leetcode.com/problems/sort-the-people/discuss/2648156/Python-or-One-Line-Functional
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return map(lambda t : t[1], sorted (zip(heights, names), reverse=True))
sort-the-people
Python | One Line Functional
on_danse_encore_on_rit_encore
0
6
sort the people
2,418
0.82
Easy
33,062
https://leetcode.com/problems/sort-the-people/discuss/2641488/O(nlogn)-Solution
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: lis = sorted(list(zip(heights,names)),reverse=True) a,b = zip(*lis) return list(b)
sort-the-people
O(nlogn) Solution
anup_omkar
0
5
sort the people
2,418
0.82
Easy
33,063
https://leetcode.com/problems/sort-the-people/discuss/2639180/Python-two-line-of-code-explained!!!
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: z = sorted(list(zip(heights, names)),key=lambda x: (-x[0])) return [y for x,y in z] ''' 1. zip(heights, names) connects height[0] with names[0]....... 2. 2.sorted() key -> is used to sort by to determine by which indices to sort the array 3. the last one is list comprehension and unpacking the zipped list '''
sort-the-people
Python two line of code explained!!!
pandish
0
21
sort the people
2,418
0.82
Easy
33,064
https://leetcode.com/problems/sort-the-people/discuss/2634136/Sort-the-People-oror-Python-oror-Dictionary
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: d={} for i in range(len(names)): d[heights[i]]=names[i] #print(d) s={} s=sorted(d.items(),reverse=True) #print(s) ans=[] for i in range(len(s)): ans.append(s[i][1]) return ans`
sort-the-people
Sort the People || Python || Dictionary
shagun_pandey
0
18
sort the people
2,418
0.82
Easy
33,065
https://leetcode.com/problems/sort-the-people/discuss/2633562/One-line-solution-in-Python-faster-than-94
class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: return [n for _, n in sorted((-h, n) for h, n in zip(heights, names))]
sort-the-people
One line solution in Python, faster than 94%
metaphysicalist
0
22
sort the people
2,418
0.82
Easy
33,066
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2648255/Group-By-and-One-Pass
class Solution: def longestSubarray(self, nums: List[int]) -> int: max_n = max(nums) return max(len(list(it)) for n, it in groupby(nums) if n == max_n)
longest-subarray-with-maximum-bitwise-and
Group By and One-Pass
votrubac
7
63
longest subarray with maximum bitwise and
2,419
0.477
Medium
33,067
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2741891/Python-O(N)-with-explanation
class Solution: def longestSubarray(self, nums: List[int]) -> int: maxim = max(nums) result = 1 current = 0 for num in nums: if (num == maxim): current = current + 1 result = max(result, current) else: current = 0 return result
longest-subarray-with-maximum-bitwise-and
Python O(N) with explanation
hallucinogen
0
1
longest subarray with maximum bitwise and
2,419
0.477
Medium
33,068
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2715773/Python-3-Two-lines-O(n)
class Solution: def longestSubarray(self, nums: List[int]) -> int: mx = max(nums) return max(map(len, ''.join(map(lambda y: ('0', '1')[mx == y], nums)).split('0')))
longest-subarray-with-maximum-bitwise-and
[Python 3] Two lines O(n)
qsqnk
0
7
longest subarray with maximum bitwise and
2,419
0.477
Medium
33,069
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2669704/Python3-one-liner-using-itertools.groupby
class Solution: def longestSubarray(self, nums: List[int]) -> int: x = max(nums) res = 1 for c, g in itertools.groupby(nums): if c == x: res = max(res, len(list(g))) return res
longest-subarray-with-maximum-bitwise-and
Python3 one liner using itertools.groupby
acerunner
0
5
longest subarray with maximum bitwise and
2,419
0.477
Medium
33,070
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2669704/Python3-one-liner-using-itertools.groupby
class Solution: def longestSubarray(self, nums: List[int]) -> int: return max([(n, len(list(g))) for n, g in itertools.groupby(nums)])[1]
longest-subarray-with-maximum-bitwise-and
Python3 one liner using itertools.groupby
acerunner
0
5
longest subarray with maximum bitwise and
2,419
0.477
Medium
33,071
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2621437/O(n)-with-maximum-length-of-sub-array-consisting-of-highest-values
class Solution: def longestSubarray(self, nums: List[int]) -> int: ans = 0 vmax = -1 cmax = 0 for i in range(len(nums)): if vmax==-1 or nums[vmax]<nums[i]: vmax = i cmax = 1 ans = 1 elif nums[vmax]==nums[i]: cmax = cmax + 1 ans = max(ans, cmax) elif nums[vmax]>nums[i]: cmax = 0 return ans
longest-subarray-with-maximum-bitwise-and
O(n) with maximum length of sub-array consisting of highest values
dntai
0
4
longest subarray with maximum bitwise and
2,419
0.477
Medium
33,072
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2620799/Python3-O(n)-count-maximum-length-of-continuous-maximum-numbers
class Solution: def longestSubarray(self, nums: List[int]) -> int: maxi = max(nums) res = 1 current = 0 for i in range(len(nums)): if nums[i] == maxi: current += 1 else: res = max(res, current) current = 0 return max(res, current)
longest-subarray-with-maximum-bitwise-and
Python3 O(n) count maximum length of continuous maximum numbers
xxHRxx
0
3
longest subarray with maximum bitwise and
2,419
0.477
Medium
33,073
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2620742/Python-Simple-Python-Solution
class Solution: def longestSubarray(self, nums: List[int]) -> int: result = 0 current_subarry_length = 0 max_value_of_nums = max(nums) for index in range(len(nums)): if nums[index] == max_value_of_nums: current_subarry_length = current_subarry_length + 1 result = max(result, current_subarry_length) else: current_subarry_length = 0 return result
longest-subarray-with-maximum-bitwise-and
[ Python ] βœ…βœ… Simple Python Solution πŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
0
28
longest subarray with maximum bitwise and
2,419
0.477
Medium
33,074
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2620615/Python3-or-longest-Consecutive-occurrence-of-max-element
class Solution: def longestSubarray(self, nums: List[int]) -> int: mx=max(nums) ans=0 v=0 for i in range(len(nums)): if nums[i]==mx: v+=1 ans=max(ans,v) else: v=0 return ans
longest-subarray-with-maximum-bitwise-and
[Python3] | longest Consecutive occurrence of max element
swapnilsingh421
0
3
longest subarray with maximum bitwise and
2,419
0.477
Medium
33,075
https://leetcode.com/problems/find-all-good-indices/discuss/2620637/Python3-Two-passes-O(n)-with-line-by-line-comments.
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: ### forward pass. forward = [False]*len(nums) ### For the forward pass, store if index i is good or not. stack = [] for i in range(len(nums)): ### if the leangth of stack is greater or equal to k, it means this index is good. if len(stack)>=k: forward[i] = True ### if the stack is empty, just add the current number to it. if not stack: stack.append(nums[i]) ### check to see if the current number is smaller or equal to the last number in stack, if it is not, put this number into the stack. else: if nums[i]<=stack[-1]: stack.append(nums[i]) else: stack = [nums[i]] ### backward pass res = [] stack = [] for i in reversed(range(len(nums))): ### Check to see if the length of stack is greater or equal to k and also check if the forward pass at this index is Ture. if len(stack)>=k and forward[i]: res.append(i) if not stack: stack.append(nums[i]) else: if nums[i]<=stack[-1]: stack.append(nums[i]) else: stack = [nums[i]] return res[::-1]
find-all-good-indices
[Python3] Two passes O(n) with line by line comments.
md2030
34
1,400
find all good indices
2,420
0.372
Medium
33,076
https://leetcode.com/problems/find-all-good-indices/discuss/2845486/Clean-Fast-Python3-or-Prefix-and-Suffix
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: n = len(nums) non_inc_prefix = [1] * n for i in range(1, n-1): if nums[i-1] >= nums[i]: non_inc_prefix[i] += non_inc_prefix[i-1] non_dec_suffix = [1] * n for i in range(n-2, 0, -1): if nums[i] <= nums[i+1]: non_dec_suffix[i] += non_dec_suffix[i+1] good = [] for i in range(k, n - k): if non_inc_prefix[i-1] >= k <= non_dec_suffix[i+1]: good.append(i) return good
find-all-good-indices
Clean, Fast Python3 | Prefix & Suffix
ryangrayson
0
1
find all good indices
2,420
0.372
Medium
33,077
https://leetcode.com/problems/find-all-good-indices/discuss/2836594/Python-(Simple-DP)
class Solution: def goodIndices(self, nums, k): n, res = len(nums), [] dec, inc = [1]*n, [1]*n for i in range(1,n): if nums[i] <= nums[i-1]: dec[i] = dec[i-1] + 1 for i in range(n-2,-1,-1): if nums[i] <= nums[i+1]: inc[i] = inc[i+1] + 1 for i in range(k,n-k): if dec[i-1] >= k and inc[i+1] >= k: res.append(i) return res
find-all-good-indices
Python (Simple DP)
rnotappl
0
3
find all good indices
2,420
0.372
Medium
33,078
https://leetcode.com/problems/find-all-good-indices/discuss/2627671/Linear-solution-three-passes
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: len_nums = len(nums) decreasing = [1] * len_nums left = nums[0] count = 0 for i, n in enumerate(nums): if n <= left: count += 1 else: count = 1 left = n decreasing[i] = count increasing = [1] * len_nums right = nums[-1] count = 0 for i in range(len_nums - 1, -1, -1): if nums[i] <= right: count += 1 else: count = 1 right = nums[i] increasing[i] = count return [i for i in range(k, len_nums - k) if decreasing[i - 1] >= k and increasing[i + 1] >= k]
find-all-good-indices
Linear solution, three passes
EvgenySH
0
14
find all good indices
2,420
0.372
Medium
33,079
https://leetcode.com/problems/find-all-good-indices/discuss/2624366/Python3-O(n)-build-lookup-table
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: size_t = len(nums) grid1, grid2 = [1], [1] for t in range(0, size_t-1): src, tar = nums[t], nums[t+1] if tar <= src: if not grid1: grid1.append(1) else: grid1.append(grid1[-1] + 1) else: grid1.append(1) for t in range(size_t-2, -1, -1): src, tar = nums[t], nums[t+1] if tar >= src: if not grid2: grid2.append(1) else: grid2.append(grid2[-1] + 1) else: grid2.append(1) grid2 = grid2[::-1] res = [] for t in range(k, size_t - k): if grid1[t-1] >= k and grid2[t+1] >= k: res.append(t) return res
find-all-good-indices
Python3 O(n) build lookup table
xxHRxx
0
8
find all good indices
2,420
0.372
Medium
33,080
https://leetcode.com/problems/find-all-good-indices/discuss/2621424/O(n)-using-updating-in-sliding-window-by-first-last-pairs-(Example-Illustration)
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: n = len(nums) n1 = 0 for i in range(1, k): if nums[i-1]>=nums[i]: n1 += 1 n2 = 0 if 2*k<=n-1: for i in range(k+2, 2*k+1): if nums[i-1]<=nums[i]: n2 += 1 print(nums, k) ans = [] for i in range(k, n-k, 1): print("++ ", i, nums[i-k:i], nums[i+1:i+k+1], n1, n2) if k==1 or (n1==k-1 and n2==k-1): ans.append(i) if i+k+1<=n-1: # before if nums[i-k]>=nums[i-k+1]: n1 -= 1 if nums[i-1]>=nums[i]: n1 += 1 # after if nums[i+1]<=nums[i+2]: n2 -= 1 if nums[i+k]<=nums[i+k+1]: n2 += 1 print("ans:", ans) print("=" * 20, "\n") return ans print = lambda *a, **aa: ()
find-all-good-indices
O(n) using updating in sliding window by first, last pairs (Example Illustration)
dntai
0
7
find all good indices
2,420
0.372
Medium
33,081
https://leetcode.com/problems/find-all-good-indices/discuss/2621252/Python3-Clean-One-Pass-O(n)-Time-O(1)-Space-(excluding-output)
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: res = [] left_count = 1 right_count = 0 prev_left = nums[0] prev_right = float('-inf') for i in range(1, len(nums)-k): if prev_left >= nums[i-1]: left_count += 1 else: left_count = 1 prev_left = nums[i-1] if prev_right <= nums[i+k]: right_count += 1 else: right_count = 1 prev_right = nums[i+k] if left_count >= k and right_count >= k: res.append(i) return res
find-all-good-indices
[Python3] Clean One Pass O(n) Time, O(1) Space (excluding output)
rt500
0
35
find all good indices
2,420
0.372
Medium
33,082
https://leetcode.com/problems/find-all-good-indices/discuss/2620777/Python-prefix-and-suffix-arrays-explained
class Solution: # Create prefix and suffix arrays # Count elements in pre and suf for i that follow the specified pattern # if number of elements following the pattern is greater than k then add i to the answer # return sorted answer as specified in the question def goodIndices(self, nums: List[int], k: int) -> List[int]: n = len(nums) pre, suf = [0] * n, [0] * n l = 1 for i in range(1, n): pre[i] = l if nums[i] <= nums[i - 1]: l += 1 else: l = 1 l = 1 for i in range(n - 2, -1, -1): suf[i] = l if nums[i] <= nums[i + 1]: l += 1 else: l = 1 res = [] for i in range(1, n - 1): if pre[i] >= k and suf[i] >= k: res.append(i) return res
find-all-good-indices
Python prefix and suffix arrays explained
shiv-codes
0
25
find all good indices
2,420
0.372
Medium
33,083
https://leetcode.com/problems/find-all-good-indices/discuss/2620572/Python3-or-Easy-O(N)
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: n=len(nums) left=[False for i in range(n)] right=[False for i in range(n)] ls,rs=-1,n for i in range(1,n): if i>=k: if i-ls>k: left[i]=True if nums[i]>nums[i-1]: ls=i-1 for j in range(n-2,-1,-1): if j<n-k: if rs-j>k: right[j]=True if nums[j]>nums[j+1]: rs=j+1 ans=[] for i in range(n): if left[i] and right[i]: ans.append(i) return ans
find-all-good-indices
[Python3] | Easy O(N)
swapnilsingh421
0
28
find all good indices
2,420
0.372
Medium
33,084
https://leetcode.com/problems/number-of-good-paths/discuss/2623051/Python-3Hint-solution-Heap-%2B-Union-find
class Solution: def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int: n = len(vals) g = defaultdict(list) # start from node with minimum val for a, b in edges: heappush(g[a], (vals[b], b)) heappush(g[b], (vals[a], a)) loc = list(range(n)) def find(x): if loc[x] != x: loc[x] = find(loc[x]) return loc[x] def union(x, y): a, b = find(x), find(y) if a != b: loc[b] = a # node by val v = defaultdict(list) for i, val in enumerate(vals): v[val].append(i) ans = n for k in sorted(v): for node in v[k]: # build graph if neighboring node <= current node val while g[node] and g[node][0][0] <= k: nei_v, nei = heappop(g[node]) union(node, nei) # Count unioned groups grp = Counter([find(x) for x in v[k]]) # for each unioned group, select two nodes (order doesn't matter) ans += sum(math.comb(x, 2) for x in grp.values()) return ans
number-of-good-paths
[Python 3]Hint solution Heap + Union find
chestnut890123
0
57
number of good paths
2,421
0.398
Hard
33,085
https://leetcode.com/problems/number-of-good-paths/discuss/2621342/O(nlogn)-using-Union-Find-Merging-and-counting-from-low-to-high-values-(Example-Illustration)
class Solution: def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int: def find(root, x): if root[x]==x: return x else: root[x] = find(root, root[x]) return root[x] n = len(vals) nodes = {} for i in range(n): nodes[vals[i]] = nodes.get(vals[i], set([])) nodes[vals[i]].add(i) print("nodes:", nodes) adj = [[] for _ in range(n)] for ai, bi in edges: adj[ai].append(bi) adj[bi].append(ai) print("adj:", adj) keys = sorted(nodes.keys(), key = lambda x: x) root = list(range(n)) ans = len(root) print("Init:", "root:", root, "ans:", ans) for k in keys: q = nodes[k] for u in q: for v in adj[u]: if vals[v]<=vals[u]: root_u = find(root, u) root_v = find(root, v) if root_u != root_v: root[root_u] = root_v levels = {} for u in q: root_u = find(root, u) levels[root_u] = levels.get(root_u, 0) + 1 cnt = sum([levels[i]*(levels[i]-1)//2 for i in levels]) ans = ans + cnt print("+ val", k, root, levels, cnt) print("ans:", ans) print("=" * 20, "\n") return ans pass print = lambda *a, **aa: ()
number-of-good-paths
O(nlogn) using Union-Find Merging and counting from low to high values (Example Illustration)
dntai
0
31
number of good paths
2,421
0.398
Hard
33,086
https://leetcode.com/problems/number-of-good-paths/discuss/2621342/O(nlogn)-using-Union-Find-Merging-and-counting-from-low-to-high-values-(Example-Illustration)
class Solution: def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int: n = len(vals) nodes = {} for i in range(n): nodes[vals[i]] = nodes.get(vals[i], set([])) nodes[vals[i]].add(i) # print(nodes) adj = [set([]) for _ in range(n)] for ai, bi in edges: adj[ai].add(bi) adj[bi].add(ai) # print(adj) def bfs(s, chk): ret = [s] q = [s] chk[s] = True while len(q)>0: u = q.pop(0) for v in adj[u]: if chk[v]==False and vals[s]>=vals[v]: q.append(v) chk[v] = True if vals[v]==vals[s]: ret.append(v) return ret keys = sorted(nodes.keys(), key = lambda x: x) chk = [False] * n ans = len(vals) for k in keys: qq = nodes[k] print("++ ", k, len(qq)) sys.stdout.flush() while len(qq)>0: v = qq.pop() ret = bfs(v, chk) nr = len(ret) ans = ans + (nr * (nr-1)) // 2 for t in ret: qq.discard(t) return ans print = lambda *a, **aa: ()
number-of-good-paths
O(nlogn) using Union-Find Merging and counting from low to high values (Example Illustration)
dntai
0
31
number of good paths
2,421
0.398
Hard
33,087
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2660629/Counter-of-Counter
class Solution: def equalFrequency(self, word: str) -> bool: cnt = Counter(Counter(word).values()) if (len(cnt) == 1): return list(cnt.keys())[0] == 1 or list(cnt.values())[0] == 1 if (len(cnt) == 2): f1, f2 = min(cnt.keys()), max(cnt.keys()) return (f1 + 1 == f2 and cnt[f2] == 1) or (f1 == 1 and cnt[f1] == 1) return False
remove-letter-to-equalize-frequency
Counter of Counter
votrubac
9
336
remove letter to equalize frequency
2,423
0.193
Easy
33,088
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2647798/Python3-OneLine-BruteForce
class Solution: def equalFrequency(self, word: str) -> bool: return any(len(set(Counter(word[:i]+word[i+1:]).values()))==1 for i in range(len(word)))
remove-letter-to-equalize-frequency
Python3, OneLine BruteForce
Silvia42
1
17
remove letter to equalize frequency
2,423
0.193
Easy
33,089
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2647798/Python3-OneLine-BruteForce
class Solution: def equalFrequency(self, word: str) -> bool: for i in range(len(word)): z=word[:i]+word[i+1:] if len(set(Counter(z).values()))==1: return True return False
remove-letter-to-equalize-frequency
Python3, OneLine BruteForce
Silvia42
1
17
remove letter to equalize frequency
2,423
0.193
Easy
33,090
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2647389/Python-Solution-or-An-Easy-Solution
class Solution: def isequal(self, c): c = Counter(c) return len(list(set(list(c.values())))) == 1 def equalFrequency(self, word: str) -> bool: for i in range(len(word)): if self.isequal(word[:i] + word[i + 1:]): return True return False
remove-letter-to-equalize-frequency
Python Solution | An Easy Solution
cyber_kazakh
1
55
remove letter to equalize frequency
2,423
0.193
Easy
33,091
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2646978/Four-conditions-(hard-problem!)
class Solution: def equalFrequency(self, word: str) -> bool: counter = Counter(word) list = [] for _, v in counter.items(): if v: list.append(v) list.sort() if len(list) == 1: # example: 'ddddd' return True if list[-1] == 1: # example: 'abcdefg' return True if list[0] == 1 and list[1] == list[-1]: # example: 'bdddfff' return True if list[-1] == list[-2] + 1 and list[0] == list[-2]: # example: 'bbbdddgggg' return True # all other cases are bad conditions return False
remove-letter-to-equalize-frequency
Four conditions (hard problem!)
pya
1
58
remove letter to equalize frequency
2,423
0.193
Easy
33,092
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2646871/Python-frequency-Counter
class Solution: def equalFrequency(self, word: str) -> bool: freq = Counter(word).values() return (len(freq) == 1 or min(freq) == max(freq) == 1 or (min(freq) == max(freq) - 1 and ( len(word) == min(freq) * len(freq) + 1 or len(word) == max(freq) * len(freq) - 1) ) )
remove-letter-to-equalize-frequency
Python, frequency Counter
blue_sky5
1
55
remove letter to equalize frequency
2,423
0.193
Easy
33,093
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2646748/Easy-to-understand.
class Solution: def equalFrequency(self, word: str) -> bool: m = {} flag = True for i in word: if i in m: m[i]+=1 else: m[i]=1 m1 = {} for key,val in m.items(): if m[key] in m1: m1[m[key]]+=1 else: m1[m[key]] = 1 if len(m1)>2: return False maxi = -sys.maxsize mini = sys.maxsize for key,val in m1.items(): maxi = max(maxi,key) mini = min(mini,key) if len(m1)==1 and maxi==1: #eg: abcd return True if (maxi==mini and len(m1)==1 and m1[maxi]==1): #eg: aaaa return True if maxi-mini==1 and (m1[maxi]==1 or m1[mini]==1): #remaining all return True else: return False
remove-letter-to-equalize-frequency
Easy to understand.
kamal0308
1
86
remove letter to equalize frequency
2,423
0.193
Easy
33,094
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2807473/O(n)-32ms-Python-use-word-only-once!
class Solution: def equalFrequency(self, word: str) -> bool: #go over a word and get the frequencies for every char a-z #return int[26] #constraint: only accepts words with lowercase chars a-z inside def getCharFreqs(word: str) -> int: counts = [0 for i in range(26)] #alphabet freqs initial 0 for n in range(len(word)): #go over word counts[ord(word[n])-97] += 1 #add the char to the freqs return counts #If there are only zeros and maybe one other frequency in the counts, return true def checkCounts(counts: list) -> bool: freq = 0 for i in range(26): if counts[i] == 0: continue #Just unused char if counts[i] != 0 and freq == 0: freq = counts[i] #Not unused char, initialize the var to look for more if counts[i] == freq: continue #just another one with known frequency if counts[i] != freq: return False #Found another unknown frequency! return True #There is only one known frequency or not even one counts = getCharFreqs(word) #O(n) go over word, extract frequencies for every char a-z for i in range(26): #For each char in the alphabet if counts[i] > 0: #Only test if this char got used counts[i] -= 1 #Remove one of these chars if (checkCounts(counts)): return True #Check for true-condition counts[i] += 1 #Else take back the useless change return False #Didnt found a solution
remove-letter-to-equalize-frequency
O(n) 32ms Python - use word only once!
lucasscodes
0
6
remove letter to equalize frequency
2,423
0.193
Easy
33,095
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2729822/Easy-understanding-python-solution-with-explanation
class Solution: def equalFrequency(self, w: str) -> bool: #pattern 1: 1, x, x (delete 1) #pattern 2: x, x, x + 1 (delete 1 from x + 1) mp = {} n = len(w) for i in range(len(w)): mp[w[i]] = mp.get(w[i], 0) + 1 print(mp) freq = list(mp.values()) freq.sort() print(freq) # pattern 1 p1, p2 = False, False if freq[0] == 1: p1 = True for i in range(1, len(freq) - 1): if freq[i] != freq[i + 1]: p1 = False if p1: return True # pattern 2 p2 = True freq[len(freq)-1] -= 1 for i in range(len(freq) - 1): if freq[i] != freq[i + 1]: p2 = False if p2: return True return False
remove-letter-to-equalize-frequency
Easy understanding python solution with explanation
jackson-cmd
0
6
remove letter to equalize frequency
2,423
0.193
Easy
33,096
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2694141/2423.-Remove-Letters-to-Equalize-Frequency.
class Solution: def equalFrequency(self, word: str) -> bool: dic={} for i in range(len(word)): if word[i] not in dic: dic[word[i]]=1 else: dic[word[i]]+=1 arr=[] for i in dic: arr.append(dic[i]) for i in range(len(arr)): arr[i]=arr[i]-1 if len(set(arr))==1: return 1 if len(set(arr))==2 and min(arr)==0: return 1 else: arr[i]+=1 return 0
remove-letter-to-equalize-frequency
2423. Remove Letters to Equalize Frequency.
rinkon
0
5
remove letter to equalize frequency
2,423
0.193
Easy
33,097
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2679224/Python-Solution-Beats-around-88-in-speed
class Solution: def equalFrequency(self, word: str) -> bool: counter = {} maxValue = -1 oneCounter = 0 maxCounter = 0 maxMinusCounter = 0 for letter in word: if letter not in counter: counter[letter] = 0 counter[letter] += 1 maxValue = max(maxValue, counter[letter]) for letter in counter: if counter[letter] == 1: oneCounter += 1 if counter[letter] == maxValue: maxCounter += 1 if counter[letter] == maxValue - 1: maxMinusCounter += 1 return (oneCounter == len(counter) or oneCounter == 1 and maxCounter + 1 >= len(counter) or maxMinusCounter + 1 == len(counter));
remove-letter-to-equalize-frequency
Python Solution Beats around 88% in speed
Omyx
0
8
remove letter to equalize frequency
2,423
0.193
Easy
33,098
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2670999/Easy-and-fast-Python3-solution%3A-Faster-than-97-of-submissions
class Solution: def equalFrequency(self, word: str) -> bool: frequencies = [word.count(i) for i in sorted(set(word))] for i in range(len(frequencies)): frequencies_copy = frequencies[:] if frequencies_copy[i] == 1: frequencies_copy.pop(i) else: frequencies_copy[i] -= 1 if len(set(frequencies_copy)) == 1: return True return False
remove-letter-to-equalize-frequency
Easy and fast Python3 solution: Faster than 97% of submissions
y-arjun-y
0
78
remove letter to equalize frequency
2,423
0.193
Easy
33,099