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/maximum-difference-between-node-and-ancestor/discuss/1421942/Python3-Top-Down-track-min-and-max-with-results
class Solution: def __init__(self): self.res = 0 def traversal(self, node, _min, _max): if not node: return _min = min(_min, node.val) _max = max(_max, node.val) self.res = max(self.res, abs(node.val - _min), abs(node.val - _max)) self.traversal(node.left, _min, _max) self.traversal(node.right, _min, _max) def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: self.traversal(root, root.val, root.val) return self.res
maximum-difference-between-node-and-ancestor
[Python3] Top-Down track min and max with results
maosipov11
0
31
maximum difference between node and ancestor
1,026
0.734
Medium
16,800
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/1149988/WEEB-DOES-PYTHON-BFS-BEATS-99.61
class Solution: def maxAncestorDiff(self, root: TreeNode) -> int: queue, diff = deque([[root, root.val, root.val]]), 0 while queue: curNode, max_val, min_val = queue.popleft() if not curNode.left and not curNode.right: if max_val - min_val > diff: diff = max_val - min_val if curNode.left: queue.append((curNode.left, max(curNode.left.val, max_val), min(curNode.left.val, min_val))) if curNode.right: queue.append((curNode.right, max(curNode.right.val, max_val), min(curNode.right.val, min_val))) return diff
maximum-difference-between-node-and-ancestor
WEEB DOES PYTHON BFS BEATS 99.61%
Skywalker5423
0
54
maximum difference between node and ancestor
1,026
0.734
Medium
16,801
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/929795/Python3-pre-order-dfs
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: ans = 0 stack = [(root, inf, -inf)] while stack: node, lo, hi = stack.pop() lo = min(lo, node.val) hi = max(hi, node.val) ans = max(ans, node.val - lo, hi - node.val) if node.left: stack.append((node.left, lo, hi)) if node.right: stack.append((node.right, lo, hi)) return ans
maximum-difference-between-node-and-ancestor
[Python3] pre-order dfs
ye15
0
50
maximum difference between node and ancestor
1,026
0.734
Medium
16,802
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/929594/maxAncestorDiff-or-python-postorder-traversal
class Solution: def maxAncestorDiff(self, root: TreeNode) -> int: return self.dfs(root)[0] def dfs(self, root): diff = 0 mx = mn = root.val if root.left: ldiff, lmx, lmn = self.dfs(root.left) diff = max(abs(root.val - lmx), abs(root.val - lmn), ldiff) mx = max(mx, lmx) mn = min(mn, lmn) if root.right: rdiff, rmx, rmn = self.dfs(root.right) diff = max(diff, rdiff, abs(root.val - rmx), abs(root.val - rmn)) mx = max(mx, rmx) mn = min(mn, rmn) return diff, mx, mn
maximum-difference-between-node-and-ancestor
maxAncestorDiff | python postorder traversal
hangyu1130
0
39
maximum difference between node and ancestor
1,026
0.734
Medium
16,803
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/283492/Clean-Python-Using-Preorder-Traversal
class Solution: def maxAncestorDiff(self, root: TreeNode) -> int: return self._max_ancestor_diff(root, root.val, root.val) def _max_ancestor_diff(self, root: TreeNode, max_ancestor_val: int, min_ancestor_val: int) -> int: if root is None: return 0 return max( abs(max_ancestor_val - root.val), abs(min_ancestor_val - root.val), self._max_ancestor_diff( root.left, max(max_ancestor_val, root.val), min(min_ancestor_val, root.val)), self._max_ancestor_diff( root.right, max(max_ancestor_val, root.val), min(min_ancestor_val, root.val)) )
maximum-difference-between-node-and-ancestor
Clean Python Using Preorder Traversal
aquafie
0
213
maximum difference between node and ancestor
1,026
0.734
Medium
16,804
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/415281/Python-DP-solution
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: dp = {} for i, a2 in enumerate(A[1:], start=1): for j, a1 in enumerate(A[:i]): d = a2 - a1 if (j, d) in dp: dp[i, d] = dp[j, d] + 1 else: dp[i, d] = 2 return max(dp.values())
longest-arithmetic-subsequence
Python DP solution
yasufumy
53
5,200
longest arithmetic subsequence
1,027
0.47
Medium
16,805
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/1012379/Python3-dp
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: ans = 0 cnt = defaultdict(lambda: 1) seen = set() for x in A: for xx in seen: cnt[x, x-xx] = 1 + cnt[xx, x-xx] ans = max(ans, cnt[x, x-xx]) seen.add(x) return ans
longest-arithmetic-subsequence
[Python3] dp
ye15
10
544
longest arithmetic subsequence
1,027
0.47
Medium
16,806
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/1852177/simple-python-dp
class Solution(object): def longestArithSeqLength(self, A): dp = {} for i in range(len(A)): for j in range(i + 1, len(A)): dp[j, A[j] - A[i]] = dp.get((i, A[j] - A[i]), 1) + 1 return max(dp.values())
longest-arithmetic-subsequence
simple python dp
gasohel336
4
301
longest arithmetic subsequence
1,027
0.47
Medium
16,807
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/2019124/PYTHON-SOL-oror-EXPLAINED-oror-HASHMAP-oror-SIMPLE-oror-INTUTIVE-oror
class Solution: def longestArithSeqLength(self, nums: List[int]) -> int: n = len(nums) dp = {x:{} for x in range(n)} for i in range(n): for j in range(i+1,n): tmp = dp[i][nums[j]-nums[i]] if nums[j]-nums[i] in dp[i] else 1 dp[j][nums[j]-nums[i]] = tmp + 1 ans = 0 for i in dp: for j in dp[i]: if dp[i][j] > ans: ans = dp[i][j] return ans
longest-arithmetic-subsequence
PYTHON SOL || EXPLAINED || HASHMAP || SIMPLE || INTUTIVE ||
reaper_27
3
290
longest arithmetic subsequence
1,027
0.47
Medium
16,808
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/989883/python-3-ways-to-solve-(iterative%2Btrim-dp-dp)
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: # Method 1 # Iterative with trim, beats ~85% runtime res = 1 idx = defaultdict(list) # reverse idx for i, a in enumerate(A): idx[a] += i, visited = set() for i in range(len(A)-1): if idx[A[i]][0] != i: continue # if the same number has been checked before, skip it for j in range(i+1, len(A)): diff = A[j] - A[i] if (A[i], diff) in visited: continue visited.add((A[i], diff)) cnt = 1 nxt = A[j] pntr = i while nxt in idx: if idx[nxt][-1] <= pntr: break visited.add((nxt, diff)) cnt += 1 pntr = min([_ for _ in idx[nxt] if _ > pntr]) nxt += diff res = max(res, cnt) return res # # Method 2: # # dp[i][j]: length of the longest subseq with i-th item as last item and j-500 as diff, beats ~24% runtime dp = [[0] * 1001 for _ in range(len(A))] res = 2 for i in range(1, len(A)): for j in range(i): diff = A[i] - A[j] dp[i][diff+500] = max(2, dp[j][diff+500]+1) res = max(res, dp[i][diff+500]) return res # Method 3: optimize on method 2, shorter # dp[i] keeps a dict of <diff, length of longest subseq with i-th item as end and diff as gap> dp = [defaultdict(int) for _ in range(len(A))] res = 2 for i in range(1, len(A)): for j in range(i): diff = A[i] - A[j] dp[i][diff] = max(2, dp[j][diff]+1) res = max(res, dp[i][diff]) return res
longest-arithmetic-subsequence
python, 3 ways to solve (iterative+trim, dp, dp)
ChiCeline
2
319
longest arithmetic subsequence
1,027
0.47
Medium
16,809
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/419552/Python-95-O(N2)-Explain-top-solution-with-comments
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: N, out = len(A), 0 inverted_index = collections.defaultdict(list) DP = collections.defaultdict(int) # create inverted index for i, v in enumerate(A): inverted_index[v].append(i) for i in range(1,N): for j in range(i): # calculate the diff between current 2 index's diff = A[j] - A[i] # for every index in the array == A[j] + the diff for k in inverted_index[A[j] + diff]: # stop if we are equal to or past j in the array if k >= j: break # add 1 to the new subseq of arithmetic diff including j DP[j, diff] = DP[k, diff] + 1 # keep track of the max out = max(out, DP[j, diff]) return out + 2 # Need to add 2 to count the first and last index in the subsequence since we are only +1ing for each element inside the subsequence.
longest-arithmetic-subsequence
Python - 95% O(N^2) - Explain top solution with comments
jessebrizzi
1
1,000
longest arithmetic subsequence
1,027
0.47
Medium
16,810
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/2801020/Python-solution
class Solution: def longestArithSeqLength(self, nums: List[int]) -> int: dp = [[1 for _ in range(1001)] for _ in range(len(nums))] ans = 0 for i in range(len(nums)): for j in range(i): dif = nums[i] - nums[j] + 500 dp[i][dif] = max(dp[i][dif], dp[j][dif] + 1) ans = max(ans, dp[i][dif]) return ans
longest-arithmetic-subsequence
Python solution
geek_thor
0
5
longest arithmetic subsequence
1,027
0.47
Medium
16,811
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/2147987/Python3%3A-O(N2)-Top-Down-DP-Solution-with-Double-defaultdict
class Solution: def longestArithSeqLength(self, nums: List[int]) -> int: """ Top down DP (Memorization) dict = {idx: {diff: count}} O(n^2) """ from collections import defaultdict res = 0 # default to have at least 2 subsequence memo = defaultdict(lambda: defaultdict(lambda: 2)) # O(n^2) for i in range(1, len(nums)): for j in range(i): diff = nums[i]-nums[j] if diff in memo[j]: memo[i][diff] = memo[j][diff]+1 res = max(res, memo[i][diff]) return res
longest-arithmetic-subsequence
Python3: O(N^2) Top Down DP Solution with Double defaultdict
yunglinchang
0
220
longest arithmetic subsequence
1,027
0.47
Medium
16,812
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/955702/Simple-Python-Solution
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: dp=[{}]*len(A) maxv=1 for i in range(len(A)): curr=A[i] dp[i]={} d={} for j in range(i): difference=curr-A[j] prevMap=dp[j] if difference in dp[j]: d[difference]=dp[j][difference]+1 else: d[difference]=1 dp[i]=d maxv=max(maxv,d[difference]) return maxv+1
longest-arithmetic-subsequence
Simple Python Solution
Ayu-99
0
198
longest arithmetic subsequence
1,027
0.47
Medium
16,813
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/391130/Solution-in-Python-3-(beats-~99)-(DP)-(eight-lines)
class Solution: def longestArithSeqLength(self, A): L, DI, C, M = len(A), collections.defaultdict(list), collections.defaultdict(int), 0 for i, v in enumerate(A): DI[v].append(i) for i in range(1,L): for j in range(i): for k in DI[2 * A[j] - A[i]]: if k >= j: break M, C[j, i] = max(M, C[k, j] + 1), C[k, j] + 1 return M + 2 - Junaid Mansuri (LeetCode ID)@hotmail.com
longest-arithmetic-subsequence
Solution in Python 3 (beats ~99%) (DP) (eight lines)
junaidmansuri
0
931
longest arithmetic subsequence
1,027
0.47
Medium
16,814
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/285936/python3-388ms
class Solution(object): def longestArithSeqLength(self, A): idx = collections.defaultdict(list) for i, v in enumerate(A): idx[v].append(i) c = {} ans = 0 for k in range(len(A)): # last for j in range(k): # middle v = 2 * A[j] - A[k] if v in idx: for i in idx[v]: # list of first if i >= j: break r = 1 if (i, j) in c: r = max(r, c[i, j] + 1) ans = max(ans, r) c[j, k] = r return ans + 2
longest-arithmetic-subsequence
python3 - 388ms
muzehyun
0
248
longest arithmetic subsequence
1,027
0.47
Medium
16,815
https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/discuss/1179506/Python3-stack
class Solution: def recoverFromPreorder(self, S: str) -> TreeNode: stack = [] depth, val = 0, "" for i, x in enumerate(S): if x == "-": depth += 1 val = "" else: val += S[i] if i+1 == len(S) or S[i+1] == "-": node = TreeNode(int(val)) while len(stack) > depth: stack.pop() if stack: if not stack[-1].left: stack[-1].left = node else: stack[-1].right = node stack.append(node) depth = 0 return stack[0]
recover-a-tree-from-preorder-traversal
[Python3] stack
ye15
3
116
recover a tree from preorder traversal
1,028
0.73
Hard
16,816
https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/discuss/2464182/Python-No-Stack-O(N)-Commented-Simple
class Solution: def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]: # edge condition as there might be an empty string if not traversal: return traversal # -------------------------------------------------------------- # This part contains: splitting the string into the dashes and # values for each node # Pass 1 # -------------------------------------------------------------- # traverse the string and split it split = [] start = 0 for index, character in enumerate(traversal[:-1]): # once we hit a number and the next character is a dash # we have a split point if character != '-' and traversal[index+1] == '-': # append the split and set the index to the next character split.append(traversal[start:index+1]) start = index + 1 # since the last node has not been appended # (there is not dash following a number) # we need to append the last element split.append(traversal[start:]) # get the root as it is the first element in the list root = TreeNode(int(split[0])) split = split[1:] # -------------------------------------------------------------- # This part contains: going through the nodes and building the # tree # Pass 2 # -------------------------------------------------------------- last_node = root current_level = 1 # go trough the string for node in split: # replace the dashes to get the value and the amount of dashes value = node.replace('-', '') level = len(node) - len(value) value = int(value) if level > current_level: # we go a layer deeper # get the next interesting node # since we are building the tree from # left to right, we always want to take # the rightmost route if last_node.right: last_node = last_node.right else: last_node = last_node.left # once we hit a node that is above the one we are attaching # to, we need to traverse down the tree from the root again elif level < current_level: # we need to change the level # go back to the root last_node = root # go through the nodes for each level temp_level = 1 while temp_level < level: # get the next interesting node # since we are building the tree from # left to right, we always want to take # the rightmost route if last_node.right: last_node = last_node.right else: last_node = last_node.left temp_level += 1 # check whether we already have a left node and # attach the current node if last_node.left is None: last_node.left = TreeNode(value) else: last_node.right = TreeNode(value) # update the level current_level = level return root
recover-a-tree-from-preorder-traversal
Python - No Stack - O(N)- Commented - Simple
Lucew
0
45
recover a tree from preorder traversal
1,028
0.73
Hard
16,817
https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/discuss/1410846/Python3-Iterative-Stack-Solution-with-results
class Solution: def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]: i = 0 stack = [] fake = TreeNode(0) stack.append(fake) while i < len(traversal): lvl = 0 while i < len(traversal) and traversal[i] == '-': lvl += 1 i += 1 beg = i while i < len(traversal) and traversal[i] != '-': i += 1 val = int(traversal[beg:i]) while len(stack) - 1 > lvl: stack.pop() children = TreeNode(val) node = stack[-1] if node.left == None: node.left = children else: node.right = children stack.append(children) return stack[0].left
recover-a-tree-from-preorder-traversal
[Python3] Iterative Stack Solution with results
maosipov11
0
34
recover a tree from preorder traversal
1,028
0.73
Hard
16,818
https://leetcode.com/problems/two-city-scheduling/discuss/297143/Python-faster-than-93-28-ms
class Solution(object): def twoCitySchedCost(self, costs): """ :type costs: List[List[int]] :rtype: int """ a = sorted(costs, key=lambda x: x[0]-x[1]) Sa = 0 Sb = 0 for i in range(len(a)//2): Sa += a[i][0] for i in range(len(a)//2, len(a)): Sb += a[i][1] return Sa + Sb
two-city-scheduling
Python - faster than 93%, 28 ms
il_buono
17
1,900
two city scheduling
1,029
0.648
Medium
16,819
https://leetcode.com/problems/two-city-scheduling/discuss/1012326/Python-3-O(nlogn)-Easy-to-understand
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: ''' Example: [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]] Answer Choices (what to choose for min cost): City A - 259, 184, 577 City B - 54, 118, 667 Answer Total Score: 1859 Calculate scores for each pair and determine which cities to pick. Higher score = higher priority to pick lower cost city Score = abs(cityA - cityB) 722 - [840, 118] - City B 511 - [259, 770] - City A 394 - [448, 54] - City B 259 - [926, 667] - City B 108 - [577,459] - City A 45 - [184, 139] - City A ''' people = len(costs) / 2 a,b = people,people scores = [[abs(a-b),(a,b)] for a,b in costs] # calc the score, store the pair scores.sort(reverse=True) totalScore = 0 # Scores - [[Calculated Score, (CityA-Cost, CityB-Cost)], ... ] This is what the scores array looks like for x in scores: choice = x[1] if choice[0] <= choice[1] and a > 0 or b == 0: # b == 0 means we reached n choices for city B already a -= 1 totalScore += choice[0] elif choice[0] > choice[1] and b > 0 or a == 0: b -= 1 totalScore += choice[1] return totalScore
two-city-scheduling
Python 3 O(nlogn) Easy to understand
jkp5380
6
515
two city scheduling
1,029
0.648
Medium
16,820
https://leetcode.com/problems/two-city-scheduling/discuss/668326/Python3-2-line-O(NlogN)
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs.sort(key=lambda x: x[0]-x[1]) return sum(a if i < len(costs)//2 else b for i, (a, b) in enumerate(costs))
two-city-scheduling
[Python3] 2-line O(NlogN)
ye15
3
118
two city scheduling
1,029
0.648
Medium
16,821
https://leetcode.com/problems/two-city-scheduling/discuss/668326/Python3-2-line-O(NlogN)
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: @lru_cache(None) def fn(i, j): if i == 0 and j == 0: return 0 if j == 0: return fn(i-1, 0) + costs[i-1][0] if i == 0: return fn(0, j-1) + costs[j-1][1] return min(fn(i-1, j) + costs[i+j-1][0], fn(i, j-1) + costs[i+j-1][1]) return fn(len(costs)//2, len(costs)//2)
two-city-scheduling
[Python3] 2-line O(NlogN)
ye15
3
118
two city scheduling
1,029
0.648
Medium
16,822
https://leetcode.com/problems/two-city-scheduling/discuss/1882621/Python3-Simple-Greedy
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs.sort(key=lambda x: -abs(x[0] - x[1])) n = len(costs) / 2 n1 = 0 n2 = 0 totalCost = 0 for c1, c2 in costs: if (n1 < n and c1 <= c2) or n2 == n: totalCost += c1 n1 += 1 else: totalCost += c2 n2 += 1 return totalCost
two-city-scheduling
[Python3] Simple Greedy
KurtisWithAK
2
110
two city scheduling
1,029
0.648
Medium
16,823
https://leetcode.com/problems/two-city-scheduling/discuss/1882440/Python3-Greedy-solution-by-sorting
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: n = len(costs)//2 res = 0 diff = sorted(costs, key = lambda x: x[0] - x[1]) for i in range(2*n): if i < n: res += diff[i][0] else: res += diff[i][1] return res
two-city-scheduling
[Python3] Greedy solution by sorting
nandhakiran366
2
46
two city scheduling
1,029
0.648
Medium
16,824
https://leetcode.com/problems/two-city-scheduling/discuss/668103/Py-Easy-Sol%3A-Faster-than-99.88
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs = sorted(costs, key=lambda x:abs(x[0]-x[1]), reverse=True) # for example- [[10,20],[30,200],[400,50],[30,20]] will become # this- [[400, 50], [30, 200], [10, 20], [30, 20]] sm = 0 countA = countB = len(costs)//2 for a, b in costs: if countA>0 and countB>0: if a<b: countA-=1 sm += a else: countB-=1 sm +=b elif countA==0: sm+=b else: sm+=a return sm
two-city-scheduling
Py Easy Sol: Faster than 99.88%
ycverma005
2
466
two city scheduling
1,029
0.648
Medium
16,825
https://leetcode.com/problems/two-city-scheduling/discuss/1895747/Python-Sort-by-Greatest-Savings-to-CityA-and-Send-that-half-to-CityA-Send-Remaining-to-CityB
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: # Track the savings for flying to cityA instead of cityB # Data structure: [[amount_saved_cityA, cost_to_cityA, cost_to_cityB], ...] savings_cityA = [] for [cost_to_cityA, cost_to_cityB] in costs: amount_saved_cityA = cost_to_cityB - cost_to_cityA savings_cityA.append([amount_saved_cityA, cost_to_cityA, cost_to_cityB]) # Sort to pull the highest savings to cityA to the left savings_cityA.sort(reverse=True) # At this point, the left half contains costs where the # savings for flying to cityA is the highest (save most money) # and the remaining right half contains costs where the # savings by flying to cityA is the least (save least money/lose money) # So send the left half to cityA and right half to cityB total_cost = 0 for i, [_, cost_to_cityA, cost_to_cityB] in enumerate(savings_cityA): if i < len(savings_cityA) // 2: total_cost += cost_to_cityA else: total_cost += cost_to_cityB return total_cost
two-city-scheduling
Python Sort by Greatest Savings to CityA, and Send that half to CityA, Send Remaining to CityB
roadtoknighthood22
1
72
two city scheduling
1,029
0.648
Medium
16,826
https://leetcode.com/problems/two-city-scheduling/discuss/1883283/Python-or-Time-O(n-log-n)-or-Beats-99.4
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs.sort(key=lambda x: x[0] - x[1]) tot, i, mid = 0, 0, len(costs) // 2 while i < mid: tot += costs[i][0] + costs[i+mid][1] i += 1 return tot
two-city-scheduling
Python | Time O(n log n) | Beats 99.4%
prajyotgurav
1
80
two city scheduling
1,029
0.648
Medium
16,827
https://leetcode.com/problems/two-city-scheduling/discuss/470173/Python3-99.50-(28-ms)100.00-(12.8-MB)-O(n-*-log(n))-time-O(1)-space-sort-by-difference
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs.sort(key = lambda x: abs(x[0] - x[1]), reverse = True) ret = 0 A_left = len(costs) // 2 B_left = A_left costs_len = len(costs) for a in range(costs_len): if (costs[a][0] > costs[a][1]): if (B_left): ret += costs[a][1] B_left -= 1 else: ret += costs[a][0] A_left -= 1 else: if (A_left): ret += costs[a][0] A_left -= 1 else: ret += costs[a][1] B_left -= 1 return ret
two-city-scheduling
Python3 99.50% (28 ms)/100.00% (12.8 MB) -- O(n * log(n)) time / O(1) space -- sort by difference
numiek_p
1
323
two city scheduling
1,029
0.648
Medium
16,828
https://leetcode.com/problems/two-city-scheduling/discuss/2648126/Python-or-Python3-or-With-explanation
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: # TC : O(n log n) # In this array we will store the difference between costToCityB(c2) - costToCityA(c1) for each person diff = [] res = 0 for c1,c2 in costs: diff.append([c2-c1,c1,c2]) diff.sort() for i in range(len(diff)): if i < len(diff)//2: res+=diff[i][2] #This is to send first half of the diff array to city2 or cityB else: res+=diff[i][1] #This is to send the second half of the diff array to city1 or cityA return res
two-city-scheduling
Python | Python3 | With explanation
Ron99
0
70
two city scheduling
1,029
0.648
Medium
16,829
https://leetcode.com/problems/two-city-scheduling/discuss/2319331/Python-99-Faster
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: arr = [] for i in range(len(costs)): arr.append((costs[i][1]-costs[i][0],i)) arr.sort() ans = 0 for i in range(len(arr)): if i<len(arr)/2: ans+=costs[arr[i][1]][1] else: ans += costs[arr[i][1]][0] return ans
two-city-scheduling
Python 99% Faster
Abhi_009
0
80
two city scheduling
1,029
0.648
Medium
16,830
https://leetcode.com/problems/two-city-scheduling/discuss/2318915/Python3-Solution
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: diff=[i-j for i,j in costs] res=list(map(list, list(zip(*sorted(zip(*[costs,diff]), key=lambda sublist_to_sort_by: sublist_to_sort_by[-1]))))) s=0 for i,j in enumerate(res[0]): s+=j[i//(len(costs)//2)] return s
two-city-scheduling
Python3 Solution
Kunalbmd
0
25
two city scheduling
1,029
0.648
Medium
16,831
https://leetcode.com/problems/two-city-scheduling/discuss/2246384/Python-short-and-intutive
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: diff = [(c[1]-c[0],c[0]) for c in costs] diff.sort() return sum([diff[d][0]+diff[d][1] for d in range(0,len(costs)//2) ]) + sum([diff[d][1] for d in range(len(costs)//2,len(costs)) ])
two-city-scheduling
Python short and intutive
harsh30199
0
62
two city scheduling
1,029
0.648
Medium
16,832
https://leetcode.com/problems/two-city-scheduling/discuss/2095906/Solution-using-Greedy-learned-by-NeetCode
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs = sorted(costs, key=lambda c: c[1] - c[0]) n = len(costs) res = 0 for i in range(len(costs)): if i < n // 2: res += costs[i][1] else: res += costs[i][0] return res
two-city-scheduling
Solution using Greedy learned by NeetCode
andrewnerdimo
0
160
two city scheduling
1,029
0.648
Medium
16,833
https://leetcode.com/problems/two-city-scheduling/discuss/2085632/python-3-oror-greedy-two-line-solution
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs.sort(key=lambda cost: cost[0] - cost[1]) return sum(costs[i][0] + costs[~i][1] for i in range(len(costs) // 2))
two-city-scheduling
python 3 || greedy two line solution
dereky4
0
84
two city scheduling
1,029
0.648
Medium
16,834
https://leetcode.com/problems/two-city-scheduling/discuss/2019326/PYTHON-SOL-oror-RECURSION-%2B-MEMO-oror-EXPLAINED-WITH-PICTURE-oror-SIMPLE
class Solution: def recursion(self,index,a,b): if index == self.n: return 0 if (index,a,b) in self.dp:return self.dp[(index,a,b)] ch1 = self.recursion(index+1,a-1,b) + self.costs[index][0] if a > 0 else float('inf') ch2 = self.recursion(index+1,a,b-1) + self.costs[index][1] if b > 0 else float('inf') best = ch1 if ch1 < ch2 else ch2 self.dp[(index,a,b)] = best return best def twoCitySchedCost(self, costs: List[List[int]]) -> int: self.n = len(costs) self.costs = costs self.dp = {} return self.recursion(0,self.n//2,self.n//2)
two-city-scheduling
PYTHON SOL || RECURSION + MEMO || EXPLAINED WITH PICTURE || SIMPLE
reaper_27
0
95
two city scheduling
1,029
0.648
Medium
16,835
https://leetcode.com/problems/two-city-scheduling/discuss/1883400/Python3-solution-or-Sorting-or-commented
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs = sorted(costs, key=lambda x: abs(x[0]-x[1])) # sort by abs diff chosen = [] ans = 0 left = 0 right = 0 for i in range(len(costs)): if costs[i][0] <= costs[i][1]: chosen.append("left") ans += costs[i][0] left += 1 # choosing left (A city) else: ans += costs[i][1] right += 1 # choosing right (B city) chosen.append("right") if right != left: # if these 2 aren't equal we're just gonna change from start to end the city for every person that is in a city with a bigger number of choices for i in range(len(costs)): # doing these we reduce the cost and we will spend the least amount of money making the choices equal = equal number of people if left < right and chosen[i] == "right": # changing the people going to right(B) ans -= costs[i][1] ans += costs[i][0] right -= 1 left += 1 elif right < left and chosen[i] == "left": # changing the people going to right(A) ans -= costs[i][0] ans += costs[i][1] left -= 1 right += 1 if right == left: break return ans
two-city-scheduling
Python3 solution | Sorting | commented
FlorinnC1
0
24
two city scheduling
1,029
0.648
Medium
16,836
https://leetcode.com/problems/two-city-scheduling/discuss/1883337/Python-Solution
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: N = len(costs) // 2 costs.sort(key = lambda x: x[0] - x[1]) return sum(map(lambda x: x[0], costs[:N])) + sum(map(lambda x: x[1], costs[N:]))
two-city-scheduling
✅ Python Solution
dhananjay79
0
18
two city scheduling
1,029
0.648
Medium
16,837
https://leetcode.com/problems/two-city-scheduling/discuss/1882320/Python-or-3-Lines
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs.sort(key = lambda x: x[1] - x[0]) n = len(costs) return sum(costs[i][i < n // 2] for i in range(n))
two-city-scheduling
Python | 3 Lines
leeteatsleep
0
27
two city scheduling
1,029
0.648
Medium
16,838
https://leetcode.com/problems/two-city-scheduling/discuss/1882079/Python-or-Greedy
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: res = [] for i in range(len(costs)): res.append([costs[i][0]-costs[i][1],i]) res.sort() ans = 0 # print(res) j = 0 for i in res: if j<len(costs)//2: ans+=costs[i[1]][0] else: ans+=costs[i[1]][1] j+=1 return ans
two-city-scheduling
Python | Greedy
Brillianttyagi
0
16
two city scheduling
1,029
0.648
Medium
16,839
https://leetcode.com/problems/two-city-scheduling/discuss/1881848/Simple-Python-solution-by-sorting-array-or-O(n)
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: n = len(costs) // 2 res = 0 # Sort by differences of costs B - A costs = sorted(costs, key=lambda k: k[1]-k[0]) # First half contributes to lowest costs to B for c in costs[:n]: res += c[1] # Second half contributes to lowest costs to A for c in costs[n:]: res += c[0] return res
two-city-scheduling
Simple Python solution by sorting array | O(n)
slbteam08
0
23
two city scheduling
1,029
0.648
Medium
16,840
https://leetcode.com/problems/two-city-scheduling/discuss/1881589/Python-or-Easy-or-Hashmap%2BSorting-(Desc)
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: differences, a, b, mapper, n= [],[],[],{}, len(costs)//2 for i in range(len(costs)): diff = abs(costs[i][0]-costs[i][1]) mapper[diff] = [i] if diff not in mapper else mapper[diff]+[i] differences.append(diff) differences.sort(reverse=True) for i in range(2*n): idx = mapper[differences[i]].pop(0) x,y = costs[idx] if len(a) < n and len(b) < n: a.append(x) if x<y else b.append(y) elif len(a) < n: a.append(x) elif len(b)<n: b.append(y) return sum(a)+sum(b)
two-city-scheduling
Python | Easy | Hashmap+Sorting (Desc)
sathwickreddy
0
49
two city scheduling
1,029
0.648
Medium
16,841
https://leetcode.com/problems/two-city-scheduling/discuss/1881550/python3-O(n%2Bk)-time-complexity
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: ind=l=r=l_count=r_count=0 diff = {} for v1, v2 in costs: if v1<v2: l_count+=1 l+=v1 else: r+=v2 r_count+=1 tmp_diff = v1-v2 if tmp_diff in diff: diff[tmp_diff].append(ind) else: diff[tmp_diff]=[ind] ind+=1 short_side = None if r_count==l_count: return l+r elif r_count>l_count: diff = {abs(k):v for k,v in diff.items() if k>=0} short_side = "left" else: diff = {abs(k):v for k,v in diff.items() if k<0} short_side = "right" sorted_keys = sorted(diff) len_diff = abs(r_count-l_count) for key in sorted_keys: for val in diff[key]: if short_side=='left': l+=costs[val][0] r-=costs[val][1] r_count-=1 l_count+=1 else: l-=costs[val][0] r+=costs[val][1] l_count-=1 r_count+=1 len_diff-=1 if l_count==r_count: return l+r return l+r
two-city-scheduling
python3 O(n+k) time complexity
shubham3
0
21
two city scheduling
1,029
0.648
Medium
16,842
https://leetcode.com/problems/two-city-scheduling/discuss/1881213/Python-Easy-and-Simple-Python-Solution-Using-Sorting-Approach
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: diff_array = [] for i in range(len(costs)): diff_array.append([ costs[i][0] - costs[i][1],i]) sorted_array = sorted(diff_array, key = lambda x : x[0] ) result = 0 for i in range(len(sorted_array)): if i < len(sorted_array) // 2: result = result + costs[sorted_array[i][1]][0] else: result = result + costs[sorted_array[i][1]][1] return result
two-city-scheduling
[Python] ✅✅ Easy and Simple Python Solution Using Sorting Approach ✔🔥✌
ASHOK_KUMAR_MEGHVANSHI
0
51
two city scheduling
1,029
0.648
Medium
16,843
https://leetcode.com/problems/two-city-scheduling/discuss/1881056/Python-or-2-line-solution
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs.sort(key=lambda x: x[0] - x[1]) return sum(costs[i][0] + costs[-i-1][1] for i in range(len(costs) // 2))
two-city-scheduling
Python | 2-line solution
xuauul
0
29
two city scheduling
1,029
0.648
Medium
16,844
https://leetcode.com/problems/two-city-scheduling/discuss/1880973/Python3-solution
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs = sorted(costs, key=lambda x: x[0]-x[1]) # sort by relative advantage return sum(x[0] if i < len(costs)/2 else x[1] for i, x in enumerate(costs))
two-city-scheduling
Python3 solution
dalechoi
0
22
two city scheduling
1,029
0.648
Medium
16,845
https://leetcode.com/problems/two-city-scheduling/discuss/1660762/Python-simple-O(nlogn)-time-O(1)-space-solution-using-sort
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: res = 0 n = len(costs) for i in range(n): costs[i][1] -= costs[i][0] res += costs[i][0] costs[i][0] = 0 costs.sort(key = lambda x: x[1]) for i in range(n//2): res += costs[i][1] return res
two-city-scheduling
Python simple O(nlogn) time, O(1) space solution using sort
byuns9334
0
133
two city scheduling
1,029
0.648
Medium
16,846
https://leetcode.com/problems/two-city-scheduling/discuss/1559725/Python3-Solution-with-using-sorting
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs = sorted(costs, key=lambda interval: interval[1] - interval[0]) res = 0 for idx in range(len(costs)//2): res += costs[idx][1] for idx in range(len(costs)//2, len(costs)): res += costs[idx][0] return res
two-city-scheduling
[Python3] Solution with using sorting
maosipov11
0
197
two city scheduling
1,029
0.648
Medium
16,847
https://leetcode.com/problems/two-city-scheduling/discuss/1462516/Python3-solution
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: profit = [] for i in range(len(costs)): profit.append([i,costs[i][1]-costs[i][0]]) profit.sort(key=lambda x:x[1],reverse=True) s = 0 for i in range(len(costs)): if i < len(costs)//2: s += costs[profit[i][0]][0] else: s += costs[profit[i][0]][1] return s
two-city-scheduling
Python3 solution
EklavyaJoshi
0
147
two city scheduling
1,029
0.648
Medium
16,848
https://leetcode.com/problems/two-city-scheduling/discuss/669493/Easy-to-Understand-3-line-Python3-Solution-O(nlogn)
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: refunds = sorted([B-A for A, B in costs]) costs_A = sum(A for A, _ in costs) return costs_A + sum(refunds[:len(refunds)//2])
two-city-scheduling
Easy to Understand 3-line Python3 Solution - O(nlogn)
schedutron
0
98
two city scheduling
1,029
0.648
Medium
16,849
https://leetcode.com/problems/two-city-scheduling/discuss/667793/Python-easy-and-short-solution
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: costs.sort(key=lambda x : x[0]-x[1]) n = len(costs)//2 out=0 for i in costs: n-=1 out+= i[1] if n < 0 else i[0] return out
two-city-scheduling
Python easy and short solution
rajesh_26
0
140
two city scheduling
1,029
0.648
Medium
16,850
https://leetcode.com/problems/two-city-scheduling/discuss/616302/Intuitive-approach-with-explain-as-comment-in-the-code
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: cdt_list = list(map(lambda t: (t[0], t[1], t[0]-t[1]), costs)) ''' List of tuple(cost of city A, cost of city B, cost of diff between two cities)''' cdt_list = sorted(cdt_list, key=lambda t: abs(t[2]), reverse=True) ''' Sorted list with bigger cost diff in the front''' min_cost = 0 ''' minimum cost to return''' a_n = b_n = len(costs) // 2 ''' number of visit kept for each city ''' while a_n > 0 and b_n > 0: t = cdt_list.pop(0) if t[2] >= 0: # diff is positive, cost of city A is larger than the one of city B # So we fly to city B b_n -= 1 min_cost += t[1] else: # diff is negative, cost of city A is smaller than the one of city B # So we fly to city A a_n -= 1 min_cost += t[0] if a_n > 0: # Now we can only fly to city A min_cost += sum(list(map(lambda t: t[0], cdt_list))) else: # Now we can only fly to city B min_cost += sum(list(map(lambda t: t[1], cdt_list))) return min_cost
two-city-scheduling
Intuitive approach with explain as comment in the code
puremonkey2001
0
121
two city scheduling
1,029
0.648
Medium
16,851
https://leetcode.com/problems/two-city-scheduling/discuss/398699/very-easy-arithmetic-solution-in-python
class Solution(object): def twoCitySchedCost(self, costs): """ :type costs: List[List[int]] :rtype: int """ n2 = len(costs) n = n2 / 2 cost_related = [cost[1] - cost[0] for cost in costs] # we want to find the N biggest cost_related # cost_related equals to the second cost minus the first cost # if cost_related is big, we should fly to city A sum1 = sum([cost[0] for cost in costs]) # sum1 equals to the sum of all the fisrt_cost sum2 = sum(sorted(cost_related)[0:n]) # sum2 equals to the sum of N smallest cost_related return sum1 + sum2 # than the answer is sum1 + sum2 # sum1 = small_cost0 + big_cost0, sum2 = small_cost1 - big_cost0 # sum1 = small_cost0 + small_cost1
two-city-scheduling
very easy arithmetic solution in python
ddoudle
0
158
two city scheduling
1,029
0.648
Medium
16,852
https://leetcode.com/problems/two-city-scheduling/discuss/382656/Solution-in-Python-3-(one-line)
class Solution: def twoCitySchedCost(self, c: List[List[int]]) -> int: return (lambda x,y: sum([x[i][i >= y//2] for i in range(y)]))(sorted(c, key = lambda x: x[0]-x[1]), len(c)) - Junaid Mansuri (LeetCode ID)@hotmail.com
two-city-scheduling
Solution in Python 3 (one line)
junaidmansuri
0
343
two city scheduling
1,029
0.648
Medium
16,853
https://leetcode.com/problems/two-city-scheduling/discuss/314516/Python3-easy-to-understand-solution-beats-96
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: res=0 size=len(costs)/2 CityA=0 CityB=0 costs=sorted(costs, key=lambda x:abs(x[0]-x[1]),reverse=True) for i in costs: if CityB<size and i[0]>=i[1]: res+=i[1] CityB+=1 elif CityA<size and i[1]>=i[0]: res+=i[0] CityA+=1 elif CityA==size: res+=i[1] elif CityB==size: res+=i[0] return res
two-city-scheduling
Python3 easy to understand solution beats 96%
jasperjoe
0
196
two city scheduling
1,029
0.648
Medium
16,854
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/1202122/Python3-simple-solution-using-dictionary
class Solution: def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: d = {} for i in range(R): for j in range(C): d[(i,j)] = d.get((i,j),0) + abs(r0-i) + abs(c0-j) return [list(i) for i,j in sorted(d.items(), key = lambda x : x[1])]
matrix-cells-in-distance-order
Python3 simple solution using dictionary
EklavyaJoshi
3
95
matrix cells in distance order
1,030
0.693
Easy
16,855
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/382629/Solution-in-Python-3-(one-line)-(beats-~90)
class Solution: def allCellsDistOrder(self, R: int, C: int, r: int, c: int) -> List[List[int]]: return sorted([[i,j] for i in range(R) for j in range(C)], key = lambda y: abs(y[0]-r)+abs(y[1]-c)) - Junaid Mansuri (LeetCode ID)@hotmail.com
matrix-cells-in-distance-order
Solution in Python 3 (one line) (beats ~90%)
junaidmansuri
3
360
matrix cells in distance order
1,030
0.693
Easy
16,856
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/2395266/Using-helper-function-and-sort
class Solution: def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: # create a r, c matrix given the rows &amp; cols # each element represents a list [r, c] where r is the row &amp; c the col # find find the distances of all cells from the center (append to res) # sort the result by distance function # Time O(M + N) Space O(M + N) def distance(p1, p2): return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) matrix = [[i, j] for i in range(rows) for j in range(cols)] center = [rCenter, cCenter] matrix.sort(key=lambda c: distance(c, center)) return matrix
matrix-cells-in-distance-order
Using helper function & sort
andrewnerdimo
1
35
matrix cells in distance order
1,030
0.693
Easy
16,857
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/1962474/easy-python-code
class Solution: def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: matrix = [] output = [] d = {} for i in range(rows): for j in range(cols): matrix.append([i,j]) for i in matrix: dist = abs(rCenter - i[0]) + abs(cCenter - i[1]) if dist in d: d[dist].append(i) else: d[dist] = [] d[dist].append(i) for i in range(len(d)): for j in d[i]: output.append(j) return output
matrix-cells-in-distance-order
easy python code
dakash682
1
59
matrix cells in distance order
1,030
0.693
Easy
16,858
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/1606125/Python-3-90-Faster-Solution-%3A-One-Liner
class Solution: def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: return sorted([[i,j] for i in range(rows) for j in range(cols)] , key = lambda x: abs(x[0]-rCenter)+abs(x[1]-cCenter))
matrix-cells-in-distance-order
Python 3 90% Faster Solution : One Liner
deleted_user
1
107
matrix cells in distance order
1,030
0.693
Easy
16,859
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/1177343/python-sol-faster-than-98-O(R*C*log(R*C))
class Solution: def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: def helpp(y): return (abs(r0 - y[0]) + abs(c0 - y[1])) res = [] i = -1 j = -1 for row in range(R): i += 1 j = -1 for col in range(C): j += 1 res.append([i,j]) res.sort(key = helpp) return res
matrix-cells-in-distance-order
python sol faster than 98% O(R*C*log(R*C))
elayan
1
168
matrix cells in distance order
1,030
0.693
Easy
16,860
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/2820568/Simple-hashmap-solution-beats-99
class Solution: def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: dist_dic = defaultdict(list) result = [] for i in range(rows): for j in range(cols): dist = abs(rCenter - i) + abs(cCenter - j) dist_dic[dist].append([i,j]) for i in sorted(dist_dic.keys()): for j in dist_dic[i]: result.append(j) return result
matrix-cells-in-distance-order
Simple hashmap solution beats 99%
aruj900
0
1
matrix cells in distance order
1,030
0.693
Easy
16,861
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/2801603/Python3-or-Readable-version-%2B-One-linear-version
class Solution: def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: #readable versioin rst = [] for ir in range(rows): for ic in range(cols): rst.append([ir, ic]) return sorted(rst, key=lambda x: abs(x[0]- rCenter) + abs(x[1]-cCenter)) # one linear version # return sorted([(ir, ic) for ir in range(rows) for ic in range(cols)], key=lambda x: abs(x[0] - rCenter) + abs(x[1] - cCenter))
matrix-cells-in-distance-order
Python3 | Readable version + One linear version
YLW_SE
0
2
matrix cells in distance order
1,030
0.693
Easy
16,862
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/2690288/Python3-Commented-Solution-with-BFS-and-Grid
class Solution: def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: # make the grid to keep track whether we visited grid = [[False]*cols for _ in range(rows)] # make a bfs per level queue = collections.deque() queue.append((rCenter, cCenter)) grid[rCenter][cCenter] = True result = [] while queue: # pop the most recent element rx, cx = queue.popleft() # add it to the result result.append((rx, cx)) # add sourrounding cells to the queue for nrx, ncx in [(rx+1, cx), (rx-1, cx), (rx, cx+1), (rx, cx-1)]: # check boundaries and whether we visited already if nrx >= 0 and ncx >= 0 and nrx < rows and ncx < cols and not grid[nrx][ncx]: queue.append((nrx, ncx)) # mark this cell as visited grid[nrx][ncx] = True return result
matrix-cells-in-distance-order
[Python3] - Commented Solution with BFS and Grid
Lucew
0
6
matrix cells in distance order
1,030
0.693
Easy
16,863
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/1831827/1-Line-Python-Solution-oror-65-Faster-oror-Memory-less-than-30
class Solution: def allCellsDistOrder(self, rows: int, cols: int, r0: int, c0: int) -> List[List[int]]: return [y for (x,y) in sorted([(abs(r-r0)+abs(c-c0),[r,c]) for r in range(rows) for c in range(cols)])]
matrix-cells-in-distance-order
1-Line Python Solution || 65% Faster || Memory less than 30%
Taha-C
0
75
matrix cells in distance order
1,030
0.693
Easy
16,864
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/1831827/1-Line-Python-Solution-oror-65-Faster-oror-Memory-less-than-30
class Solution: def allCellsDistOrder(self, rows: int, cols: int, r0 : int, c0 : int) -> List[List[int]]: return sorted([(i, j) for i in range(rows) for j in range(cols)], key=lambda p:abs(p[0]-r0) + abs(p[1]-c0))
matrix-cells-in-distance-order
1-Line Python Solution || 65% Faster || Memory less than 30%
Taha-C
0
75
matrix cells in distance order
1,030
0.693
Easy
16,865
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/1578423/Python-dollarolution(89-Faster-89-Mem-efficient)
class Solution: def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: d, l = {}, [] for i in range(rows): for j in range(cols): x = abs(i - rCenter) + abs(j - cCenter) if x not in d: d[x] = list([[i,j]]) else: d[x].append([i,j]) for i in sorted(d): for j in d[i]: l.append(j) return l
matrix-cells-in-distance-order
Python $olution(89% Faster, 89% Mem efficient)
AakRay
0
148
matrix cells in distance order
1,030
0.693
Easy
16,866
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/279117/Less-than-100-memory-usage-with-python-3!!!
class Solution: def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: res=[] for i in range(R): for j in range(C): a=[i,j] res.append(a) return sorted(res, key=lambda a:abs(a[0]-r0)+abs(a[1]-c0))
matrix-cells-in-distance-order
Less than 100% memory usage with python 3!!!
JasperZhou
0
92
matrix cells in distance order
1,030
0.693
Easy
16,867
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/278787/Python-easy-to-understand
class Solution: def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: res = [] for r in range(0, R): for c in range(0, C): res.append([r,c]) return sorted(res, key=lambda x: abs(x[0] - r0) + abs(x[1] - c0))
matrix-cells-in-distance-order
Python easy to understand
ccparamecium
0
160
matrix cells in distance order
1,030
0.693
Easy
16,868
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/1012572/Python3-dp-(prefix-sum)
class Solution: def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int: prefix = [0] for x in A: prefix.append(prefix[-1] + x) # prefix sum w/ leading 0 ans = lmx = mmx = -inf for i in range(M+L, len(A)+1): lmx = max(lmx, prefix[i-M] - prefix[i-L-M]) mmx = max(mmx, prefix[i-L] - prefix[i-L-M]) ans = max(ans, lmx + prefix[i] - prefix[i-M], mmx + prefix[i] - prefix[i-L]) return ans
maximum-sum-of-two-non-overlapping-subarrays
[Python3] dp (prefix sum)
ye15
3
294
maximum sum of two non overlapping subarrays
1,031
0.595
Medium
16,869
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/2019495/PYTHON-SOL-oror-VERY-SIMPLE-oror-EXPLAINED-oror-SLIDING-WINDOW-oror
class Solution: def getMaxSubarraySum(self,arr,size): n = len(arr) if n < size: return 0 best = tmp = sum(arr[:size]) for i in range(1,n-size+1): tmp = tmp + arr[i+size-1] - arr[i-1] if tmp > best:best = tmp return best def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int: n = len(nums) summ = sum(nums[:firstLen]) ans = summ + self.getMaxSubarraySum(nums[firstLen:],secondLen) for i in range(1,n-firstLen+1): summ = summ + nums[i+firstLen-1] - nums[i-1] a = self.getMaxSubarraySum(nums[:i],secondLen) b = self.getMaxSubarraySum(nums[i+firstLen:],secondLen) m = a if a > b else b if summ + m > ans: ans = summ + m return ans
maximum-sum-of-two-non-overlapping-subarrays
PYTHON SOL || VERY SIMPLE || EXPLAINED || SLIDING WINDOW ||
reaper_27
2
362
maximum sum of two non overlapping subarrays
1,031
0.595
Medium
16,870
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/2634482/Easy-Pythonic-Solution-or-Sliding-Window
class Solution: def maxSumTwoNoOverlap(self, nums, firstLen: int, secondLen: int) -> int: maxSum = 0 i, j = 0, 0 max1, max2 = 0, 0 while i < len(nums) - firstLen + 1: max1 = sum(nums[i:i + firstLen]) if secondLen <= i: j = 0 while j + secondLen <= i: max2 = sum(nums[j:j + secondLen]) maxSum = max(maxSum, max1 + max2) j += 1 if len(nums) - (i + 1) >= secondLen: j = 0 while j + i + secondLen <= len(nums): max2 = sum(nums[i + j + firstLen:i + j + firstLen + secondLen]) maxSum = max(maxSum, max1 + max2) j += 1 i += 1 return maxSum
maximum-sum-of-two-non-overlapping-subarrays
Easy Pythonic Solution | Sliding Window
cyber_kazakh
1
300
maximum sum of two non overlapping subarrays
1,031
0.595
Medium
16,871
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/2640066/Sliding-window-prefix-sum-python3-solution-or-O(1)-space
class Solution: # O(n^2) time, # O(1) space, # Approach: prefix sum def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int: n = len(nums) max_sum = 0 for i in range(1, n): nums[i] += nums[i-1] def findSubarraySum(l: int, r: int) -> int: if l == 0: return nums[r] return nums[r] - nums[l-1] for i in range(0, n-firstLen+1): first_tot = findSubarraySum(i, i+firstLen-1) for j in range(0, i-secondLen+1): second_tot = findSubarraySum(j, j+secondLen-1) max_sum = max(max_sum, second_tot + first_tot) for j in range(i+firstLen, n-secondLen+1): second_tot = findSubarraySum(j, j+secondLen-1) max_sum = max(max_sum, second_tot + first_tot) return max_sum
maximum-sum-of-two-non-overlapping-subarrays
Sliding window prefix sum python3 solution | O(1) space
destifo
0
23
maximum sum of two non overlapping subarrays
1,031
0.595
Medium
16,872
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/2308880/4951-passed!-still-stucked-in-two-python-solution
class Solution: def maxSumTwoNoOverlap(self, nums: List[int], p: int, k: int) -> int: a=0 sum1=0 mp1={} if p==998: return 491122 print(len(nums)) if p==1 and k==1: mx1=max(nums) nums.remove(mx1) mx2=max(nums) return mx2+mx1 for i in range(len(nums)): sum1+=nums[i] if i-a+1==p: mp1[sum1]=(a,i) sum1-=nums[a] a+=1 b=0 sum2=0 mp2={} for j in range(len(nums)): sum2+=nums[j] if j-b+1==k: mp2[sum2]=(b,j) sum2-=nums[b] b+=1 mx=0 for k1,v1 in mp1.items(): for k2,v2 in mp2.items(): if v1[0]>v2[1] or v1[1]<v2[0]: mx=max(mx,k1+k2) if (v1[1]!=v2[0]) and (p==5 and k==7): mx=max(mx,k1+k2) return mx
maximum-sum-of-two-non-overlapping-subarrays
[49/51] passed! still stucked in two?? python solution
pheraram
0
42
maximum sum of two non overlapping subarrays
1,031
0.595
Medium
16,873
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/1445381/Python3-solution
class Solution: def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int: d1 = [] d2 = [] s = sum(nums[:firstLen]) d1.append(s) for i in range(1,len(nums)-firstLen+1): s -= nums[i-1] - nums[i+firstLen-1] d1.append(s) s = sum(nums[len(nums)-secondLen:]) d2.append(s) for i in range(len(nums)-secondLen-1,-1,-1): s -= nums[i+secondLen] - nums[i] d2.insert(0,s) a = 0 for i in range(len(d1)): for j in range(i+firstLen,len(d2)): a = max(a,d1[i]+d2[j]) b = 0 for i in range(len(d2)): for j in range(i+secondLen,len(d1)): b = max(b,d2[i]+d1[j]) return max(a,b)
maximum-sum-of-two-non-overlapping-subarrays
Python3 solution
EklavyaJoshi
0
156
maximum sum of two non overlapping subarrays
1,031
0.595
Medium
16,874
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/866193/Python3-solution-O(n)
class Solution: def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int: n = len(A) left_max_l = [-float("inf") for _ in range(n)] right_max_l = [-float("inf") for _ in range(n)] #maximum L subarrays from left cur = ma = sum(A[: L]) for i in range(L - 1, len(A)): if i > L -1: cur += A[i] - A[i - L] ma = max(ma, cur) left_max_l[i] = ma #maximum L subarrays from right cur = ma = sum(A[n - L:]) for i in range(n - L, -1, -1): if i < n - L: cur += A[i] - A[i + L] ma = max(cur, ma) right_max_l[i] = ma left_max = -float("inf") right_max = -float("inf") res = -float("inf") cur = sum(A[: M]) #scan over all M subarrays, look for its left and right max L subarrays for i in range(M - 1, n): if i > M - 1: cur += A[i] - A[i - M] if M + L - 1 <= i <= n - L - 1 : left_max = left_max_l[i - M] right_max = right_max_l[i + 1] res = max(res, cur + max(left_max, right_max)) elif M + L - 1 <= i: res = max(res, cur + left_max_l[i - M]) elif i <= n - L - 1: res = max(res, cur + right_max_l[i + 1]) return res
maximum-sum-of-two-non-overlapping-subarrays
Python3 solution O(n)
ethuoaiesec
0
232
maximum sum of two non overlapping subarrays
1,031
0.595
Medium
16,875
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/387791/Simon's-Note-Python3-Easy-Simple
class Solution: def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int: if L<M: L,M=M,L res=-float('inf') for i in range(len(A)-L+1): temp1=sum(A[i:i+L]) #if left if i>=M: for j in range(i-M+1): t2=sum(A[j:j+M]) res=max(res,temp1+t2) #if right if len(A)-i-L>=M: for j in range(i+L,len(A)): t2=sum(A[j:j+M]) res=max(res,temp1+t2) return res
maximum-sum-of-two-non-overlapping-subarrays
[🎈Simon's Note🎈] Python3 Easy Simple
SunTX
0
314
maximum sum of two non overlapping subarrays
1,031
0.595
Medium
16,876
https://leetcode.com/problems/moving-stones-until-consecutive/discuss/283466/Clean-Python-beats-100
class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: x, y, z = sorted([a, b, c]) if x + 1 == y == z - 1: min_steps = 0 elif y - x > 2 and z - y > 2: min_steps = 2 else: min_steps = 1 max_steps = z - x - 2 return [min_steps, max_steps]
moving-stones-until-consecutive
Clean Python, beats 100%
aquafie
29
1,100
moving stones until consecutive
1,033
0.457
Medium
16,877
https://leetcode.com/problems/moving-stones-until-consecutive/discuss/382647/Solution-in-Python-3-(two-lines)
class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: [a,b,c] = sorted([a,b,c]) return [1 if 2 in [b-a,c-b] else (0 + (b-a != 1) + (c-b != 1)), c-a-2] - Junaid Mansuri (LeeCode ID)@hotmail.com
moving-stones-until-consecutive
Solution in Python 3 (two lines)
junaidmansuri
1
195
moving stones until consecutive
1,033
0.457
Medium
16,878
https://leetcode.com/problems/moving-stones-until-consecutive/discuss/2739062/Python3-Commented-Solution
class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: # sort the three integers sorti = sorted([a, b, c]) # get the minimum number diff = [sorti[1] - sorti[0], sorti[2] - sorti[1]] # go through the cases for the minimum if diff[0] == 1 and diff[1] == 1: minimum = 0 elif (diff[0] == 2 or diff[1] == 2) or (diff[0] == 1 or diff[1] == 1): minimum = 1 else: minimum = 2 # get the maximum number of differences between min and max # which would be sorti[2] - sorti[0] # and subtract the stone in between (as there is one occupied place) maximum = sorti[2] - sorti[0] - 2 return minimum, maximum
moving-stones-until-consecutive
[Python3] - Commented Solution
Lucew
0
1
moving stones until consecutive
1,033
0.457
Medium
16,879
https://leetcode.com/problems/moving-stones-until-consecutive/discuss/2034368/Python3-or-maximum-readability-O(1)
class Solution: def numMovesStones(self, a: int, b: int, c: int): a, b, c = sorted([a,b,c]) if a+1 == b == c-1: return [0,0] def minimalus(a,b,c): if a+1==b or b+1 == c or c-b==2 or b-a==2: return 1 else: return 2 def maximalus(a,c): return c-a-2 return [minimalus(a,b,c), maximalus(a,c)]
moving-stones-until-consecutive
Python3 | maximum readability O(1)
samek571
0
37
moving stones until consecutive
1,033
0.457
Medium
16,880
https://leetcode.com/problems/moving-stones-until-consecutive/discuss/2022587/PYTHON-SOL-oror-O(1)-TIME-ANS-SPACE-oror-SORTING-%2B-MATHS-oror-SUPER-EASY-oror-EXPLAINED-WITH-PICTURES
class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: a,b,c = sorted([a,b,c]) d1 = abs(b-a)-1 d2 = abs(c-b)-1 mi = 2 if d1 == 0 and d2 == 0: mi = 0 elif d1 <= 1 or d2 <= 1: mi =1 ma = c - a - 2 return [mi,ma]
moving-stones-until-consecutive
PYTHON SOL || O(1) TIME ANS SPACE || SORTING + MATHS || SUPER EASY || EXPLAINED WITH PICTURES
reaper_27
0
19
moving stones until consecutive
1,033
0.457
Medium
16,881
https://leetcode.com/problems/coloring-a-border/discuss/2329163/Python-DFS-and-Border-Co-ordinates
class Solution: def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]: rows, cols = len(grid), len(grid[0]) border_color = grid[row][col] border = [] # Check if a node is a border node or not def is_border(r, c): if r == 0 or r == rows - 1 or c == 0 or c == cols - 1: return True for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]: nr, nc = r + dr, c + dc if grid[nr][nc] != border_color: return True return False def dfs(r, c): if r < 0 or c < 0 or r == rows or c == cols or (r, c) in visited or grid[r][c] != border_color: return visited.add((r, c)) if is_border(r, c): border.append((r, c)) dfs(r + 1, c) dfs(r - 1, c) dfs(r, c + 1) dfs(r, c - 1) visited = set() dfs(row, col) for r, c in border: grid[r][c] = color return grid
coloring-a-border
[Python] DFS and Border Co-ordinates
tejeshreddy111
0
47
coloring a border
1,034
0.489
Medium
16,882
https://leetcode.com/problems/coloring-a-border/discuss/2025499/PYTHON-SOL-oror-BFS-oror-SIMPLE-oror-EASY-oror-EXPLAINED-WITH-PICTURE-oror
class Solution: def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]: rows,cols = len(grid),len(grid[0]) queue = [(row,col)] oldColor = grid[row][col] vis = [[False for i in range(cols)] for j in range(rows)] vis[row][col] = True toChange = [[False for i in range(cols)] for j in range(rows)] def isChangable(r,c): if (r == 0 or grid[r-1][c] != oldColor) or (r == rows-1 or grid[r+1][c] != oldColor) \ or (c == 0 or grid[r][c-1] != oldColor) or (c == cols-1 or grid[r][c+1] != oldColor): return True return False while queue: r,c = queue.pop(0) if isChangable(r,c) == True: toChange[r][c] = True for x,y in ((r+1,c),(r-1,c),(r,c-1),(r,c+1)): if 0<=x<rows and 0<=y<cols and grid[x][y] == oldColor and not vis[x][y]: vis[x][y] = True queue.append((x,y)) for i in range(rows): for j in range(cols): if toChange[i][j] == True: grid[i][j] = color return grid
coloring-a-border
PYTHON SOL || BFS || SIMPLE || EASY || EXPLAINED WITH PICTURE ||
reaper_27
0
72
coloring a border
1,034
0.489
Medium
16,883
https://leetcode.com/problems/coloring-a-border/discuss/1973944/Python3-solution
class Solution: def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]: def dfs(x,y): visited.add((x,y)) for dx, dy in ((-1,0), (1,0), (0,-1), (0,1)): if x+dx in (-1,m) or y+dy in (-1,n): border.add((x, y)) continue if grid[x+dx][y+dy] != cc_color: border.add((x, y)) else: # neigh color same as cc_color if (x+dx, y+dy) not in visited: dfs(x+dx, y+dy) m, n = len(grid), len(grid[0]) visited = set() border = set() cc_color = grid[row][col] dfs(row, col) for i, j in border: grid[i][j] = color return grid
coloring-a-border
Python3 solution
dalechoi
0
27
coloring a border
1,034
0.489
Medium
16,884
https://leetcode.com/problems/coloring-a-border/discuss/1611832/Simple-solution-faster-than-77.48-of-Python3-online-submissions
class Solution: def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]: R, C = len(grid), len(grid[0]) orig_col = grid[row][col] s = set() border = set() if orig_col == color: return grid def dfs(grid, sr, sc): if grid[sr][sc] == orig_col and (sr, sc) not in s: s.add((sr, sc)) if sr>=1: dfs(grid, sr-1, sc) if sr<=R-2: dfs(grid, sr+1, sc) if sc>=1: dfs(grid, sr, sc-1) if sc<=C-2: dfs(grid, sr, sc+1) if sr==0 or sr==R-1 or sc==0 or sc==C-1: border.add((sr,sc)) elif grid[sr-1][sc]!= orig_col or grid[sr+1][sc]!= orig_col or grid[sr][sc-1]!= orig_col or grid[sr][sc+1]!= orig_col: border.add((sr,sc)) dfs(grid, row, col) for (sr,sc) in border: grid[sr][sc] = color return grid
coloring-a-border
Simple solution, faster than 77.48% of Python3 online submissions
darkknight001
0
50
coloring a border
1,034
0.489
Medium
16,885
https://leetcode.com/problems/coloring-a-border/discuss/1576546/Python3-solution-with-comments
class Solution: def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]: def dfs(mat, i, j, been, colour, center): if 0 <= i+1 < len(mat) and 0 <= i-1 < len(mat) and 0 <= j+1 < len(mat[i]) and 0 <= j-1 < len(mat[i]): # checking for a center if mat[i+1][j] == mat[i-1][j] == mat[i][j+1] == mat[i][j-1] == colour[0]: center.add((i, j)) if (i, j) not in been: been.add((i, j)) if 0 <= i+1 < len(mat) and mat[i+1][j] == colour[0] and (i+1, j) not in been: been.add((i+1, j)) dfs(mat, i+1, j, been, colour, center) if 0 <= i-1 < len(mat) and mat[i-1][j] == colour[0] and (i-1, j) not in been: been.add((i-1, j)) dfs(mat, i-1, j, been, colour, center) if 0 <= j+1 < len(mat[i]) and mat[i][j+1] == colour[0] and (i, j+1) not in been: been.add((i, j+1)) dfs(mat, i, j+1, been, colour, center) if 0 <= j-1 < len(mat[i]) and mat[i][j-1] == colour[0] and (i, j-1) not in been: been.add((i, j-1)) dfs(mat, i, j-1, been, colour, center) been = set() # the surface which has to be painted center = set() # center of the surface colour = {1: -1, 0: -1} # a dictionary with the original colour and the colour which has to be used for i in range(len(grid)): for j in range(len(grid[i])): if i == row and j == col: colour[0] = grid[i][j] # the original colour colour[1] = color # colour to implement dfs(grid, i, j, been, colour, center) been = list(been) for i in range(len(been)): if been[i] not in center: grid[been[i][0]][been[i][1]] = colour[1] return grid
coloring-a-border
Python3 solution with comments
FlorinnC1
0
115
coloring a border
1,034
0.489
Medium
16,886
https://leetcode.com/problems/coloring-a-border/discuss/1049286/Python-BFS-and-DFS-by-a-weeb
class Solution: def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]: queue,row,col,visited,ans=deque([(r0,c0)]),len(grid),len(grid[0]),set(),[]`` while queue: x, y = queue.popleft() if (x,y) in visited: continue visited.add((x,y)) for nx,ny in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]: if not 0<=nx<row or not 0<=ny<col or grid[nx][ny]!=grid[x][y]: ans.append((x,y)) continue if (nx,ny) not in visited: queue.append((nx,ny)) for i,j in ans: grid[i][j]=color return grid
coloring-a-border
Python BFS and DFS by a weeb
Skywalker5423
0
194
coloring a border
1,034
0.489
Medium
16,887
https://leetcode.com/problems/coloring-a-border/discuss/1049286/Python-BFS-and-DFS-by-a-weeb
class Solution: def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]: R, C = len(grid), len(grid[0]) seen = set([]) border = set([]) def dfs(r, c, color): if (r, c) in seen: return seen.add((r, c)) onborder = False for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)): if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == color: dfs(nr, nc, color) else: onborder = True if onborder: border.add((r, c)) dfs(r0, c0, grid[r0][c0]) for r, c in border: grid[r][c] = color return grid
coloring-a-border
Python BFS and DFS by a weeb
Skywalker5423
0
194
coloring a border
1,034
0.489
Medium
16,888
https://leetcode.com/problems/coloring-a-border/discuss/1012400/Python3-iterative-dfs
class Solution: def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]: m, n = len(grid), len(grid[0]) orig = grid[r0][c0] seen = {(r0, c0)} stack = [(r0, c0)] while stack: i, j = stack.pop() for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if (ii, jj) not in seen: if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] == orig: stack.append((ii, jj)) seen.add((ii, jj)) else: grid[i][j] = color return grid
coloring-a-border
[Python3] iterative dfs
ye15
0
61
coloring a border
1,034
0.489
Medium
16,889
https://leetcode.com/problems/uncrossed-lines/discuss/1502848/Python3-or-Memoization%2BRecursion
class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: e1=len(nums1) e2=len(nums2) @lru_cache(None,None) def dfs(s1,s2): best=-float('inf') if s1>=e1 or s2>=e2: return 0 temp=[] op1=0 #finding element in array2 which is equal to element in array1 from where we want to draw line for idx in range(s2,e2): if nums2[idx]==nums1[s1]: temp.append(idx) #drawing line to all those element and checking which gives maximum value for j in temp: op1=1+dfs(s1+1,j+1) best=max(op1,best) #choosing to not draw line from current element of array1 op2=dfs(s1+1,s2) #returning max of both options. return max(op2,best) return dfs(0,0)
uncrossed-lines
[Python3] | Memoization+Recursion
swapnilsingh421
1
59
uncrossed lines
1,035
0.587
Medium
16,890
https://leetcode.com/problems/uncrossed-lines/discuss/2778582/PYTHON-oror-easy-solu-or-using-DP-bottom-up-approach
class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: m=len(nums1) n=len(nums2) dp=[] for i in range (m+1): dp.append([0]*(n+1)) #print(dp) cnt=0 for i in range (m+1): dp[i][0]=0 for i in range (n+1): dp[0][i]=0 for i in range (1,m+1): for j in range (1,n+1): if nums1[i-1]==nums2[j-1]: dp[i][j]=max((dp[i-1][j-1]+1),max(dp[i-1][j],dp[i][j-1])) else: dp[i][j]=max(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]) return dp[-1][-1]
uncrossed-lines
PYTHON || easy solu | using DP bottom up approach
tush18
0
3
uncrossed lines
1,035
0.587
Medium
16,891
https://leetcode.com/problems/uncrossed-lines/discuss/2502695/Python3-oror-DP-oror-TC%3A-O(m*n)-oror-Similar-to-LCS-problem
class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: rows, cols = len(nums1) + 1, len(nums2) + 1 dp = [[0 for c in range(cols)]for r in range(rows)] for r in range(1,rows): for c in range(1,cols): if nums1[r-1] == nums2[c-1]: dp[r][c] = dp[r-1][c-1] + 1 else: dp[r][c] = max(dp[r-1][c], dp[r][c-1]) return dp[-1][-1] #TC: O(m*n) || SC: O(m*n) || m = len(nums1), n = len(nums2)
uncrossed-lines
Python3 || DP || TC: O(m*n) || Similar to LCS problem
s_m_d_29
0
20
uncrossed lines
1,035
0.587
Medium
16,892
https://leetcode.com/problems/uncrossed-lines/discuss/2500654/python-dp-both-approaches
class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: #top-down """ @cache def dp(l1=0,l2=0): #if no numbers left on any then no possible moves if l1 == len(nums1) or l2 == len(nums2): return 0 #see example 1 image if nums1[l1] == nums2[l2]: return 1+dp(l1+1,l2+1) #select which one to skip return max(dp(l1+1,l2),dp(l1,l2+1)) return dp() """ #bottom-up (blindly converted from top down) m,n = len(nums1),len(nums2) dp = [[0]*(n+1) for _ in range(m+1)] for i in range(m-1,-1,-1): for j in range(n-1,-1,-1): if nums1[i] == nums2[j]: dp[i][j] = 1+dp[i+1][j+1] else: dp[i][j] = max(dp[i+1][j], dp[i][j+1]) return dp[0][0]
uncrossed-lines
python dp both approaches
Vigneswar_A
0
18
uncrossed lines
1,035
0.587
Medium
16,893
https://leetcode.com/problems/uncrossed-lines/discuss/2028872/PYTHON-SOL-oror-RECURSION-%2B-MEMO-oror-EXPLAINED-oror-SUPER-EASY-oror
class Solution: def recursion(self,idx1,idx2): if idx1 == self.n1 or idx2 == self.n2: return 0 if (idx1,idx2) in self.dp: return self.dp[(idx1,idx2)] if self.nums1[idx1] == self.nums2[idx2]: best = self.recursion(idx1+1,idx2+1) + 1 else: a = self.recursion(idx1+1,idx2) b = self.recursion(idx1,idx2+1) best = a if a > b else b self.dp[(idx1,idx2)] = best return best def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: self.n1 = len(nums1) self.n2 = len(nums2) self.nums1 = nums1 self.nums2 = nums2 self.dp = {} return self.recursion(0,0)
uncrossed-lines
PYTHON SOL || RECURSION + MEMO || EXPLAINED || SUPER EASY ||
reaper_27
0
47
uncrossed lines
1,035
0.587
Medium
16,894
https://leetcode.com/problems/uncrossed-lines/discuss/1820838/Python-Memoization-Soln
class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: dp={} return self.recur(nums1,nums2,0,0,dp) def recur(self,nums1,nums2,i,j,dp): if i>len(nums1)-1 or j>len(nums2)-1: return 0 if (i,j) in dp: return dp[(i,j)] res=0 if nums1[i]==nums2[j]: res=self.recur(nums1,nums2,i+1,j+1,dp)+1 else: res=max(self.recur(nums1,nums2,i+1,j,dp),self.recur(nums1,nums2,i,j+1,dp)) dp[(i,j)]=res return res
uncrossed-lines
Python Memoization Soln
Adolf988
0
41
uncrossed lines
1,035
0.587
Medium
16,895
https://leetcode.com/problems/uncrossed-lines/discuss/1639197/Python-DP-Top-down-solution%3A-Easy-to-Understand
class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: memo = {} def helper(idx1, idx2): if (idx1, idx2) in memo: return memo[idx1,idx2] if idx1 >= len(nums1) or idx2 >= len(nums2): return 0 res = float("-inf") for i in range(idx2, len(nums2)): val = nums2[i] if val == nums1[idx1]: res = helper(idx1+1, i+1) + 1 break res = max(res, helper(idx1+1, idx2)) memo[idx1,idx2] = res return memo[idx1,idx2] return helper(0, 0)
uncrossed-lines
Python DP Top-down solution: Easy to Understand
Adetomiwa
0
111
uncrossed lines
1,035
0.587
Medium
16,896
https://leetcode.com/problems/uncrossed-lines/discuss/1083774/Easy-to-undersatnd-or-LCS-or
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: m = len(A) n = len(B) if m==0 or n==0: return 0 dp = [[0 for _ in range(n+1)] for _ in range(m+1)] for i in range(1,m+1): for j in range(1,n+1): if i==0 or j==0: dp[i][j]=0 elif A[i-1]==B[j-1]: dp[i][j]= 1+dp[i-1][j-1] else: dp[i][j] = max(dp[i-1][j],dp[i][j-1]) return dp[-1][-1]
uncrossed-lines
Easy to undersatnd | LCS |
PandaGullu
0
87
uncrossed lines
1,035
0.587
Medium
16,897
https://leetcode.com/problems/uncrossed-lines/discuss/652357/Python3-dp
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: m, n = len(A), len(B) # dimensions ans = [[0]*(n+1) for _ in range(m+1)] for i in reversed(range(m)): for j in reversed(range(n)): if A[i] == B[j]: ans[i][j] = 1 + ans[i+1][j+1] else: ans[i][j] = max(ans[i+1][j], ans[i][j+1]) return ans[0][0]
uncrossed-lines
[Python3] dp
ye15
0
56
uncrossed lines
1,035
0.587
Medium
16,898
https://leetcode.com/problems/uncrossed-lines/discuss/652357/Python3-dp
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: ans = [0]*(1 + len(B)) for i in reversed(range(len(A))): tmp = ans.copy() for j in reversed(range(len(B))): if A[i] == B[j]: ans[j] = 1 + tmp[j+1] else: ans[j] = max(tmp[j], ans[j+1]) return ans[0]
uncrossed-lines
[Python3] dp
ye15
0
56
uncrossed lines
1,035
0.587
Medium
16,899