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/append-k-integers-with-minimal-sum/discuss/1823927/Python-O(nlogn)-solution-with-n(n%2B1)-2-Range-Sum
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: # define range sum def range_sum(start, stop, step=1): number_of_terms = (stop - start) // step sum_of_extrema = start + (stop - step) return number_of_terms * sum_of_extrema // 2 nums = list(set(nums)) # remove repeats nums.sort() # O(nlogn) # total sum sol = 0 prev = 0 ptr = 0 while k > 0: if ptr < len(nums): # potential window to add nums gap = nums[ptr] - prev - 1 sol += range_sum(prev+1, min(nums[ptr], prev+k+1)) # add range sum O(1) k -= gap prev = nums[ptr] ptr += 1 else: # draw numbers after all numbers in the list sol += range_sum(prev+1, prev + remaining + 1) k = 0 return sol
append-k-integers-with-minimal-sum
Python O(nlogn) solution with n(n+1) / 2 Range Sum
MaanavS
3
207
append k integers with minimal sum
2,195
0.25
Medium
30,500
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/2209384/python-or-O(nlogn)-solution-using-sort-or-97.65-faster
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: k_sum = k * (k + 1) // 2 nums = [*set(nums)] nums.sort() for num in nums: if num > k: break else: k += 1 k_sum += k - num return k_sum
append-k-integers-with-minimal-sum
python | O(nlogn) solution using sort | 97.65% faster
ahmadheshamzaki
1
146
append k integers with minimal sum
2,195
0.25
Medium
30,501
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1825525/Python-3-Arithmatic-progression
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: # remove dupliate nums and sort nums = sorted(set(nums)) nums = [0] + nums + [float("inf")] ans = 0 for i in range(1, len(nums)): # difference between two adjacent numbers diff = nums[i] - nums[i-1] - 1 if diff <= 0: continue # fill in the gap from nums[i-1] + 1 to nums[i] - 1 if diff < k: k -= diff ans += (nums[i-1] + 1) * diff + diff * (diff - 1) // 2 # fill the first k nums from nums[i-1] + 1 else: return ans + (nums[i-1] + 1) * k + k * (k - 1) // 2 return ans
append-k-integers-with-minimal-sum
[Python 3] Arithmatic progression
chestnut890123
1
58
append k integers with minimal sum
2,195
0.25
Medium
30,502
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1824079/Python-sum-all-nums-between-a-b-using-n-*-(n-%2B-1)-2
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: def sum_between(a, b): # inclusive sum all nums between a, b # eg: 40, 41, 42, 43, 44 # = 40 + 40 + 40 + 40 + 40 # +1 +2 +3 +4 # = 40 * 5 + sum of 1 to 4 # formula for sum of 1 to n: (n * (n + 1))//2 if b < a: return 0 dist = b - a + 1 n = dist - 1 return a * dist + (n * (n + 1))//2 nums.append(0) nums.sort() res = 0 # sum between all the gaps in the list for i in range(1, len(nums)): last = nums[i-1] + 1 cur = min(last + k - 1, nums[i] - 1) if last > cur: continue res += sum_between(last, cur) k -= cur-last+1 if k == 0: return res # add additional res += sum_between(nums[-1] + 1, nums[-1] + k) return res
append-k-integers-with-minimal-sum
Python sum all nums between a, b using n * (n + 1) / 2
davidc360
1
71
append k integers with minimal sum
2,195
0.25
Medium
30,503
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1823825/Python3-Sorting-One-Pass-greedy-11-line-solution-(explained)
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: nums = sorted(set(nums)) full_series = k * (k + 1) // 2 for n in nums: if n <= k: full_series += k - n + 1 k += 1 else: break return full_series
append-k-integers-with-minimal-sum
[Python3] Sorting, One-Pass greedy 11-line solution (explained)
dwschrute
1
51
append k integers with minimal sum
2,195
0.25
Medium
30,504
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/2837153/Python-sorting
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: if k == 0: return 0 result = 0 nums.sort() nums = [0] + nums for i in range(1, len(nums)): diff = nums[i] - nums[i - 1] if diff <= 1: continue n = min(k, (nums[i] - nums[i - 1]) - 1) left = nums[i - 1] + 1 right = nums[i - 1] + n result += (n / 2) * (left + right) k -= n if k == 0: return int(result) if k > 0: left = nums[-1] + 1 right = nums[-1] + k result += (k / 2) * (left + right) return int(result)
append-k-integers-with-minimal-sum
Python, sorting
swepln
0
3
append k integers with minimal sum
2,195
0.25
Medium
30,505
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/2755901/JavaPython3-or-Sorting-or-O(nlogn)
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: nums.sort() vis=set() currSum=k*(k+1)//2 ptr=0 for num in nums: if 1<=num<=k+ptr and num not in vis: currSum-=num ptr+=1 currSum+=k+ptr vis.add(num) return currSum
append-k-integers-with-minimal-sum
[Java/Python3] | Sorting | O(nlogn)
swapnilsingh421
0
8
append k integers with minimal sum
2,195
0.25
Medium
30,506
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1953013/Python.-Easy-and-Concise.-Math.-T.C%3A-O(nlogn)
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: # Append 0 and +inf to avoid extra checks in the for loop nums.append(0) nums.append(float("+inf")) nums.sort() total = 0 for i in range(1, len(nums)): if k == 0: break # check that the numbers are different elif nums[i] == nums[i-1]: continue else: # calculate the sum between n1 and n2 in O(1) n1, n2 = nums[i-1]+1, nums[i]-1 # Special check in case that there more numbers than k if n2 - n1 + 1 > k: n2 = n1 + k - 1 remaining = k k = 0 else: remaining = n2 - n1 + 1 k -= n2 - n1 + 1 total += remaining * (n2 + n1) // 2 return total
append-k-integers-with-minimal-sum
Python. Easy & Concise. Math. T.C: O(nlogn)
asbefu
0
110
append k integers with minimal sum
2,195
0.25
Medium
30,507
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1886212/Python-3-oror-O(nlogn)
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: def sumToN(n): return n * (n + 1) // 2 nums.sort() prev = res = 0 for num in nums: x = max(0, min(k, num - prev - 1)) res += sumToN(prev + x) - sumToN(prev) k -= x if k == 0: return res prev = num return res + sumToN(prev + k) - sumToN(prev)
append-k-integers-with-minimal-sum
Python 3 || O(nlogn)
dereky4
0
132
append k integers with minimal sum
2,195
0.25
Medium
30,508
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1836762/Sort-and-count-sums-between-numbers-71-speed
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: start, ans = 1, 0 for n in sorted(nums): if start < n: if n - start <= k: ans += (start + n - 1) * (n - start) // 2 k -= n - start else: ans += (2 * start + k - 1) * k // 2 return ans if not k: break start = n + 1 if k: ans += (2 * start + k - 1) * k // 2 return ans
append-k-integers-with-minimal-sum
Sort and count sums between numbers, 71% speed
EvgenySH
0
76
append k integers with minimal sum
2,195
0.25
Medium
30,509
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1825003/Python-Easy-O(n)-solution.
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: nums.sort() start = 1 ans = 0 for num in nums: if k<=0: break while start < num and k>0: dist = min(num-start,k) l = start-1 r = start+dist-1 ans+= (r*(r+1)//2) - (l*(l+1)//2) start = num k-= dist start = num+1 if k > 0: l = start-1 r = start+(k-1) ans+= (r*(r+1)//2) - (l*(l+1)//2) return ans********
append-k-integers-with-minimal-sum
[Python] Easy O(n) solution.
imadilkhan
0
30
append k integers with minimal sum
2,195
0.25
Medium
30,510
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1824546/Different-results-between-''-and-''.-Does-anyone-know-why
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: nums = list(set(nums)) nums.sort() n = len(nums) tarEnd = k p = 0 while p < n and nums[p] <= tarEnd: tarEnd += 1 p += 1 # return (tarEnd+1)*tarEnd // 2 - sum(nums[:p]) # correct 500000000500000001 # return ((tarEnd+1)*tarEnd >> 1) - sum(nums[:p]) # correct 500000000500000001 return int((tarEnd+1)*tarEnd / 2) - sum(nums[:p]) # wrong 500000000500000000
append-k-integers-with-minimal-sum
Different results between '/' and '//'. Does anyone know why?
CxSomebody
0
10
append k integers with minimal sum
2,195
0.25
Medium
30,511
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1823923/Python-or-Arithmetic-Progression-with-Explanation
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: summ = 0 nums.sort() for i in range(len(nums) + 1): # skip computation if we have already fulfilled requirements if k <= 0: break # just skip if the 2 terms are equal if i > 0 and i < len(nums) and nums[i] == nums[i-1]: continue # Find the start if i == 0: start = 1 else: start = nums[i-1] + 1 # find the end if i == len(nums): end = start + k - 1 else: end = min(start + k - 1, nums[i] - 1) # number of terms in arithmatic progression = last - first + 1 n = end - start + 1 # sum of arithmatic progression, given first and last term and number of terms = n * (first + last) / 2 summ += (n * (start + end)) // 2 # decrease k since we have added n terms k -= n return summ
append-k-integers-with-minimal-sum
Python | Arithmetic Progression with Explanation
rbhandu
0
25
append k integers with minimal sum
2,195
0.25
Medium
30,512
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1823793/Could-some-one-tell-why-my-code-is-too-slow
class Solution: def minimalKSum(self, A: List[int], k: int) -> int: ans=0 maxi=max(A) temp=[] A=set(A) for i in range(1,maxi): if i not in A: temp.append(i) if len(temp)> k : return sum(temp[:k]) elif len(temp)==k: return sum(temp) else: ans=sum(temp) diff=k-len(temp) ans+=((maxi+diff)*(maxi+1+diff)/2)-((maxi)*(maxi+1)/2) return(int(ans))
append-k-integers-with-minimal-sum
Could some one tell why my code is too slow ??
amit_upadhyay
0
16
append k integers with minimal sum
2,195
0.25
Medium
30,513
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1823642/Python-or-Sort-before-traverse-or-Greedy-or-Easy-Understanding
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: nums.sort() n = len(nums) result = 0 if nums[0] > k: return self.calSum(0, k+1) if nums[0] != 1: k -= (nums[0] - 1) result += self.calSum(0, nums[0]) for i in range(n-1): numOfCandidates = nums[i+1] - nums[i] -1 if numOfCandidates >= 1: if numOfCandidates >= k: result += self.calSum(nums[i], nums[i] + k +1) k = 0 return result elif numOfCandidates < k: k -= numOfCandidates result += self.calSum(nums[i], nums[i+1]) if k > 0: result += self.calSum(nums[-1], nums[-1] +k+1) return result # calculate the sum between start and end, both exclude def calSum(self, start, end): return int((end + start) / 2 * (end -start -1))
append-k-integers-with-minimal-sum
Python | Sort before traverse | Greedy | Easy Understanding
Mikey98
0
50
append k integers with minimal sum
2,195
0.25
Medium
30,514
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1823644/Python3-simulation
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: mp = {} seen = set() for p, c, left in descriptions: if p not in mp: mp[p] = TreeNode(p) if c not in mp: mp[c] = TreeNode(c) if left: mp[p].left = mp[c] else: mp[p].right = mp[c] seen.add(c) for p, _, _ in descriptions: if p not in seen: return mp[p]
create-binary-tree-from-descriptions
[Python3] simulation
ye15
8
191
create binary tree from descriptions
2,196
0.722
Medium
30,515
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1823678/Python-Solution-using-HashMap-with-Steps
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: root = None table = {} for arr in descriptions: parent = arr[0] child = arr[1] isleft = arr[2] if table.get(parent, None) is None: # If key parent does not exist in table table[parent] = [TreeNode(parent), False] if table.get(child, None) is None: If key child does not exist in table table[child] = [TreeNode(child), False] table[child][1] = True # Since child is going to have a parent in the current iteration, set its has parent property to True if isleft == 1: table[parent][0].left = table[child][0] else: table[parent][0].right = table[child][0] # Now traverse the hashtable and check which node still has no parent for k, v in table.items(): if not v[1]: # Has parent is False, so root is found. root = k break return table[root][0]
create-binary-tree-from-descriptions
Python Solution using HashMap with Steps
anCoderr
5
280
create binary tree from descriptions
2,196
0.722
Medium
30,516
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1966088/Python-Faster-then-100-solution
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: tree = dict() children = set() for parent, child, isLeft in descriptions: if parent not in tree : tree[parent] = TreeNode(parent) if child not in tree : tree[child] = TreeNode(child) if isLeft : tree[parent].left = tree[child] else : tree[parent].right = tree[child] children.add(child) for parent in tree: if parent not in children: return tree[parent]
create-binary-tree-from-descriptions
[ Python ] Faster then 100% solution
crazypuppy
3
119
create binary tree from descriptions
2,196
0.722
Medium
30,517
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/2162621/Python3-Solution-with-using-hashmap-and-hashset
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: val2node = {} child_set = set() parent_set = set() for parent_val, child_val, is_left in descriptions: if child_val not in val2node: val2node[child_val] = TreeNode(child_val) if parent_val not in val2node: val2node[parent_val] = TreeNode(parent_val) if is_left == 1: val2node[parent_val].left = val2node[child_val] else: val2node[parent_val].right = val2node[child_val] child_set.add(child_val) parent_set.discard(child_val) if parent_val not in child_set: parent_set.add(parent_val) else: parent_set.discard(parent_val) return val2node[parent_set.pop()]
create-binary-tree-from-descriptions
[Python3] Solution with using hashmap and hashset
maosipov11
1
26
create binary tree from descriptions
2,196
0.722
Medium
30,518
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1823788/Treat-it-as-a-DAG-%2B-Kahn's-Topo-Algorithm-with-Images-or-Easy-to-understand
class Solution: def construct_graph_and_indegree(self, descriptions): g = {} in_degree = {} for parent, child, is_left in descriptions: if parent not in g: g[parent] = [None, None] if child not in g: g[child] = [None, None] if parent not in in_degree: in_degree[parent] = 0 if child not in in_degree: in_degree[child] = 0 in_degree[child] += 1 # if is_left is true will be in 1st pos, else it will be inserted in right child g[parent][is_left] = child return [g, in_degree] def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: g, in_degree = self.construct_graph_and_indegree(descriptions) root = None for vertex, in_deg in in_degree.items(): if in_deg == 0: root = vertex break root_node = TreeNode(root) q = deque([root_node]) while q: curr_node = q.popleft() if g[curr_node.val][0]: right_node = TreeNode(g[curr_node.val][0]) curr_node.right = right_node q.append(right_node) if g[curr_node.val][1]: left_node = TreeNode(g[curr_node.val][1]) curr_node.left = left_node q.append(left_node) return root_node
create-binary-tree-from-descriptions
Treat it as a DAG + Kahn's Topo Algorithm with Images | Easy to understand
prudentprogrammer
1
25
create binary tree from descriptions
2,196
0.722
Medium
30,519
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/2817762/python
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: isRoot = {} node = {} for p, c, left in descriptions: if p not in isRoot: isRoot[p] = True isRoot[c] = False if p not in node: node[p] = TreeNode(p) if c not in node: node[c] = TreeNode(c) if left: node[p].left = node[c] else: node[p].right = node[c] for val, r in isRoot.items(): if r: root = val break return node[root]
create-binary-tree-from-descriptions
python
xy01
0
1
create binary tree from descriptions
2,196
0.722
Medium
30,520
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/2476696/Using-set-and-hashmap-and-BFS.-Python-solution
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: parents = set() children = set() for i in descriptions: parents.add(i[0]) children.add(i[1]) rootvalue = list(parents-children)[0]#root node parentlist = {} for desc in descriptions: if desc[0] not in parentlist: parentlist[desc[0]] = [[desc[1], desc[2]]] else: parentlist[desc[0]] +=[[desc[1], desc[2]]] root = TreeNode(val=rootvalue) queue = [root] while len(queue)>0: node = queue.pop(0) if node.val in parentlist: children = parentlist[node.val] for i in children: if i[1]==1: node.left = TreeNode(i[0]) queue.append(node.left) else: node.right = TreeNode(i[0]) queue.append(node.right) return root
create-binary-tree-from-descriptions
Using set and hashmap and BFS. Python solution
Arana
0
26
create binary tree from descriptions
2,196
0.722
Medium
30,521
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/2164765/Python3-solution-with-dictionary-and-sets
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: dicts={} set1=set() set2=set() for i in range(len(descriptions)): set1.add(descriptions[i][0]) set2.add(descriptions[i][1]) if descriptions[i][0] not in dicts.keys(): dicts[descriptions[i][0]] = TreeNode(descriptions[i][0]) if descriptions[i][1] not in dicts.keys(): dicts[descriptions[i][1]] = TreeNode(descriptions[i][1]) if descriptions[i][2] == 1: dicts[descriptions[i][0]].left = dicts[descriptions[i][1]] else: dicts[descriptions[i][0]].right = dicts[descriptions[i][1]] asd=set1-set2 return dicts[asd.pop()]
create-binary-tree-from-descriptions
Python3 solution with dictionary and sets
chandkommanaboyina
0
43
create binary tree from descriptions
2,196
0.722
Medium
30,522
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/2068306/Python-80-easy-understanding
class Solution: def createBinaryTree(self, d: List[List[int]]) -> Optional[TreeNode]: h = {n : [-1,-1] for _,n,_ in d} r = None for p, c, l in d: if p not in h: r = p h[p] = [-1,-1] if l == 1: h[p][0] = c else: h[p][1] = c return self.b(h,r) def b(self,h,r): if r == -1: return None root = TreeNode(r) root.left = self.b(h,h[r][0]) root.right = self.b(h,h[r][1]) return root
create-binary-tree-from-descriptions
Python 80% easy understanding
shuchen666
0
60
create binary tree from descriptions
2,196
0.722
Medium
30,523
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/2040600/Python-Solution
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: root = None nodes = {} for parent, child, isLeft in descriptions: if parent not in nodes: nodes[parent] = [TreeNode(parent), None] if child not in nodes: nodes[child] = [TreeNode(child), None] if isLeft == 1: nodes[parent][0].left = nodes[child][0] nodes[child][1] = parent if isLeft == 0: nodes[parent][0].right = nodes[child][0] nodes[child][1] = parent for key in nodes: if nodes[key][1] == None: root = nodes[key][0] return root
create-binary-tree-from-descriptions
Python Solution
b160106
0
25
create binary tree from descriptions
2,196
0.722
Medium
30,524
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1886416/Python-using-hashmap-and-dict%3A%3Asetdefault.-Simple-solution
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: map_val_to_node = {} map_child_to_parent = {} for p_val, c_val, is_left in descriptions: parent_node = map_val_to_node.setdefault(p_val, TreeNode(p_val)) child_node = map_val_to_node.setdefault(c_val, TreeNode(c_val)) map_child_to_parent[child_node] = parent_node if is_left: parent_node.left = child_node else: parent_node.right = child_node root = parent_node while root in map_child_to_parent: root = map_child_to_parent[root] return root
create-binary-tree-from-descriptions
Python using hashmap and dict::setdefault. Simple solution
sEzio
0
48
create binary tree from descriptions
2,196
0.722
Medium
30,525
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1877862/python-simple-O(n)-time-O(n)-space-solution-using-hashmap-and-indegree-array
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: nodes = {} indeg = defaultdict(int) for parent, child, left in descriptions: indeg[child] += 1 if parent not in nodes: nodes[parent] = TreeNode(parent) if child not in nodes: nodes[child] = TreeNode(child) parent_node = nodes[parent] child_node = nodes[child] if left == 1: parent_node.left = child_node else: # left == 0 parent_node.right = child_node root = None for node in nodes: if indeg[node] == 0: root = nodes[node] return root
create-binary-tree-from-descriptions
python simple O(n) time, O(n) space solution using hashmap and indegree array
byuns9334
0
50
create binary tree from descriptions
2,196
0.722
Medium
30,526
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1834279/Create-new-nodes-row-by-row-82-speed
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: left_i, right_i, ref = 0, 1, 2 children, all_nodes = set(), set() nodes = dict() for parent, child, is_left in descriptions: all_nodes.add(parent) all_nodes.add(child) children.add(child) if parent in nodes: nodes[parent][1 - is_left] = child else: nodes[parent] = [0, 0, None] nodes[parent][1 - is_left] = child root_val = (all_nodes - children).pop() root = TreeNode(root_val) nodes[root_val][ref] = root row = {root_val} while row: new_row = set() for v in row: if v in nodes: left_val, right_val, node_ref = nodes[v] if left_val: node_ref.left = TreeNode(left_val) if left_val in nodes: nodes[left_val][ref] = node_ref.left new_row.add(left_val) if right_val: node_ref.right = TreeNode(right_val) if right_val in nodes: nodes[right_val][ref] = node_ref.right new_row.add(right_val) row = new_row return root
create-binary-tree-from-descriptions
Create new nodes row by row, 82% speed
EvgenySH
0
20
create binary tree from descriptions
2,196
0.722
Medium
30,527
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1826980/Python-bfs-solution
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: par,child=set(),set() d=defaultdict(lambda : [0,0]) for n in descriptions: if n[2]==1: d[n[0]][0]=n[1] else: d[n[0]][1]=n[1] par.add(n[0]) child.add(n[1]) main=list(par-child).pop() q=deque() root=TreeNode(main) q.append(root) while q: for i in range(len(q)): node=q.popleft() if d[node.val][0]!=0: node.left=TreeNode(d[node.val][0]) q.append(node.left) if d[node.val][1]!=0: node.right=TreeNode(d[node.val][1]) q.append(node.right) return root
create-binary-tree-from-descriptions
Python bfs solution
amlanbtp
0
32
create binary tree from descriptions
2,196
0.722
Medium
30,528
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1824275/Python-3-or-HashMap-O(N)-or-Explanation
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: d = dict() s = set() for par, child, is_left in descriptions: s.add(child) if par not in d: d[par] = TreeNode(par) if child not in d: d[child] = TreeNode(child) if is_left: d[par].left = d[child] else: d[par].right = d[child] root = set(d.keys()) - s return d[root.pop()]
create-binary-tree-from-descriptions
Python 3 | HashMap, O(N) | Explanation
idontknoooo
0
49
create binary tree from descriptions
2,196
0.722
Medium
30,529
https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1823818/Python3-O(nlogn)-DictionaryHashmap
class Solution: def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: node_dict = defaultdict(TreeNode) ins = defaultdict(int) for p, c, isleft in descriptions: ins[p] = ins[p] ins[c] += 1 node_dict.setdefault(p, TreeNode(p)) node_dict.setdefault(c, TreeNode(c)) if isleft: node_dict[p].left = node_dict[c] else: node_dict[p].right = node_dict[c] return node_dict[min((indegree, node) for node, indegree in ins.items())[1]]
create-binary-tree-from-descriptions
[Python3] O(nlogn) - Dictionary/Hashmap
dwschrute
0
20
create binary tree from descriptions
2,196
0.722
Medium
30,530
https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/1825538/Python-3-Stack-solution
class Solution: def replaceNonCoprimes(self, nums: List[int]) -> List[int]: stack = nums[:1] for j in range(1, len(nums)): cur = nums[j] while stack and math.gcd(stack[-1], cur) > 1: prev = stack.pop() cur = math.lcm(prev, cur) stack.append(cur) return stack
replace-non-coprime-numbers-in-array
[Python 3] Stack solution
chestnut890123
2
125
replace non coprime numbers in array
2,197
0.387
Hard
30,531
https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/1823742/Python3-stack
class Solution: def replaceNonCoprimes(self, nums: List[int]) -> List[int]: stack = [] for x in nums: while stack and gcd(stack[-1], x) > 1: x = lcm(x, stack.pop()) stack.append(x) return stack
replace-non-coprime-numbers-in-array
[Python3] stack
ye15
2
113
replace non coprime numbers in array
2,197
0.387
Hard
30,532
https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/2799444/Python-in-place-(O(1)-space)
class Solution: def replaceNonCoprimes(self, nums: List[int]) -> List[int]: i = 0 while i < len(nums) - 1: gcd = math.gcd(nums[i], nums[i + 1]) if gcd > 1: nums[i] = abs(nums[i] * nums[i + 1]) // gcd # lcm del nums[i + 1] i = max(0, i - 1) else: i += 1 return nums
replace-non-coprime-numbers-in-array
Python in place (O(1) space)
user2341El
0
4
replace non coprime numbers in array
2,197
0.387
Hard
30,533
https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/2742419/Python3-O(N)-time-O(N)-Space-Stack
class Solution: def replaceNonCoprimes(self, nums: List[int]) -> List[int]: stack = [] for idx in range(len(nums)): cur_num = nums[idx] while len(stack) > 0: cur_gcd = self.calculate_gcd(numA=stack[-1], numB=cur_num) if cur_gcd > 1: cur_num = self.calculate_lcm(gcd=cur_gcd, numA=stack[-1], numB=cur_num) stack.pop() else: break stack.append(cur_num) return stack def calculate_gcd(self, numA: int, numB: int) -> int: while numA > 0 and numB > 0: if numA == numB: return numA if numA > numB: numA %= numB else: numB %= numA if numA > 0: return numA return numB def calculate_lcm(self, gcd: int, numA: int, numB: int) -> int: return (numA * numB) // gcd
replace-non-coprime-numbers-in-array
[Python3] O(N) time, O(N) Space, Stack
SoluMilken
0
6
replace non coprime numbers in array
2,197
0.387
Hard
30,534
https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/2013948/Python-Stack-Clean-and-Simple!
class Solution: def replaceNonCoprimes(self, nums): stack = [] for num in nums: while stack and gcd(num,stack[-1]) >= 2: num = lcm(num,stack[-1]) stack.pop() stack.append(num) return stack
replace-non-coprime-numbers-in-array
Python - Stack - Clean and Simple!
domthedeveloper
0
116
replace non coprime numbers in array
2,197
0.387
Hard
30,535
https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/1830696/One-pass-with-stack-97-speed
class Solution: def replaceNonCoprimes(self, nums: List[int]) -> List[int]: stack = [] for n in nums: if not stack: stack.append(n) else: last_gcd = gcd(stack[-1], n) while last_gcd > 1: stack[-1] *= n stack[-1] //= last_gcd if len(stack) > 1: n = stack.pop() last_gcd = gcd(stack[-1], n) else: break else: stack.append(n) return stack
replace-non-coprime-numbers-in-array
One pass with stack, 97% speed
EvgenySH
0
53
replace non coprime numbers in array
2,197
0.387
Hard
30,536
https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/1823799/Python3-One-pass
class Solution: def replaceNonCoprimes(self, nums: List[int]) -> List[int]: if len(nums) == 1: return nums @cache def compute_gcd(x, y) -> int: while y: x, y = y, x % y return x @cache def compute_lcm(x, y) -> int: r = (x*y)//compute_gcd(x,y) return r i, j = 0, 1 while j < len(nums): if compute_gcd(min(nums[i],nums[j]), max(nums[i],nums[j])) != 1: nums[i]=compute_lcm(min(nums[i],nums[j]), max(nums[i],nums[j])) nums.pop(j) if i != 0: i-=1 j-=1 else: i+=1 j+=1 return nums
replace-non-coprime-numbers-in-array
[Python3] One pass
SHaaD94
0
25
replace non coprime numbers in array
2,197
0.387
Hard
30,537
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/2171271/Python-easy-to-understand-oror-Beginner-friendly
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: ind_j = [] for ind, elem in enumerate(nums): if elem == key: ind_j.append(ind) res = [] for i in range(len(nums)): for j in ind_j: if abs(i - j) <= k: res.append(i) break return sorted(res)
find-all-k-distant-indices-in-an-array
✅Python easy to understand || Beginner friendly
Shivam_Raj_Sharma
4
147
find all k distant indices in an array
2,200
0.646
Easy
30,538
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1844619/O(N)-two-pass-solution-in-Python
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: keys = [-math.inf] + [idx for idx, num in enumerate(nums) if num == key] + [math.inf] N = len(nums) res = [] left = 0 for i in range(N): if i - keys[left] <= k or keys[left + 1] - i <= k: res.append(i) if keys[left + 1] == i: left += 1 return res
find-all-k-distant-indices-in-an-array
O(N) two-pass solution in Python
kryuki
3
390
find all k distant indices in an array
2,200
0.646
Easy
30,539
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1886150/python-3-oror-O(n)-O(1)
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: res = [] high = -1 n = len(nums) for i, num in enumerate(nums): if num == key: for j in range(max(high + 1, i - k), min(n, i + k + 1)): res.append(j) high = i + k return res
find-all-k-distant-indices-in-an-array
python 3 || O(n) / O(1)
dereky4
1
102
find all k distant indices in an array
2,200
0.646
Easy
30,540
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1846739/Python3-scan
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: ans = [] ii = 0 for i, x in enumerate(nums): if x == key: lo, hi = max(ii, i-k), min(i+k+1, len(nums)) ans.extend(list(range(lo, hi))) ii = hi return ans
find-all-k-distant-indices-in-an-array
[Python3] scan
ye15
1
27
find all k distant indices in an array
2,200
0.646
Easy
30,541
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1844400/Python-5-lines
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: ans = set() for i, num in enumerate(nums): if num == key: ans.update(range(max(0, i-k), min(i+k+1, len(nums)))) return sorted(list(res))
find-all-k-distant-indices-in-an-array
Python 5 lines
trungnguyen276
1
170
find all k distant indices in an array
2,200
0.646
Easy
30,542
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1844137/Clean-Python-Brute-Force-Solution
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: n, ans = len(nums), [] keys_index = [i for i in range(n) if nums[i] == key] # Holds the indices of all elements equal to key. m = len(keys_index) for i in range(n): for j in range(m): if abs(i - keys_index[j]) <= k: # If the conditions are met then add ith index to the answer array. ans.append(i) break return sorted(ans) # Return sorted ans according to problem
find-all-k-distant-indices-in-an-array
Clean Python Brute Force Solution
anCoderr
1
81
find all k distant indices in an array
2,200
0.646
Easy
30,543
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/2789398/Naive-Approach
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: # k distant index is an index difference that # doesn't exceed k and the value at the index # is the key # it's important to maintain order of nums # you only care about the key at that pos # find locations of the key and iterate through nums # to find values of i (can be flipped w/ j because of abs) # if i - j is less k append i to res and sort it afterwards # time O(n ^ 2) spcae O(n) res = set() indices = [] n = len(nums) for i, num in enumerate(nums): if num == key: indices.append(i) for key_idx in indices: for i in range(n): if abs(i - key_idx) <= k: res.add(i) return sorted(res)
find-all-k-distant-indices-in-an-array
Naive Approach
andrewnerdimo
0
1
find all k distant indices in an array
2,200
0.646
Easy
30,544
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/2385058/Ugly-but-faster-than-97
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: keys = [] l=len(nums) for i in range(l): if nums[i]==key: keys.append(i) j=0 i=0 c=[] l_k=len(keys) while i<l: if abs(i-keys[j]) <= k: c.append(i) if i-keys[j]==k: j+=1 if j==l_k: break i+=1 return c
find-all-k-distant-indices-in-an-array
Ugly but faster than 97%
sunakshi132
0
25
find all k distant indices in an array
2,200
0.646
Easy
30,545
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1975087/Python3-Sliding-window-O(N)-beats-98
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: result = [] n = len(nums) window_start = 0 num_freq = {} # create a window of size k for window_end in range(min(k, n)): right_num = nums[window_end] num_freq[right_num] = num_freq.get(right_num, 0) + 1 # loop on each index and expand the window to the right if possible # and shrink it from the left if necessary for i in range(n): if window_end + 1 < n: window_end += 1 right_num = nums[window_end] num_freq[right_num] = num_freq.get(right_num, 0) + 1 if i - window_start > k: left_num = nums[window_start] num_freq[left_num] -= 1 if num_freq[left_num] == 0: num_freq.pop(left_num) window_start += 1 if key in num_freq: result.append(i) return result
find-all-k-distant-indices-in-an-array
[Python3] Sliding window O(N), beats 98%
mostafaa
0
67
find all k distant indices in an array
2,200
0.646
Easy
30,546
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1944117/Python-dollarolution-(97-Faster)
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: v = [] for i in range(len(nums)): if key == nums[i]: v.append(i) j, i = 0, 0 l = [] while i < len(nums): if abs(v[j]-i) > k: if v[j] < i: j += 1 if j > len(v)-1: break else: i += 1 continue l.append(i) i += 1 return l
find-all-k-distant-indices-in-an-array
Python $olution (97% Faster)
AakRay
0
50
find all k distant indices in an array
2,200
0.646
Easy
30,547
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1860190/Python-easy-solution
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: res = set() n = len(nums) for i in range(n): if nums[i] == key: for x in range(max(i-k, 0), min(i+k, n-1)+1): res.add(x) return list(res)
find-all-k-distant-indices-in-an-array
Python easy solution
byuns9334
0
50
find all k distant indices in an array
2,200
0.646
Easy
30,548
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1854536/5-Lines-Python-Solution-oror-90-Faster-oror-Memory-less-than-98
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: J = [i for i,x in enumerate(nums) if x==key] ; ans=[] for i in range(len(nums)): for j in J: if abs(i-j)<=k: ans.append(i) ; break return ans
find-all-k-distant-indices-in-an-array
5-Lines Python Solution || 90% Faster || Memory less than 98%
Taha-C
0
94
find all k distant indices in an array
2,200
0.646
Easy
30,549
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1854536/5-Lines-Python-Solution-oror-90-Faster-oror-Memory-less-than-98
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: J = [i for i,x in enumerate(nums) if x==key] for i in range(len(nums)): for j in J: if abs(i-j)<=k: yield i ; break
find-all-k-distant-indices-in-an-array
5-Lines Python Solution || 90% Faster || Memory less than 98%
Taha-C
0
94
find all k distant indices in an array
2,200
0.646
Easy
30,550
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1851691/List-extend-no-sorting-94-speed
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: len_nums = len(nums) ans = list() last = 0 for i, n in enumerate(nums): if n == key: ans.extend(range(max(i - k, last), min(i + k + 1, len_nums))) last = i + k + 1 return ans
find-all-k-distant-indices-in-an-array
List extend, no sorting, 94% speed
EvgenySH
0
28
find all k distant indices in an array
2,200
0.646
Easy
30,551
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1848678/Python-100-Time-and-100-Space-or-Proof-Attached
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: res = [] start =end = 0 for i in range(len(nums)): if nums[i] == key: if i - k < end: start = end else: start = i - k if i+k+1 > len(nums): end = len(nums) else: end = i + k + 1 for j in range(start,end): res.append(j) return res
find-all-k-distant-indices-in-an-array
Python 100% Time and 100% Space | Proof Attached
vedank98
0
43
find all k distant indices in an array
2,200
0.646
Easy
30,552
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1847224/Python3-One-Pass-or-6-Lines
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: N, res = len(nums), deque([-1]) for j, num in enumerate(nums): if num == key: res.extend(i for i in range(max(res[-1] + 1, j - k), min(N, j + k + 1))) res.popleft() return res
find-all-k-distant-indices-in-an-array
[Python3] One Pass | 6 Lines
PatrickOweijane
0
33
find all k distant indices in an array
2,200
0.646
Easy
30,553
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1845621/Simple-Python-Solution-or-With-Sorting
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: output = set() for i, n in enumerate(nums): if n == key: # Move right for j in range(i, len(nums)): if abs(i - j) <= k: output.add(j) else: break # Move left for j in range(i - 1, -1, -1): if abs(i - j) <= k: output.add(j) else: break if len(output) == len(nums): break output = list(output) output.sort() return output
find-all-k-distant-indices-in-an-array
✅ Simple Python Solution | With Sorting
chetankalra11
0
12
find all k distant indices in an array
2,200
0.646
Easy
30,554
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1844804/Python-using-range
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: result = [] for i, n in enumerate(nums): if n == key: result.extend(range(max(0 if not result else result[-1]+1, i-k), min(i+k+1, len(nums)))) return result
find-all-k-distant-indices-in-an-array
Python, using range
blue_sky5
0
31
find all k distant indices in an array
2,200
0.646
Easy
30,555
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1844513/O(n)-Python-Simple-Solution-(5-lines)-or-Explained
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: k_distant_indices = set() for num_index, num in enumerate(nums): if num == key or key in nums[max(0,num_index-k):min(len(nums),num_index+k+1)]: k_distant_indices.add(num_index) return k_distant_indices
find-all-k-distant-indices-in-an-array
O(n) Python Simple Solution (5 lines) | Explained
Math_Prandini
0
15
find all k distant indices in an array
2,200
0.646
Easy
30,556
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1844434/python-or-python3
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: ans=[] z=[] for i in range(len(nums)): if nums[i]==key: z.append(i) for i in z: for j in range(i-k,i+k+1): if (-1<j <= len(nums)-1) : ans.append(j) return sorted(list(set(ans)))
find-all-k-distant-indices-in-an-array
python | python3
YaBhiThikHai
0
22
find all k distant indices in an array
2,200
0.646
Easy
30,557
https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/1844191/Short-elegant-Python-one-pass-solution-O(nk)-easy-to-understand-%2B-explanations
class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: # Time: O(nk) which at the worst case could be O(n^2) # Space: O(n) because result will never exceed N values res = set() for index, num in enumerate(nums): if num == key: for i in range(max(0, index - k), min(len(nums), index + k + 1)): res.add(i) return list(res)
find-all-k-distant-indices-in-an-array
💯 Short elegant Python one-pass solution O(nk), easy to understand + explanations
yangshun
0
69
find all k distant indices in an array
2,200
0.646
Easy
30,558
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1844361/Python-elegant-short-and-simple-to-understand-with-explanations
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: # Time: O(max(artifacts, dig)) which is O(N^2) as every position in the grid can be in dig # Space: O(dig) which is O(N^2) result, dig_pos = 0, set(tuple(pos) for pos in dig) for pos in artifacts: if all((x, y) in dig_pos for x in range(pos[0], pos[2] + 1) for y in range(pos[1], pos[3] + 1)): result += 1 return result
count-artifacts-that-can-be-extracted
💯 Python elegant, short and simple to understand with explanations
yangshun
6
352
count artifacts that can be extracted
2,201
0.551
Medium
30,559
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1844361/Python-elegant-short-and-simple-to-understand-with-explanations
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: pos_to_artifacts = {} # (x, y) => artifact unique index artifacts_to_remaining = {} # artifact unique index to remaining spots for artifact to dig up results = 0 # Each artifact is identified by a unique index. for id, artifact in enumerate(artifacts): start, end = (artifact[0], artifact[1]), (artifact[2], artifact[3]) size = 0 for x in range(start[0], end[0] + 1): for y in range(start[1], end[1] + 1): pos_to_artifacts[(x, y)] = id size += 1 artifacts_to_remaining[id] = size for pos in dig: if tuple(pos) not in pos_to_artifacts: continue id = pos_to_artifacts[tuple(pos)] artifacts_to_remaining[id] = artifacts_to_remaining[id] - 1 if artifacts_to_remaining[id] == 0: results += 1 return results
count-artifacts-that-can-be-extracted
💯 Python elegant, short and simple to understand with explanations
yangshun
6
352
count artifacts that can be extracted
2,201
0.551
Medium
30,560
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1844168/Python-Solution-using-Matrix-and-Simple-Counting
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: grid, artifact_id = [[-1] * n for _ in range(n)], 0 # Making the grid for r1, c1, r2, c2 in artifacts: # Populate the grid matrix for r in range(r1, r2 + 1): for c in range(c1, c2 + 1): grid[r][c] = artifact_id artifact_id += 1 for r, c in dig: # Change the grid row, col to -1 by traversing dig array. if grid[r][c] >= 0: grid[r][c] = -1 artifacts_remaining = set() for r in range(n): for c in range(n): if grid[r][c] >= 0: # > 0 means that there still remains an artifact underneath, thus add it to the array artifacts_remaining.add(grid[r][c]) return artifact_id - len(artifacts_remaining)
count-artifacts-that-can-be-extracted
Python Solution using Matrix and Simple Counting
anCoderr
3
198
count artifacts that can be extracted
2,201
0.551
Medium
30,561
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1844345/Python-6-lines
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: dig = set((r, c) for r, c in dig) ans = 0 for r0, c0, r1, c1 in artifacts: if all((r, c) in dig for r in range(r0, r1 + 1) for c in range(c0, c1 + 1)): ans += 1 return ans
count-artifacts-that-can-be-extracted
Python 6 lines
trungnguyen276
2
130
count artifacts that can be extracted
2,201
0.551
Medium
30,562
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1846781/Python3-enumerate
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: dig = {(x, y) for x, y in dig} ans = 0 for i1, j1, i2, j2 in artifacts: for i in range(i1, i2+1): for j in range(j1, j2+1): if (i, j) not in dig: break else: continue break else: ans += 1 return ans
count-artifacts-that-can-be-extracted
[Python3] enumerate
ye15
1
18
count artifacts that can be extracted
2,201
0.551
Medium
30,563
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1846781/Python3-enumerate
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: grid = [[0]*n for _ in range(n)] for i, j in dig: grid[i][j] = 1 prefix = [[0]*(n+1) for _ in range(n+1)] for i in range(n): for j in range(n): prefix[i+1][j+1] = grid[i][j] + prefix[i][j+1] + prefix[i+1][j] - prefix[i][j] ans = 0 for i1, j1, i2, j2 in artifacts: area = prefix[i2+1][j2+1] - prefix[i2+1][j1] - prefix[i1][j2+1] + prefix[i1][j1] if area == (i2-i1+1) * (j2-j1+1): ans += 1 return ans
count-artifacts-that-can-be-extracted
[Python3] enumerate
ye15
1
18
count artifacts that can be extracted
2,201
0.551
Medium
30,564
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/2831348/Python-simple-solution
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: cells = {} artMap = {} for i in range(len(artifacts)): x1, y1, x2, y2 = artifacts[i] cells[i] = (x2 - x1 + 1) * (y2 - y1 + 1) for j in range(x1, x2 + 1): for k in range(y1, y2 + 1): artMap[(j, k)] = i result = 0 for x, y in dig: if (x, y) in artMap: cells[artMap[(x, y)]] -= 1 if cells[artMap[(x, y)]] == 0: result += 1 return result
count-artifacts-that-can-be-extracted
Python, simple solution
swepln
0
1
count artifacts that can be extracted
2,201
0.551
Medium
30,565
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/2014470/Python3-Hashmap-Solution
class Solution: def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int: counter = 0 dicts = {} for a,b,c,d in artifacts: for t in range(a, c+1): for k in range(b, d+1): dicts[(t,k)] = counter counter += 1 for a,b in dig: if (a,b) in dicts: del dicts[(a,b)] remain = set() for value in dicts.values(): remain.add(value) return len(artifacts) - len(remain)
count-artifacts-that-can-be-extracted
Python3 Hashmap Solution
xxHRxx
0
46
count artifacts that can be extracted
2,201
0.551
Medium
30,566
https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1995281/Python-Faster-than-81-of-other-submissions
class Solution: def digArtifacts(self, n: int, artifact: List[List[int]], dig: List[List[int]]) -> int: dig_set = set() for i in dig: dig_set.add(tuple(i)) count = 0 for afact in artifact: flag = True r1,c1,r2,c2 = afact for i in range(r1,r2+1): for j in range(c1,c2+1): if (i,j) not in dig_set: flag = False break if(flag == True): count += 1 return count
count-artifacts-that-can-be-extracted
Python , Faster than 81% of other submissions
pragyagautam02
0
38
count artifacts that can be extracted
2,201
0.551
Medium
30,567
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1844186/Python-3-Find-Maximum-of-first-k-1-elements-or-(k%2B1)th-element-or-Beats-100
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: if len(nums) == 1: if k%2 != 0: return -1 return nums[0] if k == 0: return nums[0] if k == len(nums): return max(nums[:-1]) if k > len(nums): return max(nums) if k == 1: return nums[1] m = max(nums[:k-1]) m = max(m, nums[k]) return m
maximize-the-topmost-element-after-k-moves
[Python 3] Find Maximum of first k-1 elements or (k+1)th element | Beats 100%
hari19041
9
369
maximize the topmost element after k moves
2,202
0.228
Medium
30,568
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1844225/Python-Solution-by-Analyzing-All-Cases.
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: n = len(nums) if k == 0: return nums[0] if k == 1: if n == 1: return -1 else: return nums[1] if n == 1: if k % 2 != 0: return -1 else: return nums[0] if k - n - 1 >= 0: return max(nums) if n == k: return max(nums[0:k - 1]) if n > k: return max(max(nums[0:k - 1]), nums[k])
maximize-the-topmost-element-after-k-moves
Python Solution by Analyzing All Cases.
anCoderr
3
224
maximize the topmost element after k moves
2,202
0.228
Medium
30,569
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1844385/Python-9-lines
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: if len(nums) == 1: return -1 if k % 2 == 1 else nums[0] if k <= 1: return nums[k] if k < len(nums): return max(max(nums[:k-1]), nums[k]) if k < len(nums) + 2: return max(nums[:k-1]) return max(nums)
maximize-the-topmost-element-after-k-moves
Python 9 lines
trungnguyen276
2
72
maximize the topmost element after k moves
2,202
0.228
Medium
30,570
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1846786/Python3-scan-the-array
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: if len(nums) == 1 and k&amp;1: return -1 ans = 0 for i in range(min(k-1, len(nums))): ans = max(ans, nums[i]) if k < len(nums): ans = max(ans, nums[k]) return ans
maximize-the-topmost-element-after-k-moves
[Python3] scan the array
ye15
1
24
maximize the topmost element after k moves
2,202
0.228
Medium
30,571
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1844637/Simulating-all-cases
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: N = len(nums) #edge cases if N == 1 and k % 2 == 1: return -1 if k == 0: return nums[0] if k > N: return max(nums) if k == N: return max(nums[:N - 1]) #non-edge cases return max(nums[:k - 1] + [nums[k]])
maximize-the-topmost-element-after-k-moves
Simulating all cases
kryuki
1
73
maximize the topmost element after k moves
2,202
0.228
Medium
30,572
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1844545/Easy-to-understand-solution-with-comments
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: # made 0 moves so return top most element if k == 0: return nums[0] n = len(nums) # odd k won't work with len = 1 because we will end up empty array state if n == 1: return -1 if k % 2 != 0 else nums[0] # we have a lot of moves so we can do anything to make sure the first element is always the max if k > n: return max(nums) else: # k<=n scenario # make sure you don't exceed the array size upper_bound = min(n, k - 1) # consider first k - 1 elements (aka upper bound) # for kth index, we have the option to use the kth element if it's available (k < len(nums)) # or replace it with the previous seen max in which case we don't consider it return max(nums[:upper_bound] + [nums[k] if k < n else float('-inf')])
maximize-the-topmost-element-after-k-moves
Easy to understand solution with comments
prudentprogrammer
1
27
maximize the topmost element after k moves
2,202
0.228
Medium
30,573
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1844147/Python3-simple-O(n)-solution
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: n = len(nums) if n == 1 and k%2 == 1: return -1 if k == 0: return nums[0] if k == 1: return nums[1] if k > n: return max(nums) if k == n: return max(nums[:k-1]) if k < n: return max(max(nums[:k-1]),nums[k])
maximize-the-topmost-element-after-k-moves
Python3 simple O(n) solution
Yihang--
1
52
maximize the topmost element after k moves
2,202
0.228
Medium
30,574
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/2046477/python-3-oror-greedy-solution-oror-O(n)O(1)
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: n = len(nums) if n == 1: return nums[0] if k % 2 == 0 else -1 return max(nums[i] for i in range(min(n, k + 1)) if i != k - 1)
maximize-the-topmost-element-after-k-moves
python 3 || greedy solution || O(n)/O(1)
dereky4
0
102
maximize the topmost element after k moves
2,202
0.228
Medium
30,575
https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1849371/Python-Very-Easy-Solution-or-Explained
class Solution: def maximumTop(self, nums: List[int], k: int) -> int: if len(nums) <= 1 and k &amp; 1: return -1 # Case 1: triggered end = min(k-1, len(nums)) # If k is greater than len(nums), end = len(nums), because Case 2 is triggered, else case 3 is triggered, we still need to find max till k-1 maxi = max(nums[:end]) if k > 1 else 0 # we calculated the max element based on our end. k > 1 I have given to save from error, beacuse if k <= 1, spliced list will be empty. kplusOne = nums[k % len(nums)] # this is for case 3, finding the k + 1 element, k +1 can give array index out of bound exception, so i did % return max(maxi, kplusOne) # Case 3, we have to decide either we choose to put the max from removed or (k+1) element
maximize-the-topmost-element-after-k-moves
✅ Python Very Easy Solution | Explained
dhananjay79
0
24
maximize the topmost element after k moves
2,202
0.228
Medium
30,576
https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/discuss/1867689/Three-min-costs-to-every-node-97-speed
class Solution: def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int: forward, backward = dict(), dict() for start, end, weight in edges: if start in forward: if end in forward[start]: forward[start][end] = min(weight, forward[start][end]) else: forward[start][end] = weight else: forward[start] = {end: weight} if end in backward: if start in backward[end]: backward[end][start] = min(weight, backward[end][start]) else: backward[end][start] = weight else: backward[end] = {start: weight} def travel(origin: int, relations: dict, costs: list) -> None: level = {origin} costs[origin] = 0 while level: new_level = set() for node in level: if node in relations: for next_node, w in relations[node].items(): if w + costs[node] < costs[next_node]: new_level.add(next_node) costs[next_node] = w + costs[node] level = new_level from_src1 = [inf] * n from_src2 = [inf] * n from_dest = [inf] * n travel(src1, forward, from_src1) travel(src2, forward, from_src2) travel(dest, backward, from_dest) combined_cost = min(sum(tpl) for tpl in zip(from_src1, from_src2, from_dest)) return combined_cost if combined_cost < inf else -1
minimum-weighted-subgraph-with-the-required-paths
Three min costs to every node, 97% speed
EvgenySH
1
144
minimum weighted subgraph with the required paths
2,203
0.357
Hard
30,577
https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/discuss/1846788/Python3-bfs
class Solution: def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int: graph = [[] for _ in range(n)] trans = [[] for _ in range(n)] for u, v, w in edges: graph[u].append((v, w)) trans[v].append((u, w)) def bfs(x, graph): dist = [inf] * n dist[x] = 0 queue = deque([(x, 0)]) while queue: u, w = queue.popleft() if dist[u] == w: for v, ww in graph[u]: if w+ww < dist[v]: dist[v] = w+ww queue.append((v, w+ww)) return dist ds1 = bfs(src1, graph) ds2 = bfs(src2, graph) dd = bfs(dest, trans) ans = min(x+y+z for x, y, z in zip(ds1, ds2, dd)) return ans if ans < inf else -1
minimum-weighted-subgraph-with-the-required-paths
[Python3] bfs
ye15
1
43
minimum weighted subgraph with the required paths
2,203
0.357
Hard
30,578
https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/discuss/1852639/Python-3-BFS-with-comments
class Solution: def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int: g = defaultdict(lambda: defaultdict(lambda: float('inf'))) for u, v, w in edges: g[u][v] = min(g[u][v], w) # first to calculate the optimal solution for distance from src node to other node def helper(start): vis1 = defaultdict(lambda: float('inf'), {start: 0}) q = [(0, start)] while q: s1, node1 = heappop(q) if node1 == dest: continue for nei1 in g[node1]: w1 = g[node1][nei1] if vis1[nei1] <= s1 + w1: continue vis1[nei1] = s1 + w1 heappush(q, (s1 + w1, nei1)) return vis1 vis1, vis2 = helper(src1), helper(src2) # can't reach destination if dest not in vis1 or dest not in vis2: return -1 # distance after collided node def rest(start, vis): q = [(0, start, 0)] # distance, current node, already collide with path from other source node tmp = defaultdict(lambda: float('inf'), {(start, 0): 0}) if start in vis: heappush(q, (vis[start], start, 1)) tmp[start, 1] = vis[start] while q: s2, node2, reached = heappop(q) if node2 == dest and reached: #not only need to reach dest but also need to collide with path from other source node return s2 for nei2 in g[node2]: w2 = g[node2][nei2] #if not collide before then check for collision if not reached and nei2 in vis: if tmp[(nei2, 1)] <= s2 + w2 + vis[dest]: continue tmp[(nei2, 1)] = s2 + w2 + vis[nei2] heappush(q, (s2 + w2 + vis[nei2], nei2, 1)) # otherwise goes for the rest path else: if tmp[(nei2, reached)] <= s2 + w2: continue tmp[(nei2, reached)] = s2 + w2 heappush(q, (s2 + w2, nei2, reached)) return min(rest(src1, vis2), rest(src2, vis1))
minimum-weighted-subgraph-with-the-required-paths
[Python 3] BFS with comments
chestnut890123
0
59
minimum weighted subgraph with the required paths
2,203
0.357
Hard
30,579
https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/discuss/1844288/Python-3-recursive-and-iterative
class Solution: def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int: graph,regra = defaultdict(list),defaultdict(list) for x,y,d in edges: graph[x].append((y,d)) regra[y].append((x,d)) for x in graph.keys(): graph[x].sort(key=lambda p: p[1]) for x in regra.keys(): regra[x].sort(key=lambda p: p[1]) pathfromdest = [float('inf') for _ in range(n)] psrcjeden = [float('inf') for _ in range(n)] psrcdwa = [float('inf') for _ in range(n)] ## def expdes(nod,d): if d < pathfromdest[nod]: pathfromdest[nod] = d for som,da in regra[nod]: expdes(som,d+da) def expsje(nod,d): if d < psrcjeden[nod]: psrcjeden[nod] = d for som,da in graph[nod]: expsje(som,d+da) def expesdwa(nod,d): if d < psrcdwa[nod]: psrcdwa[nod] = d for som,da in graph[nod]: expesdwa(som,d+da) expdes(dest,0) if pathfromdest[src1] == float('inf') or pathfromdest[src2] == float('inf'): return -1 expsje(src1,0) expesdwa(src2,0) ## # q = [dest] # cu = 0 # while cu < len(q): # m = q[cu] # cu += 1 # for som,d in regra[m]: # if pathfromdest[m] + d < pathfromdest[som]: # pathfromdest[som] = pathfromdest[m] + d # q.append(som) # ## # q = [src1] # cu = 0 # while cu < len(q): # m = q[cu] # cu += 1 # for som,d in graph[m]: # if psrcjeden[m] + d < psrcjeden[som]: # psrcjeden[som] = psrcjeden[m] + d # q.append(som) # ## # q = [src2] # cu = 0 # while cu < len(q): # m = q[cu] # cu += 1 # for som,d in graph[m]: # if psrcdwa[m] + d < psrcdwa[som]: # psrcdwa[som] = psrcdwa[m] + d # q.append(som) ## ans = min(pathfromdest[ii]+psrcjeden[ii]+psrcdwa[ii] for ii in range(n)) if ans == float('inf'): return -1 else: return ans
minimum-weighted-subgraph-with-the-required-paths
Python 3 recursive and iterative
nonieno
0
24
minimum weighted subgraph with the required paths
2,203
0.357
Hard
30,580
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1864079/Python-Solution-Using-Counter-oror-Beats-99-oror-O(n)
class Solution: def divideArray(self, nums: List[int]) -> bool: lena = len(nums) count = sum(num//2 for num in Counter(nums).values()) return (lena/2 == count)
divide-array-into-equal-pairs
Python Solution Using Counter || Beats 99% || O(n)
IvanTsukei
6
698
divide array into equal pairs
2,206
0.746
Easy
30,581
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2072603/Python-Easy-1-liner-using-set-operation
class Solution: def divideArray(self, nums: List[int]) -> bool: return not reduce(lambda x,elem: x ^ {elem}, nums, set())
divide-array-into-equal-pairs
Python Easy 1 liner using set operation
constantine786
1
129
divide array into equal pairs
2,206
0.746
Easy
30,582
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2072603/Python-Easy-1-liner-using-set-operation
class Solution: def divideArray(self, nums: List[int]) -> bool: not_a_pair = set() for x in nums: if x not in not_a_pair: not_a_pair.add(x) else: not_a_pair.remove(x) return not not_a_pair
divide-array-into-equal-pairs
Python Easy 1 liner using set operation
constantine786
1
129
divide array into equal pairs
2,206
0.746
Easy
30,583
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2849206/Python-SOLUTION
class Solution: def divideArray(self, nums: List[int]) -> bool: nums.sort() pairs = len(nums) // 2 for i in range(0,len(nums)-1,2): if nums[i] != nums[i+1]: return False return True
divide-array-into-equal-pairs
Python SOLUTION
kruzhilkin
0
1
divide array into equal pairs
2,206
0.746
Easy
30,584
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2847260/Python3-solution
class Solution: def divideArray(self, nums: List[int]) -> bool: for num in set(nums): if nums.count(num) % 2 != 0: return False return True
divide-array-into-equal-pairs
Python3 solution
SupriyaArali
0
1
divide array into equal pairs
2,206
0.746
Easy
30,585
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2846126/Python-Sort-and-Count-O(n-log(n))-time-O(1)-space
class Solution: def divideArray(self, nums: List[int]) -> bool: if len(nums) % 2: return False nums.sort() last, count = nums[0], 1 for i in range(1, len(nums)): if (n := nums[i]) == last: count += 1 elif count % 2 == 0: last, count = n, 1 else: break return count % 2 == 0
divide-array-into-equal-pairs
[Python] Sort and Count - O(n log(n)) time, O(1) space
Lindelt
0
1
divide array into equal pairs
2,206
0.746
Easy
30,586
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2839415/91.7-or-Python-or-LeetCode-or-2206.-Divide-Array-Into-Equal-Pairs-(Easy)
class Solution: def divideArray(self, nums: List[int]) -> bool: count = 0 n = len(nums) // 2 set_ = set() for i in nums: if i in set_: count += 1 set_.remove(i) else: set_.add(i) if count == n: return True return False
divide-array-into-equal-pairs
91.7% | Python | LeetCode | 2206. Divide Array Into Equal Pairs (Easy)
UzbekDasturchisiman
0
2
divide array into equal pairs
2,206
0.746
Easy
30,587
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2839415/91.7-or-Python-or-LeetCode-or-2206.-Divide-Array-Into-Equal-Pairs-(Easy)
class Solution: def divideArray(self, nums: List[int]) -> bool: nums.sort() for i in range(0,len(nums),2): if nums[i] ^ nums[i + 1] != 0: return False return True
divide-array-into-equal-pairs
91.7% | Python | LeetCode | 2206. Divide Array Into Equal Pairs (Easy)
UzbekDasturchisiman
0
2
divide array into equal pairs
2,206
0.746
Easy
30,588
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2785855/Best-Easy-Solution-oror-TC-O(N)-oror-Easy-approach
class Solution: def divideArray(self, nums: List[int]) -> bool: a=Counter(nums) for i,j in a.items(): if j%2!=0: return False return True
divide-array-into-equal-pairs
Best Easy Solution || TC O(N) || Easy approach
Kaustubhmishra
0
3
divide array into equal pairs
2,206
0.746
Easy
30,589
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2785156/python-all
class Solution: def divideArray(self, nums: List[int]) -> bool: return all([v % 2 == 0 for v in Counter(nums).values()])
divide-array-into-equal-pairs
python all
JasonDecode
0
3
divide array into equal pairs
2,206
0.746
Easy
30,590
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2783042/Python-using-dictionary
class Solution: def divideArray(self, nums: List[int]) -> bool: count=0 dic={} for i in range(len(nums)): if nums[i] not in dic: dic[nums[i]]=i elif nums[i] in dic: count+=1 del dic[nums[i]] return count==len(nums)//2
divide-array-into-equal-pairs
Python using dictionary
Bhuvan1234
0
2
divide array into equal pairs
2,206
0.746
Easy
30,591
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2755848/Easy-Dictionary-Solution
class Solution: def divideArray(self, nums: List[int]) -> bool: d={} for i in nums: if i not in d: d[i]=1 else: d[i]+=1 check=0 for k,v in d.items(): if v % 2 == 0: check+=v return True if check == len(nums) else False
divide-array-into-equal-pairs
Easy Dictionary Solution
beingab329
0
4
divide array into equal pairs
2,206
0.746
Easy
30,592
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2711370/Python-solution-clean-code-with-full-comments.
class Solution: def divideArray(self, nums: List[int]) -> bool: return even_value(list_to_dict(nums)) # Convert integer list into a dictionary. def list_to_dict(nums: List[int]): dic = {} for i in nums: if i in dic: dic[i] += 1 else: dic[i] = 1 return dic # Iterate through the dictionarys value and if we get odd value, then we return false # beacuse we cannot divide the array into equal pairs. # For this to work, we need that all the value to be even. def even_value(dic): for key in dic.keys(): if dic[key] % 2 != 0: return False return True # Runtime: 129 ms, faster than 76.08% of Python3 online submissions for Divide Array Into Equal Pairs. # Memory Usage: 14 MB, less than 63.78% of Python3 online submissions for Divide Array Into Equal Pairs. # If you like my work and found it helpful, then I'll appreciate a like. Thanks!
divide-array-into-equal-pairs
Python solution, clean code with full comments.
375d
0
16
divide array into equal pairs
2,206
0.746
Easy
30,593
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2654819/Easy-and-faster-solution-using-Counter
class Solution: def divideArray(self, nums: List[int]) -> bool: c=Counter(nums) for i in c: if(c[i]%2!=0): return False return True
divide-array-into-equal-pairs
Easy and faster solution using Counter
Raghunath_Reddy
0
4
divide array into equal pairs
2,206
0.746
Easy
30,594
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2519054/Simple-Python-solution-using-hashmap
class Solution: def divideArray(self, nums: List[int]) -> bool: n = len(nums) if n % 2 == 1: return False dic = collections.Counter(nums) for k,v in dic.items(): if v % 2 == 1: return False return True
divide-array-into-equal-pairs
Simple Python solution using hashmap
aruj900
0
19
divide array into equal pairs
2,206
0.746
Easy
30,595
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2478679/Python3-Simple-using-dicts-explanation-no-imports-memory-efficient
class Solution: def divideArray(self, nums: List[int]) -> bool: # Let's start by creating a python dictionary to count the occurances of each number in the list n_dict = {} for n in nums: n_dict[n] = n_dict.get(n, 0) + 1 #print(n_dict) # Uncomment this to see the dict. It has the form {(key: value), } or in our case {(number: occurances), ...} # Now we can loop through the dictionary, and if any of the occurance counts are not divisible by 2, then we know the answer is false # We can determine if something is divisible by 2 by using the modulus operator which returns the remainder after a division (4 % 2 = 0, 5 % 2 = 1) for n in n_dict: if n_dict[n] % 2 != 0: return False # If we didn't find any occurances not divisable by 2, we know the answer must be true return True
divide-array-into-equal-pairs
[Python3] Simple using dicts - explanation - no imports - memory efficient
connorthecrowe
0
34
divide array into equal pairs
2,206
0.746
Easy
30,596
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2471290/Python-solution-faster-than-99.05-using-set-and-collections
class Solution: def divideArray(self, nums: List[int]) -> bool: set_nums = set(nums) dict_nums = collections.Counter(nums) count_even_val = 0 for k, v in dict_nums.items(): if v % 2 == 0: count_even_val += 1 if count_even_val == len(set_nums): return True return False
divide-array-into-equal-pairs
Python solution faster than 99.05% using set and collections
samanehghafouri
0
31
divide array into equal pairs
2,206
0.746
Easy
30,597
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2149454/One-liner
class Solution: def divideArray(self, nums: List[int]) -> bool: return all(v % 2 == 0 for _, v in Counter(nums).items())
divide-array-into-equal-pairs
One liner
dima62
0
30
divide array into equal pairs
2,206
0.746
Easy
30,598
https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/2092117/PYTHON-or-Super-simple-python-solution-or-HashMap
class Solution: def divideArray(self, nums: List[int]) -> bool: numMap = {} for i in nums: numMap[i] = 1 + numMap.get(i, 0) for i in numMap: if numMap[i] % 2 != 0: return False return True
divide-array-into-equal-pairs
PYTHON | Super simple python solution | HashMap
shreeruparel
0
58
divide array into equal pairs
2,206
0.746
Easy
30,599