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/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2048606/Python-Simple-Python-Solution-Using-BFS-and-Recursion | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
self.ans = TreeNode()
def PrintTree(node1,node2,target):
if node1 is not None:
if node1.left is not None and node2.left is not None:
PrintTree(node1.left,node2.left,target)
if node1.val == target.val and node2.val == target.val:
self.ans = node2
if node1.right is not None and node2.right is not None:
PrintTree(node1.right,node2.right,target)
PrintTree(original, cloned,target)
return self.ans | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | [ Python ] ✅✅ Simple Python Solution Using BFS and Recursion✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 46 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,700 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2048350/Python-Simple-BFS | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
queue = collections.deque()
queue.append(cloned)
while queue:
for i in range(len(queue)):
node = queue.popleft()
if node:
if node.val == target.val:
return node
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python - Simple BFS | supersid1695 | 0 | 20 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,701 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2047983/Python-2-Solutions.-With-and-and-Without-duplicate-values | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
q = deque()
q.append(cloned)
while q:
current_node = q.popleft()
if current_node.val == target.val:
return current_node
if current_node.left:
q.append(current_node.left)
if current_node.right:
q.append(current_node.right) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | [Python] - 2 Solutions. With and and Without duplicate values | yours-truly-rshi | 0 | 20 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,702 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2047983/Python-2-Solutions.-With-and-and-Without-duplicate-values | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
q1 = deque()
q1.append(original)
q2 = deque()
q2.append(cloned)
while q1:
current_node = q1.popleft()
cloned_node = q2.popleft()
if current_node == target:
return cloned_node
if current_node.left:
q1.append(current_node.left)
q2.append(cloned_node.left)
if current_node.right:
q1.append(current_node.right)
q2.append(cloned_node.right) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | [Python] - 2 Solutions. With and and Without duplicate values | yours-truly-rshi | 0 | 20 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,703 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2047318/5-line-Python-O(n) | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if original == None:
return None
if original == target:
return cloned
return self.getTargetCopy(original.left, cloned.left, target) or self.getTargetCopy(original.right, cloned.right, target) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 5 line Python O(n) | mrabhishek1379 | 0 | 18 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,704 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2047223/Breaking-the-problem-into-smaller-subproblem-intuition-(Recursion) | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if (not original):
return None
if (original == target):
return cloned
lst = self.getTargetCopy(original.left, cloned.left, target)
rst = self.getTargetCopy(original.right, cloned.right, target)
if (not lst):
return rst
else:
return lst | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Breaking the problem into smaller subproblem intuition (Recursion) | luffySenpai | 0 | 6 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,705 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046888/Python3-O(n)-time-complexity-or-O(n)-space-complexity | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
stack = [(original, cloned)]
while stack:
x, y = stack.pop()
if x == target: return y
if x:
stack.append((x.left, y.left))
stack.append((x.right, y.right)) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | [Python3] O(n) time complexity | O(n) space complexity | onegentleman | 0 | 9 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,706 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046190/Python-DFS | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
def dfs(node1, node2):
if not node1 or self.stop:
return
if node1 is target:
self.stop = True
self.cloned_target = node2
return
dfs(node1.left, node2.left)
dfs(node1.right, node2.right)
self.stop = False
dfs(original, cloned)
return self.cloned_target | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python, DFS | blue_sky5 | 0 | 75 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,707 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046148/Python-or-Commented-or-Recursion-or-O(n) | # Recursive Solution
# Time: O(n), Visits each node at most one time.
# Space: O(1), No extra space, but some additional memory will be used for the recursive stack.
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not original: return None # Current node is None, thus return None.
if original == target: return cloned # Found target node, return the clone's reference to node.
leftSearch = self.getTargetCopy(original.left, cloned.left, target) # Recursivly iterate through left children to find target node.
rightSearch = self.getTargetCopy(original.right, cloned.right, target) # Recursivly iterate through right children to find target node.
return leftSearch or rightSearch or None # Return clone reference if found in leftSearch or rightSearch, otherwise return None. | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python | Commented | Recursion | O(n) | bensmith0 | 0 | 23 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,708 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/1418093/Python3-recursive-dfs-solution | class Solution:
def is_equal(self, cloned, target):
if cloned == None:
return cloned == target
if cloned.val == target.val:
if self.is_equal(cloned.left, target.left):
if self.is_equal(cloned.right, target.right):
return True
return False
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if cloned == None:
return None
if target.val == cloned.val:
if self.is_equal(cloned, target):
return cloned
l = self.getTargetCopy(original, cloned.left, target)
r = self.getTargetCopy(original, cloned.right, target)
if l == None:
return r
return l | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | [Python3] recursive dfs solution | maosipov11 | 0 | 36 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,709 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/998872/Find-Corresponding-Node-or-Python3-or-Recursion-(explained) | class Solution:
# Will solve for followup straight off the bat
# Since we're looking for same reference in original tree,
# we will traverse both trees at the same time
# until we find the target TreeNode in the original tree.
# We will then return the corresponding TreeNode at that point
# in the cloned tree.
# This will work even in a tree of duplicates because instead
# of checking whether the value of a node is equal to the target,
# we are checking if the target node is equal to the current node
# in the original tree.
# TC: O(N) - Worst case target is last visited node in tree
# SC: O(N) - Worst case tree is completely skewed and we have
# to visit last node, meaning there are N recursive calls
def getTargetCopy(self, original, cloned, target):
# base case - root is target
# return wherever we are in the cloned tree
if original == target:
return cloned
# null case if branch doesn't have target
if not original: return None
# Otherwise, traverse tree and return
# whichever subcall contains the target
return self.getTargetCopy(original.left, cloned.left, target) or \
self.getTargetCopy(original.right, cloned.right, target) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Find Corresponding Node | Python3 | Recursion (explained) | ctopher | 0 | 44 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,710 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/998174/Python-Simple-3-line-DFS-(preorder)-recursive-solution | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not original: return None
if original == target: return cloned
else: return self.getTargetCopy(original.left,cloned.left,target) or \
self.getTargetCopy(original.right,cloned.right,target) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | [Python] Simple 3-line DFS (preorder) recursive solution | KevinZzz666 | 0 | 62 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,711 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/998130/Elegant-and-pythonic-DFS-solution | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
def dfs(node):
if node:
yield from dfs(node.left)
yield node
yield from dfs(node.right)
for node, node_cloned in zip(dfs(original), dfs(cloned)):
if node == target:
return node_cloned | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Elegant & pythonic DFS solution | aleksj | 0 | 93 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,712 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/755030/Super-Short-Python3-Beats-90 | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
# Traverse both trees simultaneously
def traverse(real_node, cloned_node):
if not real_node: return None
# Found the node? Return the cloned version
if real_node == target: return cloned_node
# Will return the node since one call will return None and the other will return TreeNode
return traverse(real_node.left, cloned_node.left) or traverse(real_node.right, cloned_node.right)
return traverse(original, cloned) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Super Short Python3 Beats 90% | jacksilver | 0 | 131 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,713 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/746801/Python3-Simplest-Solution | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
found = None
if original.val == target.val:
found = cloned
if found is None and original.left is not None:
found = self.getTargetCopy(original.left, cloned.left, target)
if found is None and original.right is not None:
found = self.getTargetCopy(original.right, cloned.right, target)
# target must be found in original, so the "found" must not be None.
return found | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python3 Simplest Solution | user3104p | 0 | 97 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,714 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/589727/Record-action(s)-from-original-tree-and-replay-them-on-cloned-tree | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
queue = [([], original)]
while queue:
actions, node = queue.pop(0)
if id(node) == id(target):
cloned_target = cloned
for a in actions:
if a == 1:
cloned_target = cloned_target.right
else:
cloned_target = cloned_target.left
return cloned_target
if node.left:
actions_copy = []
actions_copy.extend(actions)
actions_copy.append(0) # Move left
queue.append((actions_copy, node.left))
if node.right:
actions_copy = []
actions_copy.extend(actions)
actions_copy.append(1) # Move right
queue.append((actions_copy, node.right))
return None | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Record action(s) from original tree and replay them on cloned tree | puremonkey2001 | 0 | 27 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,715 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/539748/Python3-store-row-min-and-column-max | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
rmin = [min(x) for x in matrix]
cmax = [max(x) for x in zip(*matrix)]
return [matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[0])) if rmin[i] == cmax[j]] | lucky-numbers-in-a-matrix | [Python3] store row min & column max | ye15 | 9 | 1,500 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,716 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/539748/Python3-store-row-min-and-column-max | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
return set(map(min, matrix)) & set(map(max, zip(*matrix))) | lucky-numbers-in-a-matrix | [Python3] store row min & column max | ye15 | 9 | 1,500 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,717 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1948134/easy-Python-code | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
m,n = [],[]
output = []
for i in matrix:
m.append(min(i))
for i in range(len(matrix[0])):
c = []
for j in range(len(matrix)):
c.append(matrix[j][i])
n.append(max(c))
for i in m:
if i in n:
output.append(i)
return output | lucky-numbers-in-a-matrix | easy Python code | dakash682 | 5 | 250 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,718 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1660261/Python-Easy-Solution-or-Simple-Approach | class Solution:
def luckyNumbers(self, mat: List[List[int]]) -> List[int]:
return list({min(row) for row in mat} & {max(col) for col in zip(*mat)}) | lucky-numbers-in-a-matrix | Python Easy Solution | Simple Approach ✔ | leet_satyam | 5 | 354 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,719 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2503871/Python-simple-90-solution | class Solution:
def luckyNumbers (self, m: List[List[int]]) -> List[int]:
min_r = [min(x) for x in m]
max_c = []
for i in range(len(m[0])):
tmp = []
for j in range(len(m)):
tmp.append(m[j][i])
max_c.append(max(tmp))
return set(min_r)&set(max_c) | lucky-numbers-in-a-matrix | Python simple 90% solution | StikS32 | 1 | 94 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,720 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/547533/Straightforward-Python-Solution | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
hmap = {}
lmap = {}
# Parsing through matrix, row-wise and finding minimum element in each row
for i , r in list(enumerate(matrix)):
min_row = min(r)
hmap[min_row] = (i, r.index(min_row))
# Parsing through the matrix column-wise, and find the maximum element in each column
for i in range(len(matrix[i])):
max_ele = 0
for j in range(len(matrix)):
res = matrix[j][i]
max_ele = max(max_ele, matrix[j][i])
lmap[max_ele] = (i,j)
# Checking for intersection of the 2 hashmaps, to see if we have common elements
res = [v for v in list(hmap.keys()) if v in list(lmap.keys())]
return res | lucky-numbers-in-a-matrix | Straightforward Python Solution | cppygod | 1 | 425 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,721 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2846385/python3-solution | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
min_row = set()
for i in matrix:
min_row.add(min(i))
min_col = set()
for i in range(len(matrix[0])):
a = 0
for j in range(len(matrix)):
a = max(matrix[j][i],a)
min_col.add(a)
res = list(min_col & min_row)
return res | lucky-numbers-in-a-matrix | python3 solution | Cosmodude | 0 | 1 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,722 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2799659/Python-O(M*N)-Solution-easy-and-straight-forward. | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
minList = []
maxList = []
for i in range(0,len(matrix)):
minimum = math.inf
for j in range(0,len(matrix[i])):
if matrix[i][j] < minimum:
minimum = matrix[i][j]
minList.append(minimum)
for i in range(0,len(matrix[0])):
maximum = -math.inf
for j in range(0,len(matrix)):
if matrix[j][i] > maximum:
maximum = matrix[j][i]
maxList.append(maximum)
output = []
for i in minList:
for j in maxList:
if i==j:
output.append(i)
return output | lucky-numbers-in-a-matrix | Python O(M*N) Solution easy and straight forward. | tanaydwivedi095 | 0 | 4 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,723 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2779362/Better-than-98-percent-all-max-and-min-in-single-scan-then-sorting-and-merging-the-results | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
rowmax = []
colmin = [0]*len(matrix[0])
for row in matrix:
curRowMax = 5000000
i = 0
for elem in row:
if elem < curRowMax:
curRowMax = elem
if elem > colmin[i]:
colmin[i] = elem
i +=1
rowmax.append(curRowMax)
print(rowmax)
colmin.sort()
rowmax.sort()
colindex = 0
rowindex = 0
res = []
while(rowindex < len(matrix) and colindex < len(matrix[0])):
if colmin[colindex] == rowmax[rowindex]:
res.append(colmin[colindex] )
rowindex += 1
colindex += 1
continue
if colmin[colindex] > rowmax[rowindex]:
rowindex += 1
else:
colindex += 1
return res | lucky-numbers-in-a-matrix | Better than 98 percent, all max and min in single scan then sorting and merging the results | peterspamftw | 0 | 4 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,724 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2773515/python | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
r=[]
t=[]
res=[]
for i in range(len(matrix[0])):
for j in range(len(matrix)):
t+=[matrix[j][i]]
r+=[max(t)]
t=[]
print(r)
for i in range(len(matrix)):
if min(matrix[i]) in r:
res+=[min(matrix[i])]
return res | lucky-numbers-in-a-matrix | python | sarvajnya_18 | 0 | 11 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,725 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2742475/Easy-Python3-Solution-using-Sets | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
max_list = set()
min_list = set()
temp = []
l = len(matrix[0])
for i in range(0, l):
for j in range(0,len(matrix)):
temp.append(matrix[j][i])
max_list.add(max(temp))
temp = []
min_list = {min(matrix[i]) for i in range(0, len(matrix))}
return list(max_list.intersection(min_list)) | lucky-numbers-in-a-matrix | Easy Python3 Solution using Sets | jacobsimonareickal | 0 | 9 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,726 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2733164/Easiest-and-98.59-faster-solution-using-python | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
maxCol, minRow = [], []
r, c = len(matrix), len(matrix[0])
# first search for all min val in rows wise
minRow = [min(i) for i in matrix]
# second search for all max val in cols wise
for i in range(c):
tmp = []
for j in range(r):
tmp.append(matrix[j][i])
maxCol.append(max(tmp))
# last return those val present in both array
return [i for i in maxCol if i in minRow] | lucky-numbers-in-a-matrix | Easiest and 98.59 % faster solution using python | ankurbhambri | 0 | 10 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,727 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2691740/Clear-and-Intuitive-Answer. | class Solution(object):
def luckyNumbers (self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
res = []
values = set()
for arr in matrix:
values.add(min(arr))
for col in range(len(matrix[0])):
max_val = 0
for row in range(len(matrix)):
max_val = max(max_val, matrix[row][col])
if max_val in values:
res.append(max_val)
return res | lucky-numbers-in-a-matrix | Clear and Intuitive Answer. | EmmanEsp | 0 | 4 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,728 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2630367/Python-or-Straight-forward-Solution-or-Faster-than-99.8 | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
min_row = [min(row) for row in matrix]
max_col = [max(col) for col in zip(*matrix)] # zip(*matrix) transposes the matrix
return [val for val in min_row if val in max_col] | lucky-numbers-in-a-matrix | Python | Straight-forward Solution | Faster than 99.8% | ahmadheshamzaki | 0 | 13 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,729 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2630367/Python-or-Straight-forward-Solution-or-Faster-than-99.8 | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
return [val for val in [min(row) for row in matrix] if val in [max(col) for col in zip(*matrix)]] | lucky-numbers-in-a-matrix | Python | Straight-forward Solution | Faster than 99.8% | ahmadheshamzaki | 0 | 13 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,730 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2630367/Python-or-Straight-forward-Solution-or-Faster-than-99.8 | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
min_row = {min(row) for row in matrix}
max_col = {max(col) for col in zip(*matrix)}
return min_row & max_col # Get set intersection | lucky-numbers-in-a-matrix | Python | Straight-forward Solution | Faster than 99.8% | ahmadheshamzaki | 0 | 13 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,731 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2589563/Python3-oror-faster-than-95-oror-caching-of-max-column-vals | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
m = len(matrix)
n = len(matrix[0])
res = []
col_max = {}
for row_ind in range(m):
row = matrix[row_ind]
col_ind = min(range(n), key=row.__getitem__)
row_min = row[col_ind]
if col_ind not in col_max:
col_max[col_ind] = max([matrix[row_i][col_ind] for row_i in range(m)])
if col_max[col_ind] == row_min:
res.append(row_min)
continue
return res | lucky-numbers-in-a-matrix | Python3 || faster than 95% || caching of max column vals | sespivak | 0 | 20 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,732 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2564724/easy-to-understand-python-solution-using-sets-and-intersection | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
max_columns = set()
min_rows = set()
for li in matrix:
min_rows.add(min(li))
A = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))]
for r in range(len(matrix)):
for c in range(len(matrix[0])):
A[c][r] = matrix[r][c]
for li in A:
max_columns.add(max(li))
intersect = min_rows.intersection(max_columns)
if len(intersect) == 0:
return []
return list(intersect) | lucky-numbers-in-a-matrix | easy to understand python solution using sets and intersection | samanehghafouri | 0 | 11 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,733 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2391783/ugly-python-code | class Solution:
# def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
# rows = set(min(row) for row in matrix)
# cols = set(max(col) for col in zip(*matrix))
# return list(rows & cols)
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
m=len(matrix)
n=len(matrix[0])
a2 =[]
for i in range(n):
a2.append(0)
a1=set()
for i in range(m):
a1.add(min(matrix[i]))
for i in range(m):
for j in range(n):
a2[j] = max(a2[j],matrix[i][j])
ans=[]
for i in a2:
if i in a1:
ans.append(i)
return ans | lucky-numbers-in-a-matrix | ugly python code | sunakshi132 | 0 | 33 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,734 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/2281129/Two-Python-Brute-Force-solutions.......If-you-can-help-optimise-further-would-be-appreciated. | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
matrix.sort()
d={}
for i in range(0,len(matrix)):
a=min(matrix[i])
b=matrix[i].index(a)
d[b]=a
result=[]
j=0
for j in d.keys():
count=0
for i in range(0,len(matrix)):
if matrix[i][j]>d[j]:
break
else:
count+=1
if count==len(matrix):
result.append(d[j])
return result | lucky-numbers-in-a-matrix | Two Python Brute Force solutions.......If you can help optimise further would be appreciated. | guneet100 | 0 | 48 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,735 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1921865/Python-easy-solution-using-zip-function-to-transpose | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
transpose = list(zip(*matrix))
res = []
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if min(matrix[i]) == matrix[i][j] and max(transpose[j]) == matrix[i][j]:
res.append(matrix[i][j])
return res | lucky-numbers-in-a-matrix | Python easy solution using zip function to transpose | alishak1999 | 0 | 71 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,736 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1915041/Python-Set-Intersection-Explained-Via-Comments | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
mn_row, mx_col = set(), set()
# Get min in each row
for i in matrix:
mn_row.add(min(i))
# Get max in each column
for i in list(zip(*matrix)):
mx_col.add(max(i))
# The intersection is the only element that show in both row and column
return list(mn_row.intersection(mx_col)) | lucky-numbers-in-a-matrix | Python Set Intersection, Explained Via Comments | Hejita | 0 | 58 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,737 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1810033/5-Lines-Python-Solution-oror-97-Faster-oror-Memory-less-than-86 | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
t_matrix, ans = list(zip(*matrix)), []
for i in range(len(matrix)): ans.append(min(matrix[i]))
for i in range(len(t_matrix)):
if max(t_matrix[i]) in ans: return [max(t_matrix[i])]
return [] | lucky-numbers-in-a-matrix | 5-Lines Python Solution || 97% Faster || Memory less than 86% | Taha-C | 0 | 128 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,738 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1706263/Interview-friendly-followup-to-One-pass-O(mn)-solution | class Solution:
def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
row_min = {}
col_min = {}
for row in range(len(matrix)):
for col in range(len(matrix[0])):
min_row_val = matrix[row][row_min.setdefault(row, col)]
max_col_val = matrix[col_min.setdefault(col, row)][col]
if matrix[row][col] < min_row_val:
row_min[row] = col
if matrix[row][col] > max_col_val:
col_min[col] = row
result_arr = []
for row, col in row_min.items():
if col_min[col] == row:
result_arr.append(matrix[row][col])
return result_arr | lucky-numbers-in-a-matrix | Interview friendly followup to One pass, O(mn) solution | snagsbybalin | 0 | 53 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,739 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1706207/One-pass-O(m-%2B-n)-space-O(mn)-time-without-set()dict()-in-python3 | class Solution:
def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
# Get row, col tuple of minimum value of a row in this array. Row number is implicit in array index, save column as value
row_min_cols = [0] * len(matrix)
# Get row, col tuple of maximum value of a col in this array. Column number is implicit in array index, save row as value
col_min_rows = [0] * len(matrix[0])
# Find minimum and maximum
for row in range(len(matrix)):
for col in range(len(matrix[0])):
row_min_val = matrix[row][row_min_cols[row]]
col_min_val = matrix[col_min_rows[col]][col]
if matrix[row][col] < row_min_val:
row_min_cols[row] = col
if matrix[row][col] > col_min_val:
col_min_rows[col] = row
result_arr = []
# If match found in both arrays, return
for idx, val in enumerate(row_min_cols):
if idx == col_min_rows[val]:
result_arr.append(matrix[idx][val])
return result_arr | lucky-numbers-in-a-matrix | One pass, O(m + n) space, O(mn) time without set()/dict() in python3 | snagsbybalin | 0 | 33 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,740 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1543616/Python-3-One-pass-O(m*n)-solution-step-wise | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
numRows = len(matrix)
numCols = len(matrix[0])
mins = [math.inf for i in range(numRows)]
maxes = [0 for i in range(numCols)]
for i in range(numRows):
for j in range(numCols):
if matrix[i][j] < mins[i]:
mins[i] = matrix[i][j]
if matrix[i][j] > maxes[j]:
maxes[j] = matrix[i][j]
return list(set(mins).intersection(maxes)) | lucky-numbers-in-a-matrix | [Python 3] One pass O(m*n) solution - step wise | Kartikeya1012 | 0 | 167 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,741 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1272730/python-Solution-beats-~97 | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
n=len(matrix[0])
m=len(matrix)
minRow=[]
maxCol=[]
for i in range(m):
minRow.append(min(matrix[i]))
for j in range(n):
x=0
for i in range(m):
if matrix[i][j]>x:
x=matrix[i][j]
maxCol.append(x)
for i in maxCol:
if i in minRow:
return [i] | lucky-numbers-in-a-matrix | python Solution beats ~97% | prakharjagnani | 0 | 122 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,742 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1160072/Python-pythonic-and-fast | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
min_in_row = [min(x) for x in matrix]
for index in range(len(matrix[0])):
column_max = max([x[index] for x in matrix])
if column_max in min_in_row:
return [column_max] | lucky-numbers-in-a-matrix | [Python] pythonic and fast | cruim | 0 | 77 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,743 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1054635/or-Python-3-or-Easy-to-understand | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
result = [min(i) for i in matrix]
temp, answer = [], []
for i in range(len(matrix[0])):
for j in range(len(matrix)):
temp.append(matrix[j][i])
if max(temp) in result:
answer.append(max(temp))
temp = []
return answer | lucky-numbers-in-a-matrix | | Python 3 | Easy to understand | bruadarach | 0 | 159 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,744 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1045092/python-pass-through-matrix-once-120ms | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
max_col = {}
min_rows = []
for row in matrix:
min_rows.append(min(row))
for index, x in enumerate(row):
try:
if max_col[index] < x:
max_col[index] = x
except KeyError:
max_col[index] = x
return set(min_rows).intersection(max_col.values()) | lucky-numbers-in-a-matrix | python pass through matrix once 120ms | peatear-anthony | 0 | 86 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,745 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/1037054/Python3-simple-solution | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
l1 = []
for i in matrix:
l1.append(min(i))
l2 = []
for i in zip(*matrix):
l2.append(max(i))
return set(l1).intersection(set(l2)) | lucky-numbers-in-a-matrix | Python3 simple solution | EklavyaJoshi | 0 | 62 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,746 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/946278/Python-Simple-Solution | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
mi={min(r) for r in matrix}
ma={max(c) for c in zip(*matrix)}
return mi & ma | lucky-numbers-in-a-matrix | Python Simple Solution | lokeshsenthilkumar | 0 | 281 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,747 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/783861/Python3-solution-easy-to-understand-92.00-faster! | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
newl = []
x = 0
for i in range(len(matrix[0])):
l = []
for j in range(len(matrix)):
l.append(matrix[j][x])
maxi = max(l)
pos = l.index(maxi)
mini = min(matrix[pos])
if maxi == mini:
newl.append(maxi)
x += 1
return newl | lucky-numbers-in-a-matrix | Python3 solution easy to understand; 92.00% faster! | rocketrikky | 0 | 90 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,748 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/565362/Python-Solution-%2B-Explanation | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
result = [min(array) for array in matrix][::-1]
previous = 0
for array in matrix:
previous = min(array)
index = array.index(min(array) if min(array) > previous)
list = [array[index] for array in matrix]
if max(list) == max(result):
return [max(result)]
else:
return [] | lucky-numbers-in-a-matrix | Python Solution + Explanation | aniulis | 0 | 105 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,749 |
https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/539974/Python-Using-Min-with-commentary | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
row_count = len(matrix)
column_count = len(matrix[0])
result = []
for row in matrix:
# Identify min value in row and get it's column index
min_value = min(row)
min_index = row.index(min_value)
column_index = 0
column_max = 0
# Using the column check for max of that column
while column_index < row_count:
if matrix[column_index][min_index] > column_max:
column_max = matrix[column_index][min_index]
column_index += 1
# If row min equals column max then add it to our results list
if column_max == min_value:
result.append(min_value)
return result | lucky-numbers-in-a-matrix | [Python] - Using Min with commentary | dentedghost | 0 | 126 | lucky numbers in a matrix | 1,380 | 0.705 | Easy | 20,750 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/539780/Python3-collect-values-and-reconstruct-bst-recursively | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def dfs(node):
"""inorder depth-first traverse bst"""
if not node: return
dfs(node.left)
value.append(node.val)
dfs(node.right)
value = [] #collect values
dfs(root)
def tree(lo, hi):
if lo > hi: return None
mid = (lo + hi)//2
ans = TreeNode(value[mid])
ans.left = tree(lo, mid-1)
ans.right = tree(mid+1, hi)
return ans
return tree(0, len(value)-1) | balance-a-binary-search-tree | [Python3] collect values & reconstruct bst recursively | ye15 | 6 | 363 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,751 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/1273243/Quite-simple-Solution-'n-85-Accuracy-python-and-Good-structured-easy-to-understand | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def inorder(root):
if root is None: return None
inorder(root.left); lst.append(root); inorder(root.right)
lst = []
inorder(root)
def bst(arr):
if len(arr) == 0:return
mid = len(arr)//2; root = arr[mid]
root.left = bst(arr[:mid]); root.right = bst(arr[mid+1:])
return root
return bst(lst) | balance-a-binary-search-tree | Quite simple Solution 'n 85% Accuracy [python] and Good structured easy to understand | rstudy211 | 5 | 218 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,752 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/1552927/Well-Coded-oror-For-Beginners-oror-Easy-Approach | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
arr = []
def inorder(root):
if root is None:
return
inorder(root.left)
arr.append(root.val)
inorder(root.right)
def mbst(i,j,arr):
if i>j:
return None
if i==j:
return TreeNode(arr[i])
m = (i+j)//2
root = TreeNode(arr[m])
root.left = mbst(i,m-1,arr)
root.right= mbst(m+1,j,arr)
return root
inorder(root)
i, j = 0, len(arr)-1
return mbst(i,j,arr | balance-a-binary-search-tree | 📌📌 Well-Coded || For Beginners || Easy-Approach 🐍 | abhi9Rai | 2 | 262 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,753 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/2504986/Simple-Python-solution-with-inorder-traversal-oror-beats-92 | class Solution:
def __init__(self):
self.arr = []
def inOrder(self,root):
if root is None:
return []
else:
self.inOrder(root.left)
self.arr.append(root.val)
self.inOrder(root.right)
return self.arr
def balanced(self,left,right,nums):
if left > right:
return None
else:
mid = (left + right)//2
root = TreeNode(nums[mid])
root.left = self.balanced(left,mid-1,nums)
root.right = self.balanced(mid+1,right,nums)
return root
def balanceBST(self, root: TreeNode) -> TreeNode:
nums = self.inOrder(root)
return self.balanced(0,len(nums)-1,nums) | balance-a-binary-search-tree | Simple Python solution with inorder traversal || beats 92% | aruj900 | 1 | 58 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,754 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/2781548/Python3-Solution | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
# convert BST tree to a sorted array:
def bstToArrayInorder(root, arr):
if root is None:
return
bstToArrayInorder(root.left, arr)
arr.append(root.val)
bstToArrayInorder(root.right, arr)
return
def bstBalancedConstructerFromSortedArray(arr):
if not arr:
return None
mid = len(arr) // 2
root = TreeNode(arr[mid])
root.left = bstBalancedConstructerFromSortedArray(arr[:mid])
root.right = bstBalancedConstructerFromSortedArray(arr[mid+1:])
return root
arr = []
bstToArrayInorder(root, arr)
return bstBalancedConstructerFromSortedArray(arr) | balance-a-binary-search-tree | Python3 Solution | sipi09 | 0 | 6 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,755 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/2719601/Python3-Just-Remake-The-Tree-Reusing-Nodes | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
nodes = []
def r(n):
if n is not None:
r(n.left)
nodes.append(n)
r(n.right)
r(root)
def r2(l, r):
c = r-l + 1
if c <= 0:
return None
m = l + (c // 2)
n = nodes[m]
n.left = r2(l, m-1)
n.right = r2(m+1, r)
return n
return r2(0, len(nodes) - 1) | balance-a-binary-search-tree | Python3 Just Remake The Tree Reusing Nodes | godshiva | 0 | 4 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,756 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/2634973/Python-Simple-Clean-approach-Easy | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def inorder(root):
if root is None: return []
return inorder(root.left) + [root.val] + inorder(root.right)
nums = inorder(root)
def bst(l,r):
if l>r: return None
mid = (l+r)//2
return TreeNode(nums[mid], bst(l,mid-1), bst(mid+1,r))
return bst(0, len(nums)-1) | balance-a-binary-search-tree | ✅ [Python] Simple, Clean approach, Easy | girraj_14581 | 0 | 15 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,757 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/2231988/Python-Very-Simple-solution | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
arr=[]
def inorder(node):
if node:
inorder(node.left)
arr.append(node.val)
inorder(node.right)
return
inorder(root)
def fun(l,r):
while l<=r:
m=(l+r)//2
node=TreeNode(arr[m])
node.left=fun(l,m-1)
node.right=fun(m+1,r)
return node
return None | balance-a-binary-search-tree | [Python] Very Simple solution | pbhuvaneshwar | 0 | 79 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,758 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/1782707/Clean-and-easy-python3-solution | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def dfs(root):
if not root:
return
dfs(root.left)
res.append(root.val)
dfs(root.right)
res=[]
dfs(root)
def helper(root,nums):
if len(nums)==0:
return
mid=len(nums)//2
root=TreeNode(nums[mid])
root.left=helper(root.left,nums[:mid])
root.right=helper(root.right,nums[mid+1:])
return root
return helper(root,res) | balance-a-binary-search-tree | Clean and easy python3 solution | Karna61814 | 0 | 123 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,759 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/1525038/Python-in-order-DFS-traversal-to-build-a-sorted-array-and-then-build-balanced | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def dfs(n, nodes):
if not n:
return
dfs(n.left, nodes)
nodes.append(n.val)
dfs(n.right, nodes)
nodes = []
dfs(root, nodes)
def buildBalanced(nodes):
if not nodes:
return None
mid = len(nodes) // 2
n = TreeNode(nodes[mid])
n.left = buildBalanced(nodes[:mid])
n.right = buildBalanced(nodes[mid+1:])
return n
return buildBalanced(nodes) | balance-a-binary-search-tree | Python, in-order DFS traversal to build a sorted array and then build balanced | blue_sky5 | 0 | 118 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,760 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/1473996/Python-Clean-and-Easy | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def reconstruct(L, R):
if L > R:
return None
M = L + (R-L)//2
root = TreeNode(vals[M])
root.left = reconstruct(L, M-1)
root.right = reconstruct(M+1, R)
return root
def get_vals(node = root):
if not node:
return
get_vals(node.left)
vals.append(node.val)
get_vals(node.right)
vals = []
get_vals()
return reconstruct(0, len(vals)-1) | balance-a-binary-search-tree | [Python] Clean & Easy | soma28 | 0 | 188 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,761 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/1326478/Python3-Recursion | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
storage = []
def helper(root):
if not root:
return
helper(root.left)
storage.append(root)
helper(root.right)
helper(root)
def builder(data):
if not data:
return None
if len(data) == 1:
# reaching leaf, clearing previous relationships
out = data[0]
out.left = None
out.right = None
return out
mid = len(data) // 2
root = data[mid]
root.left = builder(data[: mid])
root.right = builder(data[mid + 1:])
return root
return builder(storage) | balance-a-binary-search-tree | Python3 Recursion | zhanz1 | 0 | 148 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,762 |
https://leetcode.com/problems/balance-a-binary-search-tree/discuss/1373973/Recursively-restore-with-medians-from-inorder-sequence-in-Python-3 | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def inorder_gen(n: TreeNode):
if not n:
return
yield from inorder_gen(n.left)
yield n
yield from inorder_gen(n.right)
n.left, n.right = None, None
seq = tuple(inorder_gen(root))
def restore(r, l) -> TreeNode:
if r > l:
return
mid = l + (r - l) // 2
n = seq[mid]
n.left, n.right = restore(r, mid - 1), restore(mid + 1, l)
return n
return restore(0, len(seq)-1) | balance-a-binary-search-tree | Recursively restore with medians from inorder sequence in Python 3 | mousun224 | -1 | 60 | balance a binary search tree | 1,382 | 0.807 | Medium | 20,763 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/741822/Met-this-problem-in-my-interview!!!-(Python3-greedy-with-heap) | class Solution:
def maxPerformance_simple(self, n, speed, efficiency):
people = sorted(zip(speed, efficiency), key=lambda x: -x[1])
result, sum_speed = 0, 0
for s, e in people:
sum_speed += s
result = max(result, sum_speed * e)
return result # % 1000000007 | maximum-performance-of-a-team | Met this problem in my interview!!! (Python3 greedy with heap) | dashidhy | 58 | 2,500 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,764 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/741822/Met-this-problem-in-my-interview!!!-(Python3-greedy-with-heap) | class Solution:
def maxPerformance(self, n, speed, efficiency, k):
people = sorted(zip(speed, efficiency), key=lambda x: -x[1])
result, sum_speed = 0, 0
min_heap = []
for i, (s, e) in enumerate(people):
if i < k:
sum_speed += s
heapq.heappush(min_heap, s)
elif s > min_heap[0]:
sum_speed += s - heapq.heappushpop(min_heap, s)
else:
continue # don't have to update result since top k speeds are not changed and efficiency goes down
result = max(result, sum_speed * e)
return result # % 1000000007 | maximum-performance-of-a-team | Met this problem in my interview!!! (Python3 greedy with heap) | dashidhy | 58 | 2,500 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,765 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2559791/Python3-Runtime%3A-387-ms-faster-than-98.24-or-Memory%3A-29.5-MB-less-than-99.37 | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
cur_sum, h = 0, []
ans = -float('inf')
for i, j in sorted(zip(efficiency, speed),reverse=True):
while len(h) > k-1:
cur_sum -= heappop(h)
heappush(h, j)
cur_sum += j
ans = max(ans, cur_sum * i)
return ans % (10**9+7) | maximum-performance-of-a-team | [Python3] Runtime: 387 ms, faster than 98.24% | Memory: 29.5 MB, less than 99.37% | anubhabishere | 16 | 1,600 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,766 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2560904/Python-Solution-with-Heap | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
heap = []
c = 0
ans = 0
for i,j in sorted(zip(efficiency,speed),reverse=True):
c += j
heapq.heappush(heap,j)
if len(heap)>k:
d = heapq.heappop(heap)
c -= d
ans = max(ans,i*c)
return ans%(10**9+7) | maximum-performance-of-a-team | Python Solution with Heap | a_dityamishra | 1 | 27 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,767 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2559899/Python3-soln-with-detailed-explanation-and-complexity-analysis | class Solution:
# O(nlogn) time,
# O(n) space,
# Approach: heap, sorting
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
# we create a array of tuples, (efficiency[i], speed[i])
engineers = [(efficiency[i], speed[i]) for i in range(n)]
# we will sort the our array in descending order of the engineers efficiency
engineers.sort(reverse=True)
# we create variables to hold the max performance, and tot speed when we iterate through our engineers array
# we will also have a min heap to store our min speed during our iteration,
# poping the next min speed will be possible that way
max_perf = 0
min_heap = []
tot_speed = 0
for engineer in engineers:
eng_speed = engineer[1]
min_eff = engineer[0]
# we add our current
heapq.heappush(min_heap, eng_speed)
tot_speed += eng_speed
# if tot engnrs are more than k, we pop the slowest engineer
if len(min_heap) > k:
tot_speed -=heapq.heappop(min_heap)
# we calculate the max perf we can get from this round of engineers
curr_max = tot_speed * min_eff
# update our max perf,
max_perf = max(max_perf, curr_max)
MOD = 10**9 + 7
return max_perf % MOD | maximum-performance-of-a-team | Python3 soln with detailed explanation and complexity analysis | destifo | 1 | 48 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,768 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2805460/Python%3A-Priority-Queue-(Min-Heap)-oror-Easy-to-understand | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
res=[]
for i in range(n):
res.append([speed[i],efficiency[i]])
res.sort(key=lambda x:x[1], reverse=True)
speedsum,performance=0,0
m=[]
heapq.heapify(m)
for i in range(len(res)):
currspeed=res[i][0]
curreff=res[i][1]
while len(m)>=k:
a=heapq.heappop(m)
speedsum-=a
heapq.heappush(m,currspeed)
speedsum+=currspeed
performance=max(performance,speedsum*curreff)
return performance%(10**9+7) | maximum-performance-of-a-team | Python: Priority Queue (Min Heap) || Easy to understand | utsa_gupta | 0 | 3 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,769 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2794282/Python3-or-Priority-Queue-or-Explained-with-example. | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
pq = []
currSum = 0
arr = sorted(zip(efficiency,speed),reverse = True)
ans = 0
for e,s in arr:
heappush(pq,s)
currSum+=s
if len(pq) > k:
currSum-=heappop(pq)
ans = max(ans,currSum*e)
return ans%(10**9+7) | maximum-performance-of-a-team | [Python3] | Priority Queue | Explained with example. | swapnilsingh421 | 0 | 4 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,770 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2562075/Python-O(n*log(n))-time-or-O-(n)-space | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
pairs = sorted(zip(efficiency, speed), reverse=True)
spheap, totalSpeed, best = [], 0, 0
for eff, spd in pairs:
heappush(spheap, spd)
if len(spheap) <= k:
totalSpeed += spd
else:
totalSpeed += spd - heappop(spheap)
best = max(best, totalSpeed * eff)
return best % (10**9+7) | maximum-performance-of-a-team | Python O(n*log(n)) time | O (n) space | vtalantsev | 0 | 12 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,771 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2561843/Simple-%22python%22-solution | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
eng = zip(efficiency, speed)
eng = sorted(eng, key=lambda x: x[0], reverse=True)
sumSpeed, res = 0, 0
speedHeap = []
for e, s in eng:
heapq.heappush(speedHeap, s)
sumSpeed += s
if len(speedHeap) > k:
sumSpeed -= heapq.heappop(speedHeap)
res = max(res, sumSpeed * e)
return res % (10 ** 9 + 7) | maximum-performance-of-a-team | Simple "python" solution | anandchauhan8791 | 0 | 20 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,772 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2561570/O(nlogn)-with-min-heap-and-sorting | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
mod = 10 ** 9 + 7
a = sorted(zip(efficiency, speed))[::-1]
print(a, k)
q = []
sum_speed = 0
ans = -1
for ei, si in a:
heappush(q, si)
sum_speed += si
if len(q)>k:
sum_speed -= heappop(q)
performance = sum_speed * ei
ans = max(ans, performance)
print("++ ", "ei:", ei, "si:", si, q, f"speed x effect={sum_speed} x {ei} = {performance}", "ans:", ans)
ans = ans % mod
print("ans:", ans)
print("="* 20)
return ans
print = lambda *a, **aa: () | maximum-performance-of-a-team | O(nlogn) with min heap and sorting | dntai | 0 | 6 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,773 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2560998/Python3-oror-TC%3A-O(nlogn)-oror-Priority-Queue | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
mod = (10 ** 9) + 7
#reverse sort based on efficiency
engineers = []
for eff, sp in zip(efficiency,speed):
engineers.append([eff,sp])
engineers.sort(reverse=True)
#maintain a heap of size k
#heap of speeds
total_speed = 0
speed_heap = []
performance = 0
for idx in range(k):
curr_min_eff = engineers[idx][0]
curr_speed = engineers[idx][1]
total_speed += curr_speed
heapq.heappush(speed_heap,engineers[idx][1])
performance = max(performance, curr_min_eff * total_speed)
for idx in range(k,len(engineers)):
curr_min_eff = engineers[idx][0]
curr_speed = engineers[idx][1]
if curr_speed > speed_heap[0]:
total_speed += curr_speed - speed_heap[0]
heapq.heappop(speed_heap)
heapq.heappush(speed_heap,curr_speed)
performance = max(performance, total_speed * curr_min_eff)
return performance % mod | maximum-performance-of-a-team | Python3 || TC: O(nlogn) || Priority Queue | s_m_d_29 | 0 | 12 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,774 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2560970/Python-it-in-10-Lines | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
cur_sum, h = 0, []
ans = -float('inf')
for i, j in sorted(zip(efficiency, speed),reverse=True):
while len(h) > k-1:
cur_sum -= heappop(h)
heappush(h, j)
cur_sum += j
ans = max(ans, cur_sum * i)
return ans % (10**9+7) | maximum-performance-of-a-team | Python it in 10 Lines 🔥 | Khacker | 0 | 23 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,775 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2560225/EASY-PYTHON3-SOLUTION | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
#variable zipped: stores employees' efficiency and speed in decreasing order of efficiency then speed
zipped = sorted(zip(efficiency, speed), reverse=True)
output = 0
#initialise heap
h = []
#to store sum of employees' speed, initialise sm
sm = 0
#loop to iterate over zipped
for z in range(0,n):
#current employee's speed
emp_speed = zipped[z][1]
#current employee's efficiency
emp_efficiency = zipped[z][0]
#push employee speed to heap h
heappush(h,emp_speed)
#increament sm by current employee's speed, since we want to focus on maximising speed
sm += emp_speed
#if number of employees' speed in heap > k
if len(h) > k:
#subtract the popped heap node from sm
sm -= heappop(h)
#find maximum performance
#emp_efficiency is already minimum as we sorted it before
output = max(output, sm*emp_efficiency)
return output % (10**9+7) | maximum-performance-of-a-team | ✅✔🔥 EASY PYTHON3 SOLUTION 🔥✅✔ | rajukommula | 0 | 19 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,776 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/2560224/Python3-Solution-or-Heap-or-O(nlogn) | class Solution:
def maxPerformance(self, n, speed, efficiency, k):
heap, csum, ans = [], 0, 0
for e, s in sorted(list(zip(efficiency, speed)), reverse = True):
csum += s
heapq.heappush(heap, s)
if len(heap) > k:
csum -= heapq.heappop(heap)
ans = max(ans, csum * e)
return ans % (1000_000_007) | maximum-performance-of-a-team | ✔ Python3 Solution | Heap | O(nlogn) | satyam2001 | 0 | 9 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,777 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/1257336/Python-O(n(logn-%2B-logk))-solution-using-MinHeap | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
sum_, ans = 0, 0
heap, pairlist = [], zip(efficiency, speed)
pairlist = sorted(pairlist, key=lambda x: x[0], reverse=True)
for val in pairlist:
if len(heap) >= k:
mi = heapq.heappop(heap)
sum_ -= mi
heapq.heappush(heap, val[1])
sum_ += val[1]
ans = max(ans, sum_ * val[0])
return ans % (10 ** 9 + 7) | maximum-performance-of-a-team | Python O(n(logn + logk)) solution using MinHeap | m0biu5 | 0 | 142 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,778 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/1252914/Python3-greedy | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
ans = rsm = 0
pq = []
for x, y in sorted(zip(efficiency, speed), reverse=True):
rsm += y
heappush(pq, y)
if len(pq) > k: rsm -= heappop(pq)
ans = max(ans, rsm * x)
return ans % 1_000_000_007 | maximum-performance-of-a-team | [Python3] greedy | ye15 | 0 | 65 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,779 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/1252509/python-heap-solution | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
heap = []
res = 0 ; ts = 0
a = []
for i in range(n):
a.append([efficiency[i],speed[i]])
a.sort(key = lambda x:x[0],reverse = True)
for eff,speed in a:
heappush(heap,speed)
ts += speed
if len(heap)>k:
ts-=heappop(heap)
res = max(res,ts*eff)
return res%(10**9+7) | maximum-performance-of-a-team | python heap solution | Abheet | 0 | 89 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,780 |
https://leetcode.com/problems/maximum-performance-of-a-team/discuss/1252280/96-faster-oror-Well-explained-with-comments-oror-Sort-and-Heap | class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
MOD = 10**9+7
# Converting both list into one list
candidates = zip(efficiency,speed)
# sort the candidates in terms of decreasing speed
candidates = sorted(candidates,key=lambda x:x[0],reverse=True)
speed_sum=res=0
# defining heap to store "K" efficient candidates
heap=[]
# Checking with every candidates
for ce,cs in candidates:
if len(heap)>=k:
speed_sum-=heap[0]
heapq.heappop(heap)
heapq.heappush(heap,cs)
speed_sum+=cs
res=max(res,speed_sum*ce)
return res%MOD | maximum-performance-of-a-team | 🐍 96% faster || Well-explained with comments || Sort & Heap | abhi9Rai | 0 | 138 | maximum performance of a team | 1,383 | 0.489 | Hard | 20,781 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2015283/python-3-oror-simple-binary-search-solution | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
n = len(arr2)
arr2.sort()
res = 0
for num in arr1:
low, high = 0, n - 1
while low <= high:
mid = (low + high) // 2
if abs(num - arr2[mid]) <= d:
break
elif num < arr2[mid]:
high = mid - 1
else:
low = mid + 1
else:
res += 1
return res | find-the-distance-value-between-two-arrays | python 3 || simple binary search solution | dereky4 | 4 | 298 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,782 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/1192875/Simple-Python-Bruteforce-Solution | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
res = len(arr1)
for i in arr1:
for j in arr2:
if(abs(i-j)>d):
continue
else:
res-=1
break
return res | find-the-distance-value-between-two-arrays | Simple Python Bruteforce Solution | ekagrashukla | 4 | 429 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,783 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2311656/Python-Simple-Python-Solution-With-Two-Approach | class Solution:
def findTheDistanceValue(self, array1: List[int], array2: List[int], d: int) -> int:
result = 0
array2 = sorted(array2)
for num in array1:
flag = True
low = 0
high = len(array2)-1
while low <= high:
mid = (low + high) // 2
if abs(array2[mid] - num) <= d:
flag = False
break
elif array2[mid] > num:
high = mid - 1
else:
low = mid + 1;
if flag == True:
result = result + 1
return result | find-the-distance-value-between-two-arrays | [ Python] ✅✅ Simple Python Solution With Two Approach 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 3 | 276 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,784 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2311656/Python-Simple-Python-Solution-With-Two-Approach | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
s=0
for i in arr1:
t=0
for j in arr2:
if abs(i-j)<= d:
t=1
break
if t==0:
s=s+1
return s | find-the-distance-value-between-two-arrays | [ Python] ✅✅ Simple Python Solution With Two Approach 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 3 | 276 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,785 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2419318/C%2B%2BPython-Best-Approach-solution | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr2.sort()
distance = len(arr1)
for num in arr1:
start = 0
end = len(arr2) - 1
while start <= end:
mid = (start+end)//2
if abs(num- arr2[mid]) <= d:
distance -= 1
break
elif arr2[mid] > num :
end = mid-1
elif arr2[mid] < num :
start = mid+1
return distance | find-the-distance-value-between-two-arrays | C++/Python Best Approach solution | arpit3043 | 2 | 133 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,786 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2356023/Python-Iterative-Binary-Search-Solution-oror-Well-Documented | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
# binary search for diff <= d, if found return 0, else 1
def binSearch(value: int) -> int:
low, high = 0, len(arr2) - 1
# Repeat until the pointers low and high meet each other
while low <= high:
mid = (low + high) // 2
if abs(value-arr2[mid]) <= d:
return 0
if v > arr2[mid]:
low = mid + 1 # go right side
else:
high = mid - 1 # go left side
# no such value found where diff <= d
return 1
# sort the array so that we can perform binary-search
arr2.sort()
# distance value count
dValueCount = 0
# search for diff <= d for each num
for v in arr1:
dValueCount += binSearch(v)
return dValueCount | find-the-distance-value-between-two-arrays | [Python] Iterative Binary Search Solution || Well Documented | Buntynara | 2 | 61 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,787 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/859630/Python3-two-binary-searches | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr2.sort()
ans = 0
for x in arr1:
i = bisect_left(arr2, x-d)
j = bisect_right(arr2, x+d)
if i == j: ans += 1
return ans | find-the-distance-value-between-two-arrays | [Python3] two binary searches | ye15 | 2 | 145 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,788 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/859630/Python3-two-binary-searches | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr2.sort()
ans = 0
for x in arr1:
i = bisect_left(arr2, x-d)
j = bisect_left(arr2, x+d+1)
if i == j: ans += 1
return ans | find-the-distance-value-between-two-arrays | [Python3] two binary searches | ye15 | 2 | 145 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,789 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/859630/Python3-two-binary-searches | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr1.sort()
arr2.sort()
ans = i = j = 0
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j] + d:
if arr1[i] < arr2[j] - d: ans += 1
i += 1
else: j += 1
return ans + len(arr1) - i | find-the-distance-value-between-two-arrays | [Python3] two binary searches | ye15 | 2 | 145 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,790 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2530644/Python3-or-Solved-Using-Binary-Search-and-Considering-Range-of-Numbers | class Solution:
#Time-Complexity: O(len(arr1)*2d*log(len(arr2)))
#Space-Complexity: O(1)
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
#initialize ans variable!
ans = 0
#helper function will compute whether particular element is in given array of elements,
#of at least size 1!
#to apply helper function on arr2, we need to make sure it's sorted!
arr2.sort()
def helper(e, a):
#involve binary search
L, R = 0, len(a) - 1
while L <= R:
mid = (L+R) // 2
if(a[mid] == e):
return True
elif(a[mid] > e):
R = mid - 1
continue
else:
L = mid + 1
continue
return False
#iterate through each and every element in arr1!
for num in arr1:
#flag will indicate whether current num is able to contribute to distance value!
flag = True
#iterate through possible values w/ respect to num that will make it
#not contribute to distance value between two arrays!
for i in range(num - d, num+d+1):
#check if current i is in arr2!
#if so, set flag off and break!
if(helper(i, arr2)):
flag = False
break
#check boolean flag!
if(flag):
ans += 1
return ans | find-the-distance-value-between-two-arrays | Python3 | Solved Using Binary Search and Considering Range of Numbers | JOON1234 | 1 | 70 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,791 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2119709/Simple-Python-Brute-Force-Solution | class Solution(object):
def findTheDistanceValue(self, arr1, arr2, d):
min_dist=0
for i in range(len(arr1)):
for j in range(len(arr2)):
if abs(arr1[i]-arr2[j]) <= d:
min_dist +=1
break
return len(arr1)-(min_dist) | find-the-distance-value-between-two-arrays | Simple Python Brute Force Solution | NathanPaceydev | 1 | 105 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,792 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2077581/python-O(nd)-solution(use-dict) | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
dic, count = {}, len(arr1)
for i in arr2:
dic[i] = True
for i in arr1:
for j in range(i - d, i + d + 1):
if j in dic:
count -= 1
break
return count | find-the-distance-value-between-two-arrays | python O(nd) solution(use dict) | TUL | 1 | 109 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,793 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/1466702/Sort-and-bisect-95-speed | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr2.sort()
len2 = len(arr2)
distance = 0
for n in arr1:
idx = bisect_left(arr2, n)
if idx < len2 and arr2[idx] - n > d:
if idx > 0:
if n - arr2[idx - 1] > d:
distance += 1
else:
distance += 1
elif idx == len2 and n - arr2[idx - 1] > d:
distance += 1
return distance | find-the-distance-value-between-two-arrays | Sort and bisect, 95% speed | EvgenySH | 1 | 254 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,794 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/1067775/Python3-solution-using-two-approaches | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
l1 = []
for i in arr1:
l1.append(list(range(i-d, i+d+1)))
count = len(arr1)
print(l1)
for i in l1:
for j in i:
if j in arr2:
count -= 1
break
return count | find-the-distance-value-between-two-arrays | Python3 solution using two approaches | EklavyaJoshi | 1 | 132 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,795 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/1067775/Python3-solution-using-two-approaches | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr2.sort()
count = 0
for i in arr1:
low = 0
high = len(arr2)-1
while high - low > 1:
mid = (high + low)//2
if arr2[mid] > i:
high = mid
else:
low = mid
if min(abs(arr2[low]-i),abs(arr2[high]-i)) > d:
count += 1
return count | find-the-distance-value-between-two-arrays | Python3 solution using two approaches | EklavyaJoshi | 1 | 132 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,796 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2838906/python-solution-not-binary | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
di= defaultdict(list)
for a1 in arr1 :
for a2 in arr2 :
di[a1].append(abs(a1-a2))
cnt = 0
for k in arr1:
if all( e>d for e in di[k] ):
cnt+=1
return cnt | find-the-distance-value-between-two-arrays | python solution / not binary | Cosmodude | 0 | 2 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,797 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2835835/Simple-Python-solution | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
count = 0
for i in arr1:
for j in arr2:
if abs(i-j) <= d:
break
else:
count += 1
return count | find-the-distance-value-between-two-arrays | Simple Python solution | aruj900 | 0 | 3 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,798 |
https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2797226/Python-3orEasy-to-understand-orexplained-approach | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
c=0
value=False
for i in arr1:
for j in arr2:
if abs(i-j)<=d:
value=True
if value ==False:
c+=1
value=False
return c | find-the-distance-value-between-two-arrays | Python-3|Easy to understand |explained approach | ankit0702 | 0 | 2 | find the distance value between two arrays | 1,385 | 0.654 | Easy | 20,799 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.