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/make-array-zero-by-subtracting-equal-amounts/discuss/2790265/Python-3-Solution
class Solution: def minimumOperations(self, nums: List[int]) -> int: if 0 in nums: return len(set(nums)) - 1 return len(set(nums))
make-array-zero-by-subtracting-equal-amounts
Python 3 Solution
mati44
0
4
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,300
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2789370/One-line-python-solution
class Solution(object): def minimumOperations(self, nums): """ :type nums: List[int] :rtype: int """ return len({i for i in nums if i != 0})
make-array-zero-by-subtracting-equal-amounts
One-line python solution
csgogogo9527
0
3
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,301
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2786349/Python-easy-solution-for-beginners-using-set
class Solution: def minimumOperations(self, nums: List[int]) -> int: s = set() for num in nums: if num > 0: s.add(num) return len(s)
make-array-zero-by-subtracting-equal-amounts
Python easy solution for beginners using set
AeRajya
0
7
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,302
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2784438/Best-Easy-Approach-oror-96.1-Acceptance-oror-TC-O(N)
class Solution: def minimumOperations(self, nums: List[int]) -> int: a=set(nums) a=list(a) if 0 in a: a.remove(0) return (len(a)) return len(a)
make-array-zero-by-subtracting-equal-amounts
Best Easy Approach || 96.1% Acceptance || TC O(N)
Kaustubhmishra
0
9
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,303
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2706377/The-answer-is-same-as-number-of-distinct-values-which-greater-0.
class Solution: def minimumOperations(self, nums: List[int]) -> int: """ The answer is same as number of distinct values which > 0, because same numbers will be subtracted at the same time. TC: O(n) SC: O(n) """ distinct_values_greater_than_0 = set(nums) - {0} return len(distinct_values_greater_than_0) """ Testcases: 1. import random # Generate 50 random numbers between 0 and 100 random_list = random.sample(range(0, 101), 50) 2. random_list1 + random_list2 """
make-array-zero-by-subtracting-equal-amounts
The answer is same as number of distinct values which > 0.
woora3
0
8
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,304
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2659739/Done-using-pure-coding
class Solution: def minimumOperations(self, nums: List[int]) -> int: counter=0 while max(nums)!=0: arr=[] m=max(nums) print(m) for i in range(len(nums)-1): for j in range(1,len(nums)): if nums[j]>=nums[i] and nums[i]<m and nums[i]>0: m=nums[i] elif nums[i]>=nums[j] and nums[j]<m and nums[j]>0: m=nums[j] print(m) for i in nums: if i-m<=0: arr.append(0) else: arr.append(i-m) print(arr) nums=arr counter+=1 return counter
make-array-zero-by-subtracting-equal-amounts
Done using pure coding
prashantdahiya711
0
22
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,305
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2652227/Python3-Beats-98
class Solution: def minimumOperations(self, nums: List[int]) -> int: nums.sort() t = 0 while True: while nums and nums[0]==0: del nums[0] if len(nums)==0: return t t+=1 v = nums[0] nums = [i-v for i in nums]
make-array-zero-by-subtracting-equal-amounts
Python3 Beats 98%
godshiva
0
13
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,306
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2651201/Python-Solution-oror-98.99-faster-oror-simple-to-understand
class Solution: def minimumOperations(self, nums: List[int]) -> int: val = list(filter(lambda x: (x >0), nums)) val = set(val) return len(val)
make-array-zero-by-subtracting-equal-amounts
Python Solution || 98.99 faster || simple to understand
kartik_5051
0
8
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,307
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2559765/94.84-faster-python-solution-no-for-loops-used-set!
class Solution: def minimumOperations(self, nums: List[int]) -> int: set_nums = set(nums) if len(nums) == 1 and 0 in set_nums: return 0 elif 0 in set_nums: set_nums.remove(0) return len(set_nums) else: return len(set_nums)
make-array-zero-by-subtracting-equal-amounts
94.84% faster python solution, no for loops, used set!
samanehghafouri
0
18
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,308
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2522312/Simple-python-solution
class Solution: def minimumOperations(self, nums: List[int]) -> int: while 0 in nums: nums.remove(0) return len(list(set(nums)))
make-array-zero-by-subtracting-equal-amounts
Simple python solution
aruj900
0
72
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,309
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2503816/Python-Simple-Python-Solution-or-2-Ways
class Solution: def minimumOperations(self, nums: List[int]) -> int: return len(set(nums) - {0})
make-array-zero-by-subtracting-equal-amounts
[ Python ] ✔✔ Simple Python Solution | 2 Ways 🔥✌
divyamohan123
0
54
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,310
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2489762/Two-Liner-Python-Solution-O(n)
class Solution: def minimumOperations(self, nums: List[int]) -> int: nums = set(nums) return len(nums) if 0 not in nums else len(nums)-1
make-array-zero-by-subtracting-equal-amounts
Two Liner Python Solution O(n)
_jorjis
0
39
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,311
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2394416/Python-3-solution
class Solution: def minimumOperations(self, nums: List[int]) -> int: nums = list(set(nums)) if (nums[0] == 0): return len(nums) - 1 return len(nums)
make-array-zero-by-subtracting-equal-amounts
Python 3 solution
srikomm
0
57
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,312
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2393429/Easy-and-Clear-Python3-Solution
class Solution: def minimumOperations(self, nums: List[int]) -> int: nums = [value for value in nums if value != 0] s = set(nums) return len(s)
make-array-zero-by-subtracting-equal-amounts
Easy & Clear Python3 Solution
moazmar
0
29
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,313
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2367218/Easy-python-priority-queue-%2B-number-of-different-positives
class Solution: def minimumOperations(self, nums: List[int]) -> int: heapify(nums) count=0 max_=max(nums) last=0 #sum of last subtracted elements while nums: x1=heappop(nums)-last #sum of last elements will be subtracted each time while (x1==0) and nums: #iterate till we have a positive integer x1=heappop(nums)-last if x1>0: max_-=x1 last+=x1 count+=1 #number of rounds taken if max_<=0: return count return count
make-array-zero-by-subtracting-equal-amounts
Easy python priority queue + number of different positives
sunakshi132
0
29
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,314
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2367218/Easy-python-priority-queue-%2B-number-of-different-positives
class Solution: def minimumOperations(self, nums: List[int]) -> int: return len(set(nums) - {0})
make-array-zero-by-subtracting-equal-amounts
Easy python priority queue + number of different positives
sunakshi132
0
29
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,315
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2361892/Python-Javascript-without-set
class Solution: def minimumOperations(self, nums: List[int]) -> int: min = float('inf') for num in nums: if num > 0 and num < min: min = num if min == float('inf'): return 0 counter = 0 while True: counter += 1 newMin = float('inf') for i in range(len(nums)): if nums[i] > 0: nums[i] -= min if nums[i] > 0 and nums[i] < newMin: newMin = nums[i] if newMin == float('inf'): break min = newMin return counter
make-array-zero-by-subtracting-equal-amounts
Python / Javascript without set
ChaseDho
0
36
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,316
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2359682/Python-Easy-Solution
class Solution: def minimumOperations(self, nums: List[int]) -> int: nums.sort() count = 0 i = 0 while (max(nums) > 0): if nums[i] <= 0: i += 1 if nums[i] != 0: count += 1 nums = [a - nums[i] for a in nums] return count
make-array-zero-by-subtracting-equal-amounts
Python Easy Solution
YangJenHao
0
13
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,317
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2359232/Python-simple-solution
class Solution: def minimumOperations(self, nums: List[int]) -> int: return len({x for x in nums if x})
make-array-zero-by-subtracting-equal-amounts
Python simple solution
StikS32
0
22
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,318
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2358396/Python-Clean-Code-Solution%3A-Make-Array-Zero-by-Subracting-Equal-Amounts
class Solution: def minimumOperations(self, nums: List[int]) -> int: minOperations = 0 tempList = nums[:] while not isAllElementsZero(tempList): minElement = getMinNonZeroElement(tempList) minOperations += 1 for j in range(len(tempList)): if tempList[j] != 0: tempList[j] -= minElement else: continue return minOperations def isAllElementsZero(nums): for element in nums: if element != 0 : return False return True def getMinNonZeroElement(nums): minElem = float('inf') for element in nums: if element != 0 and element < minElem: minElem = element else: continue return minElem
make-array-zero-by-subtracting-equal-amounts
Python Clean Code Solution: Make Array Zero by Subracting Equal Amounts
Nab110
0
10
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,319
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2358188/Python-or-1-Liner-or-Set-Cardinality
class Solution: def minimumOperations(self, nums: List[int]) -> int: return len(set(nums) - {0})
make-array-zero-by-subtracting-equal-amounts
Python | 1 Liner | Set Cardinality
leeteatsleep
0
7
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,320
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2358135/Python-Very-simple-solution-with-set
class Solution: def minimumOperations(self, nums: List[int]) -> int: ## RC ## un = set() for num in nums: if num: un.add(num) return len(un)
make-array-zero-by-subtracting-equal-amounts
[Python] Very simple solution with set
101leetcode
0
15
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,321
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2358012/Python-Count-Unique-Number
class Solution: def minimumOperations(self, nums: List[int]) -> int: return len(set(nums)) - (0 in nums)
make-array-zero-by-subtracting-equal-amounts
[Python] Count Unique Number
sodinfeliz
0
11
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,322
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2357815/Python-Simple-Python-Solution
class Solution: def minimumOperations(self, nums: List[int]) -> int: result = 0 while True: if nums.count(0) == len(nums): break min_value = 100000 for num in nums: if num < min_value and num != 0: min_value = num for i in range(len(nums)): if nums[i] >= min_value: nums[i] = nums[i] - min_value result = result + 1 return result
make-array-zero-by-subtracting-equal-amounts
[ Python ] ✅✅ Simple Python Solution 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
44
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,323
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2357727/easy-python-solution
class Solution: def minimumOperations(self, nums: List[int]) -> int: nums.sort() count = 0 while nums.count(0) != len(nums) : count += 1 nums.sort() flag, min_num = True, 0 for i in range(len(nums)) : if (nums[i] != 0) and flag : min_num = nums[i] flag = False nums[i] -= min_num return count
make-array-zero-by-subtracting-equal-amounts
easy python solution
sghorai
0
66
make array zero by subtracting equal amounts
2,357
0.727
Easy
32,324
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2358259/Python-oror-Math-oror-Two-Easy-Approaches
class Solution: def maximumGroups(self, grades: List[int]) -> int: x = len(grades) n = 0.5 * ((8 * x + 1) ** 0.5 - 1) ans = int(n) return ans
maximum-number-of-groups-entering-a-competition
✅Python || Math || Two Easy Approaches
chuhonghao01
4
155
maximum number of groups entering a competition
2,358
0.675
Medium
32,325
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2358259/Python-oror-Math-oror-Two-Easy-Approaches
class Solution: def maximumGroups(self, grades: List[int]) -> int: sortedGrades = sorted(grades) groupNums = 0 total = 0 while total <= len(sortedGrades): groupNums += 1 total += groupNums return groupNums - 1
maximum-number-of-groups-entering-a-competition
✅Python || Math || Two Easy Approaches
chuhonghao01
4
155
maximum number of groups entering a competition
2,358
0.675
Medium
32,326
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2357724/Simple-Greedy-with-Explanation
class Solution: def maximumGroups(self, g: List[int]) -> int: n = len(g) g.sort() curr_group = 1 curr_group_sum = 0 idx = 0 count = 0 while idx < n: # We don't have enough elements to put in the next group, let's put them in the current group and return. if n - idx < curr_group: return count # Calculate the next group sum. next_group_sum = 0 c = 0 while c < curr_group: next_group_sum += g[idx] idx += 1 c += 1 # If the next group sum is not enough, put the remaining elements in the current group and return early. if next_group_sum <= curr_group_sum: return count count += 1 curr_group_sum = next_group_sum curr_group += 1 return count
maximum-number-of-groups-entering-a-competition
Simple Greedy with Explanation
wickedmishra
2
99
maximum number of groups entering a competition
2,358
0.675
Medium
32,327
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2671078/Python-3-O(N)
class Solution: def maximumGroups(self, grades: List[int]) -> int: n=len(grades) k=0 while n>=k+1: k+=1 n-=k return k
maximum-number-of-groups-entering-a-competition
Python 3 O(N)
Sneh713
1
19
maximum number of groups entering a competition
2,358
0.675
Medium
32,328
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2360455/Python3-or-Linear-Traversal-with-Sorting
class Solution: def maximumGroups(self, grades: List[int]) -> int: #we can solve by traversing linearly using one pointer! pointer = 0 prev_sum, prev_size = 0,0 cur_sum, cur_size = 0,0 ans = 0 #we have to make sure array is sorted in ascending order though! grades.sort() #as long as pointer is not out of bounds! while pointer < len(grades): #process current right element! cur_sum += grades[pointer] cur_size += 1 #we formed a new group if(cur_sum > prev_sum and cur_size > prev_size): ans += 1 prev_sum, prev_size = cur_sum, cur_size cur_sum, cur_size = 0, 0 pointer += 1 continue pointer += 1 return ans
maximum-number-of-groups-entering-a-competition
Python3 | Linear Traversal with Sorting
JOON1234
1
9
maximum number of groups entering a competition
2,358
0.675
Medium
32,329
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2803349/Python-One-line-O(1)-without-loop
class Solution: def maximumGroups(self, grades: List[int]) -> int: return int(math.sqrt(2 * len(grades) + 0.25) - 0.5)
maximum-number-of-groups-entering-a-competition
[Python] One line O(1) without loop
huangweijing
0
2
maximum number of groups entering a competition
2,358
0.675
Medium
32,330
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2384730/python-3-or-one-line-O(1)-time-O(1)-space
class Solution: def maximumGroups(self, grades: List[int]) -> int: return (-1 + int(math.sqrt(1 + 8*len(grades)))) // 2
maximum-number-of-groups-entering-a-competition
python 3 | one line, O(1) time, O(1) space
dereky4
0
65
maximum number of groups entering a competition
2,358
0.675
Medium
32,331
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2358055/Python-solution-with-explanation
class Solution: def maximumGroups(self, grades: List[int]) -> int: n=len(grades) t=0 g=0 count=2 while(t<n): t+=count g+=1 count+=1 return g
maximum-number-of-groups-entering-a-competition
Python solution with explanation
saurabhvarade0903
0
18
maximum number of groups entering a competition
2,358
0.675
Medium
32,332
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2357783/easy-python-solution-using-dict
class Solution: def maximumGroups(self, grades: List[int]) -> int: if len(grades) <= 2 : return 1 else : grades.sort() dict_group ={} group_len = 1 i = 0 end = 0 while end < len(grades) : start, end = i, i + group_len # if end >= len(grades) : # break if group_len != 1 : if (sum(grades[start: end]) > sum(dict_group[group_len - 1])) and (len(grades[start: end]) == (end - start)) : # print(start, end) dict_group[group_len] = grades[start: end] else : return len(dict_group) else : dict_group[group_len] = grades[start: end] group_len += 1 i = end # print(dict_group) return len(dict_group)
maximum-number-of-groups-entering-a-competition
easy python solution using dict
sghorai
0
9
maximum number of groups entering a competition
2,358
0.675
Medium
32,333
https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/2357692/Simple-Breadth-First-Search-with-Explanation
class Solution: def get_neighbors(self, start: int) -> Dict[int, int]: distances = defaultdict(lambda: math.inf) queue = deque([start]) level = 0 while queue: for _ in range(len(queue)): curr = queue.popleft() if distances[curr] <= level: continue distances[curr] = level for neighbor in graph[curr]: queue.append(neighbor) level += 1 return distances def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: n = len(edges) graph = [[] for _ in range(n)] for _from, to in enumerate(edges): if to != -1: graph[_from].append(to) a = self.get_neighbors(node1) b = self.get_neighbors(node2) options = [] for idx in range(n): if a[idx] != math.inf and b[idx] != math.inf: options.append((max(a[idx], b[idx]), idx)) if not options: return -1 return min(options)[1]
find-closest-node-to-given-two-nodes
Simple Breadth First Search with Explanation
wickedmishra
2
137
find closest node to given two nodes
2,359
0.342
Medium
32,334
https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/2754800/JavaPython3-or-DFS-%2BMap
class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: count,ans=len(edges),float('inf') graph=[[] for i in range(count)] reach1,reach2={},{} vis=set() reach1[node1]=0 reach2[node2]=0 curr=float('inf') for u,v in enumerate(edges): if v!=-1: graph[u].append(v) def dfs(node,reach,dist): for it in graph[node]: if it not in vis: vis.add(it) reach[it]=dist+1 dfs(it,reach,dist+1) vis.remove(it) return vis.add(node1) dfs(node1,reach1,0) vis.remove(node1) vis.clear() vis.add(node2) dfs(node2,reach2,0) vis.remove(node2) for node in reach2: if node in reach1: if curr>max(reach1[node],reach2[node]): ans=node curr=max(reach1[node],reach2[node]) elif curr==max(reach1[node],reach2[node]) and node<ans: ans=node curr=max(reach1[node],reach2[node]) if ans==float('inf'): return -1 else: return ans
find-closest-node-to-given-two-nodes
[Java/Python3] | DFS +Map
swapnilsingh421
0
6
find closest node to given two nodes
2,359
0.342
Medium
32,335
https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/2388006/Find-distances-from-nodes-1and2-to-other-nodes-95-speed
class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: n = len(edges) def distances_to_nodes(start: int) -> list: res = [inf] * n res[start] = 0 next_node = edges[start] count = 1 while (next_node != -1 and count < res[next_node]): res[next_node] = count next_node = edges[next_node] count += 1 return res ans, min_max_d = -1, inf for i, (a, b) in enumerate(zip(distances_to_nodes(node1), distances_to_nodes(node2))): if (distance := max(a, b)) < min_max_d: ans = i min_max_d = distance return ans
find-closest-node-to-given-two-nodes
Find distances from nodes 1&2 to other nodes, 95% speed
EvgenySH
0
50
find closest node to given two nodes
2,359
0.342
Medium
32,336
https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/2362590/Python-bfs-solution-easy
class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: def get_dist(graph,n): dist = [-1 for i in range(len(graph))] queue = [(n,0)] while queue: x,count = queue.pop(0) dist[x] = count for i in graph[x]: if dist[i]==-1: queue.append((i,count+1)) return dist graph = {} for i in range(len(edges)): graph[i] = [] for i in range(len(edges)): if edges[i]!=-1: graph[i].append(edges[i]) li1 = get_dist(graph,node1) li2 = get_dist(graph,node2) ans = -1 result = 99999999 for i in range(len(edges)): if li1[i]!=-1 and li2[i]!=-1: max_dist = max(li1[i],li2[i]) if max_dist<result: result = max_dist ans = i return ans
find-closest-node-to-given-two-nodes
Python bfs solution easy
Brillianttyagi
0
9
find closest node to given two nodes
2,359
0.342
Medium
32,337
https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/2359489/python3-Solution-for-reference-dfs-keeping-track-of-source.
class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: s = [(node1, 0, 0), (node2, 0, 1)] v = defaultdict(list) ansnode = -1 dist = float('inf') while s: node, distance, source = s.pop() if not v[node]: v[node] = [float('inf'),float('inf')] elif v[node][source] != float('inf'): continue v[node][source] = min(v[node][source], distance) if v[node][0] != float('inf') and v[node][1] != float('inf'): dmax = max(v[node][0], v[node][1]) if dmax < dist: dist = dmax ansnode = node elif dmax == dist: ansnode = min(ansnode, node) if edges[node] != -1: next_node = edges[node] s.append((next_node, distance+1, source)) return ansnode
find-closest-node-to-given-two-nodes
[python3] Solution for reference dfs keeping track of source.
vadhri_venkat
0
2
find closest node to given two nodes
2,359
0.342
Medium
32,338
https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/2358169/python-Simple-DFS-solution
class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: ## RC ## ## APPROACH: GRAPH ## ## LOGIC ## ## 1. Typical Graph problem, just do what the question asks ## 2. Watch out for race conditions, a) when no common node b) multiple paths for the same node graph = collections.defaultdict(list) for u, v in enumerate(edges): if v != -1: graph[u].append(v) res = float('inf') ans = -1 visited1 = {} def dfs1(node, d): nonlocal res nonlocal ans if node == node2: res=min(res, d) ans=node if node in visited1: if visited1[node] > d: visited1[node] = d return visited1[node] = d if node in graph: dfs1(graph[node][0], d +1) dfs1(node1, 0) visited2 = {} def dfs2(node, d): nonlocal res nonlocal ans if node == node1: if res > d: # if already found in first node, then check for max distance res = d ans=node if node in visited2: if visited2[node] > d: visited2[node] = d return visited2[node] = d if node in graph: dfs2(graph[node][0], d +1) dfs2(node2, 0) for node in sorted(visited1.keys()): if node in visited2: if max(visited1[node], visited2[node]) < res: res = max(visited1[node], visited2[node]) ans = node return ans
find-closest-node-to-given-two-nodes
[python] Simple DFS solution
101leetcode
0
16
find closest node to given two nodes
2,359
0.342
Medium
32,339
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2357772/Python3-One-pass-dfs
class Solution: def longestCycle(self, edges: List[int]) -> int: in_d = set() out_d = set() for i, j in enumerate(edges): if j != -1: in_d.add(j) out_d.add(i) potential = in_d &amp; out_d visited = set() self.ans = -1 def dfs(node, curr, v): visited.add(node) v[node] = curr nei = edges[node] if nei in v: self.ans = max(self.ans, curr - v[nei] + 1) visited.add(nei) return if nei not in visited and nei in potential: dfs(nei, curr + 1, v) for node in potential: dfs(node, 1, {}) return self.ans
longest-cycle-in-a-graph
[Python3] One pass dfs
Remineva
5
257
longest cycle in a graph
2,360
0.386
Hard
32,340
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2360079/O(n)-Python-Solution-Beats-100
class Solution: def longestCycle(self, edges: List[int]) -> int: res, seenSet = -1, set() for element in range(len(edges)): #traverses all possible nodes count, currNode = 0, element cycleMap = dict() #tabulates all distances while currNode not in seenSet and currNode != -1: count += 1 seenSet.add(currNode); cycleMap[currNode] = count #adds nodes to the hashmap and the hashset currNode = edges[currNode] #moves on to the next node res = max(res, count + 1 - cycleMap.get(currNode, 200000)) #gets the max distance return res
longest-cycle-in-a-graph
O(n) Python Solution, Beats 100%
ZivSucksBallsDaLimmy
3
65
longest cycle in a graph
2,360
0.386
Hard
32,341
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2385580/VISUAL-or-PYTHON-or-DFS-or-Easy-to-Understand-or-O(N)-Time-or-O(N)-Space
class Solution: def longestCycle(self, edges: List[int]) -> int: def get_length(i, length): #end of path if i ==-1: return -1 #path previously seen if i in prev_seen: return -1 #cycle detected if i in cur_seen: return length - cur_seen[i]+1 cur_seen[i] = length+1 return get_length(edges[i], length+1) res = -1 prev_seen = {} for i in range(len(edges)): cur_seen={} length = get_length(i, 0) res = max(res, length) prev_seen |= cur_seen return res
longest-cycle-in-a-graph
📌 [VISUAL] | [PYTHON] | DFS | Easy to Understand | O(N) Time | O(N) Space
matthewlkey
1
33
longest cycle in a graph
2,360
0.386
Hard
32,342
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2378505/Python-oror-Simple-DFS-solution
class Solution: def longestCycle(self, edges: List[int]) -> int: N = len(edges) def dfs(node, step): if node in total: return total[node] if node in visited: return step-visited[node] else: visited[node] = step next_node = edges[node] if next_node == -1: return -1 return dfs(next_node, step+1) total = defaultdict(int) for e in range(len(edges)): if e not in total: visited = defaultdict(int) res = dfs(e, 0) for v in visited: total[v] = res ans = max(total.values()) return -1 if ans == 0 else ans
longest-cycle-in-a-graph
Python || Simple DFS solution
pivovar3al
1
52
longest cycle in a graph
2,360
0.386
Hard
32,343
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2357678/Python-3-oror-Easy-to-understand-solution
class Solution: def longestCycle(self, edges: List[int]) -> int: n = len(edges) colors = [0] * n dis = [0] * n def dfs(u, d): colors[u] = 1 dis[u] = d ans = -1 if edges[u] == -1: colors[u] = 2 return -1 if colors[edges[u]] == 0: ans = max(ans, dfs(edges[u], d + 1)) elif colors[edges[u]] == 1: return dis[u] - dis[edges[u]] + 1 colors[u] = 2 return ans res = -1 for i in range(n): if colors[i] == 0: res = max(res, dfs(i, 0)) return res s = Solution() print(s.longestCycle([-1, 4, -1, 2, 0, 4]))
longest-cycle-in-a-graph
Python 3 || Easy to understand solution
pramodjoshi_22
1
37
longest cycle in a graph
2,360
0.386
Hard
32,344
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2827238/Python-easy-to-read-and-understand-or-dfs
class Solution: def cycle(self, graph, visit, node, mp): # print(visit) if visit[node] == 2: # print(node, self.cnt) self.cnt = self.cnt - mp[node] return True visit[node] = 2 mp[node] = self.cnt for nei in graph[node]: if visit[nei] != 1: self.cnt += 1 if self.cycle(graph, visit, nei, mp): return True visit[node] = 1 return False def longestCycle(self, edges: List[int]) -> int: n = len(edges) graph = {i: [] for i in range(n)} for u, v in enumerate(edges): if v != -1: graph[u].append(v) res = -1 visit = [0] * n for i in range(n): if visit[i] == 0: self.cnt = 0 mp = {i: 0 for i in range(n)} if self.cycle(graph, visit, i, mp): res = max(res, self.cnt) return res
longest-cycle-in-a-graph
Python easy to read and understand | dfs
sanial2001
0
6
longest cycle in a graph
2,360
0.386
Hard
32,345
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2807663/tarjan-algorithm
class Solution: def longestCycle(self, edges: List[int]) -> int: def tarjan(): stack = [] vis = defaultdict(int) low = defaultdict(int) self.ts = 1 ret = [] def dfs(node): vis[node] = self.ts low[node] = self.ts self.ts += 1 stack.append(node) nex = edges[node] if nex != -1: if vis[nex] == 0: dfs(nex) low[node] = min(low[node], low[nex]) elif nex in stack: low[node] = min(low[node], low[nex]) if vis[node] == low[node]: tmp = [] while stack[-1] != node: tmp.append(stack.pop()) tmp.append(stack.pop()) ret.append(tmp) for i in range(len(edges)): if vis[i] == 0: dfs(i) return ret ret = tarjan() cir = max(len(r) for r in ret) if cir == 1: return -1 else: return cir
longest-cycle-in-a-graph
tarjan algorithm
xsdnmg
0
1
longest cycle in a graph
2,360
0.386
Hard
32,346
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2480549/python-3-or-dfs
class Solution: def longestCycle(self, edges: List[int]) -> int: seen = {-1} self.res = -1 def dfs(i): if i in seen: return i, 1 seen.add(i) cycleNode, length = dfs(edges[i]) if i == cycleNode: self.res = max(self.res, length) return cycleNode, length + 1 for i in range(len(edges)): dfs(i) return self.res
longest-cycle-in-a-graph
python 3 | dfs
dereky4
0
69
longest cycle in a graph
2,360
0.386
Hard
32,347
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2375901/Analogy-with-find-method-in-union-find-ADT-or-Python3-or-DFS
class Solution: def longestCycle(self, edges: List[int]) -> int: # 1. init n = len(edges) res = -1 visited = set([-1]) # 2. main loop for i in range(n): if i not in visited: # do traversal start = i current_visited = set() while start not in visited: visited.add(start) current_visited.add(start) start = edges[start] if start in current_visited: cycle_length = 1 node = edges[start] while node != start: node = edges[node] cycle_length += 1 res = max(res, cycle_length) return res
longest-cycle-in-a-graph
Analogy with find method in union-find ADT | Python3 | DFS
wxy0925
0
8
longest cycle in a graph
2,360
0.386
Hard
32,348
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2361213/DFS-as-simple-as-possible-with-few-optimizations.
class Solution: def longestCycle(self, edges: List[int]) -> int: lookup = defaultdict(list) self.max_depth = -1 # optimization # calculating the lookup for only edges that have indegree and outdegree. # Because if nodes do not have both indegree and outdegree, then they can't form a cycle. indegree, outdegree = set(), set() for i in range(0, len(edges)): indegree.add(edges[i]) outdegree.add(i) all_nodes = indegree &amp; outdegree for i in range(0, len(edges)): if i in all_nodes and edges[i] in all_nodes: lookup[i].append(edges[i]) def dfs(i, cnt, curr_dict): if i not in seen: seen.add(i) curr_dict[i] = cnt for each in lookup[i]: del lookup[i] # optimization # this can be applied because every node has # at most one outgoing edge. dfs(each, cnt + 1, curr_dict) else: self.max_depth = max(self.max_depth, cnt - curr_dict.get(i, float("inf"))) seen = set() for each in all_nodes: if each not in seen: # optimization # avoiding visiting the nodes multiple times. dfs(each, 0, {}) return self.max_depth
longest-cycle-in-a-graph
DFS as simple as possible with few optimizations.
devanshihdesai
0
15
longest cycle in a graph
2,360
0.386
Hard
32,349
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2360300/DFSDFS%2BKahn's-Algorithm
class Solution: def longestCycle(self, edges: List[int]) -> int: # degree of inbounds deg = Counter(edges) # cycle length cycle = defaultdict(int) n = len(edges) def dfs(node, path, dis): dis += 1 nei = edges[node] # cycle found if nei in path: # cycle length = total travel distance - distance when node first traversed cycle[nei] = dis - path[nei] # check whether all inbounds have been traversed elif nei > -1 and deg[nei]: deg[nei] -= 1 path[nei] = dis dfs(nei, path, dis) for i in range(n): if not deg[i]: continue dfs(i, {}, 0) return max(cycle.values()) if cycle else -1
longest-cycle-in-a-graph
[DFS]DFS+Kahn's Algorithm
chestnut890123
0
35
longest cycle in a graph
2,360
0.386
Hard
32,350
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2359899/python3-Reference-solution-DFS-traversal-keeping-track-of-distance
class Solution: def longestCycle(self, edges) -> int: N = len(edges) indegree = [0] * len(edges) cycles = defaultdict(int) for x in edges: if x != -1: indegree[x] += 1 def dfs(n, d): ret = 0 if cycles[n] > 0: return cycles[n] if dist[n] > -1: cycles[n] = d - dist[n] return d - dist[n] if visited[n] == True: return 0 visited[n] = True dist[n] = d if edges[n] != -1: ret = max(ret, dfs(edges[n], d+1)) dist[n] = -1 return ret visited = defaultdict(bool) ans = 0 dist = [-1] * N for n in range(N): if visited[n] == False and indegree[n] > 0: ans = max(ans, dfs(n, 0)) return ans if ans else -1
longest-cycle-in-a-graph
[python3] Reference solution - DFS traversal keeping track of distance
vadhri_venkat
0
8
longest cycle in a graph
2,360
0.386
Hard
32,351
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2358132/Python-Simple-Python-Solution-Using-Dictionary
class Solution: def longestCycle(self, edges: List[int]) -> int: result = -1 visited_node = set([-1]) for i in range(len(edges)): if i not in visited_node: start_node = i current_visit = set() while start_node not in visited_node: visited_node.add(start_node) current_visit.add(start_node) start_node = edges[start_node] if start_node in current_visit: current_cycle_length = 1 scan = edges[start_node] while scan != start_node: scan = edges[scan] current_cycle_length = current_cycle_length + 1 result = max(result, current_cycle_length) return result
longest-cycle-in-a-graph
[ Python ] ✅✅ Simple Python Solution Using Dictionary 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
43
longest cycle in a graph
2,360
0.386
Hard
32,352
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2357836/Simple-Python-Dictionary-and-Set
class Solution: def longestCycle(self, edges: List[int]) -> int: ans = -1 def checkLoop(start): temp = {} count = 0 while start != -1: if start in temp: return count - temp[start] elif start in visited: return -1 visited.add(start) temp[start] = count count += 1 start = edges[start] return -1 visited = set() for value in edges: if value in visited: continue else: ans = max(ans, checkLoop(value)) return ans
longest-cycle-in-a-graph
Simple Python Dictionary and Set
syji
0
15
longest cycle in a graph
2,360
0.386
Hard
32,353
https://leetcode.com/problems/merge-similar-items/discuss/2388802/Python-Simple-Python-Solution-Using-HashMap
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: merge_item = items1 + items2 d = defaultdict(int) for i in merge_item: value,weight = i d[value] = d[value] + weight result = [] for j in sorted(d): result.append([j,d[j]]) return result
merge-similar-items
[ Python ] ✅✅ Simple Python Solution Using HashMap 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
8
393
merge similar items
2,363
0.753
Easy
32,354
https://leetcode.com/problems/merge-similar-items/discuss/2388677/One-Liner
class Solution: def mergeSimilarItems(self, i1: List[List[int]], i2: List[List[int]]) -> List[List[int]]: return sorted((Counter({i[0] : i[1] for i in i1}) + Counter({i[0] : i[1] for i in i2})).items())
merge-similar-items
One Liner
votrubac
8
683
merge similar items
2,363
0.753
Easy
32,355
https://leetcode.com/problems/merge-similar-items/discuss/2388275/Python-oror-Easy-Approaches
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: hashset = {} for i in range(len(items1)): if items1[i][0] in hashset: hashset[items1[i][0]] += items1[i][1] else: hashset[items1[i][0]] = items1[i][1] for i in range(len(items2)): if items2[i][0] in hashset: hashset[items2[i][0]] += items2[i][1] else: hashset[items2[i][0]] = items2[i][1] ans = [] for i in sorted(hashset): ans.append([i, hashset[i]]) return ans
merge-similar-items
✅Python || Easy Approaches
chuhonghao01
5
340
merge similar items
2,363
0.753
Easy
32,356
https://leetcode.com/problems/merge-similar-items/discuss/2421396/Python-Elegant-and-Short-or-HashMap-or-Sorting
class Solution: """ Time: O((n+m)*log(n+m)) Memory: O(n+m) """ def mergeSimilarItems(self, first: List[List[int]], second: List[List[int]]) -> List[List[int]]: merged = defaultdict(int) for value, weight in first + second: merged[value] += weight return sorted(merged.items())
merge-similar-items
Python Elegant & Short | HashMap | Sorting
Kyrylo-Ktl
3
128
merge similar items
2,363
0.753
Easy
32,357
https://leetcode.com/problems/merge-similar-items/discuss/2848454/Python-oror-Different-Technique-oror-Easy-for-Beginners
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: final=items1+items2 final.sort(key=lambda i:(i[0])) for i in range(0,len(final)): for j in range(i+1,len(final)-1): if(final[i][0]==final[j][0]): final[i][1]=final[i][1]+final[j][1] del final[j] if final[-1][0]==final[-2][0]: final[-2][1]=final[-2][1]+final[-1][1] del final[-1] return final
merge-similar-items
Python || Different Technique || Easy for Beginners
jannat99
0
1
merge similar items
2,363
0.753
Easy
32,358
https://leetcode.com/problems/merge-similar-items/discuss/2835870/Python-O(n**2)-complexity-beats-98.71-memory-usage
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: for i1 in items1: for i2 in items2: if i1[0] == i2[0]: i1[1] += i2[1] items2.remove(i2) items1.extend(items2) return sorted(items1, key=lambda x: x[0])
merge-similar-items
Python O(n**2) complexity beats 98.71% memory usage
Molot84
0
4
merge similar items
2,363
0.753
Easy
32,359
https://leetcode.com/problems/merge-similar-items/discuss/2820023/simple-python-solution-using-hashmap-and-merge-sort-beats-80
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: hashmap = {} for items in items1: if hashmap.get(items[0]) is not None: hashmap[items[0]]+=items[1] else: hashmap[items[0]]=items[1] for items in items2: if hashmap.get(items[0]) is not None: hashmap[items[0]]+=items[1] else: hashmap[items[0]]=items[1] result = [k for k in hashmap.keys() ] self.mergeSort(result) return [[k,hashmap[k]] for k in result ] def mergeSort(self,arr): if len(arr)>1: mid = len(arr)//2 left = arr[:mid] right = arr[mid:] self.mergeSort(left) self.mergeSort(right) i,j,k =0,0,0 while i<len(left) and j<len(right): if left[i]<right[j]: arr[k]=left[i] i+=1 k+=1 else: arr[k]=right[j] j+=1 k+=1 while i<len(left): arr[k]=left[i] i+=1 k+=1 while j<len(right): arr[k]=right[j] j+=1 k+=1
merge-similar-items
simple python solution using hashmap and merge sort beats 80%
sudharsan1000m
0
1
merge similar items
2,363
0.753
Easy
32,360
https://leetcode.com/problems/merge-similar-items/discuss/2787575/Python-Solution-Using-HashMap
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: merge_item = items1 + items2 hashMap = defaultdict(int) for i in merge_item: value,weight = i hashMap[value] = hashMap[value] + weight lst = [] for i in sorted(hashMap): lst.append([i,hashMap[i]]) return lst
merge-similar-items
Python Solution - Using HashMap
danishs
0
7
merge similar items
2,363
0.753
Easy
32,361
https://leetcode.com/problems/merge-similar-items/discuss/2738523/Easy-Python3-solution-using-Dictionary-Comprehension-and-Sorting
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: dic = {i[0]:[i[-1]] for i in items1} for i in items2: if i[0] in dic: dic[i[0]].append(i[-1]) else: dic[i[0]] = [i[-1]] l = sorted([[key, sum(dic[key])] for key in dic.keys()] , key = lambda x:x[0]) return l
merge-similar-items
Easy Python3 solution using Dictionary Comprehension and Sorting
jacobsimonareickal
0
2
merge similar items
2,363
0.753
Easy
32,362
https://leetcode.com/problems/merge-similar-items/discuss/2685671/Python-oror-Using-Hashmap-oror-beats-93
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) ->List[List[int]]: d={} for i in items1: d[i[0]]=i[1] #print(d) for i in items2: if i[0] in d.keys(): d[i[0]]+=i[1] else: d[i[0]]=i[1] l=list(d.keys()) l.sort() ans=[] for i in range(len(l)): if l[i] in d.keys(): ans.append([l[i],d[l[i]]]) return ans
merge-similar-items
Python || Using Hashmap || beats 93%
utsa_gupta
0
8
merge similar items
2,363
0.753
Easy
32,363
https://leetcode.com/problems/merge-similar-items/discuss/2667197/Python3-or-When-in-doubt-throw-in-a-dict
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: d = {} res = [] for i in items1: if i[0] in d: d[i[0]] = d[i[0]] + i[1] else: d[i[0]] = i[1] for i in items2: if i[0] in d: d[i[0]] = d[i[0]] + i[1] else: d[i[0]] = i[1] for [key, value] in d.items(): res.append([key, value]) return sorted(res)
merge-similar-items
Python3 | When in doubt throw in a dict
prameshbajra
0
6
merge similar items
2,363
0.753
Easy
32,364
https://leetcode.com/problems/merge-similar-items/discuss/2586613/Python-Solution-using-Dictionary
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: visited={} for v,w in items1: for j in range(len(items2)): if v == items2[j][0] and v not in visited: visited[v]=[v,w+items2[j][1]] if v not in visited.keys(): visited[v]=[v,w] for v,w in items2: if v not in visited.keys(): visited[v]=[v,w] return sorted(visited.values())
merge-similar-items
Python Solution using Dictionary
beingab329
0
34
merge similar items
2,363
0.753
Easy
32,365
https://leetcode.com/problems/merge-similar-items/discuss/2519079/Simple-Python-solution-using-hashmap-oror-beats-93
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: items = items1 + items2 res = [] dic = collections.defaultdict(list) for i,w in items: dic[i].append(w) for k,v in dic.items(): res.append([k,sum(v)]) res.sort(key=lambda x : x[0]) return res
merge-similar-items
Simple Python solution using hashmap || beats 93%
aruj900
0
38
merge similar items
2,363
0.753
Easy
32,366
https://leetcode.com/problems/merge-similar-items/discuss/2497089/Python-solution
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: map_ = {item[0]: item[1] for item in items2} for item in items1: item[1] += map_.get(item[0], 0) map_[item[0]] = 0 for key, val in map_.items(): # {3: 0, 6: 2} if val: items1.append([key, val]) items1.sort(key=lambda x:x[0]) return items1
merge-similar-items
Python solution
yash921
0
39
merge similar items
2,363
0.753
Easy
32,367
https://leetcode.com/problems/merge-similar-items/discuss/2483203/Python-for-beginners
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: #Runtime:130ms dic={} lis=[] for value,weight in items1: dic[value]=dic.get(value,0)+weight for value2,weight2 in items2: dic[value2]=dic.get(value2,0)+weight2 for i in sorted(dic.keys()): lis.append([i,dic[i]]) return lis
merge-similar-items
Python for beginners
mehtay037
0
30
merge similar items
2,363
0.753
Easy
32,368
https://leetcode.com/problems/merge-similar-items/discuss/2481522/Python-solution-faster-than-85.5-using-dictionary-O(n)
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: item1_dict = {} for i in items1: item1_dict[i[0]] = i[1] result = [] for j in items2: if j[0] in item1_dict: result.append([j[0], item1_dict[j[0]] + j[1]]) del item1_dict[j[0]] else: result.append(j) if len(item1_dict) != 0: for k, v in item1_dict.items(): result.append([k, v]) return sorted(result)
merge-similar-items
Python solution faster than 85.5% using dictionary O(n)
samanehghafouri
0
23
merge similar items
2,363
0.753
Easy
32,369
https://leetcode.com/problems/merge-similar-items/discuss/2469932/Easy-Python-solution-without-Counter
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: d = {} for i, j in items1+items2: d[i] = d.get(i, 0)+j ret = [list(i) for i in d.items()] ret.sort(key = lambda x: x[0]) return ret
merge-similar-items
Easy Python solution without Counter
yhc22593
0
17
merge similar items
2,363
0.753
Easy
32,370
https://leetcode.com/problems/merge-similar-items/discuss/2409147/Python3-Counter
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: mp = Counter(dict(items1)) + Counter(dict(items2)) return sorted(mp.items())
merge-similar-items
[Python3] Counter
ye15
0
17
merge similar items
2,363
0.753
Easy
32,371
https://leetcode.com/problems/merge-similar-items/discuss/2393820/Python-Simple-with-Explanation-Solution
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: items1+=items2[:] items1.sort() ans,i=[],0 while i!=len(items1): # check if it is not last element, if it is it will go in else part to append in ans if i!= len(items1)-1 and items1[i][0]==items1[i+1][0]: ans.append([items1[i][0],items1[i][1]+items1[i+1][1]]) i=i+2 else: ans.append(items1[i]) i+=1 return ans
merge-similar-items
Python Simple with Explanation Solution
ayushrawat11562
0
17
merge similar items
2,363
0.753
Easy
32,372
https://leetcode.com/problems/merge-similar-items/discuss/2391499/Easy-hashmap-python3
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: w = {} for i in items1: w[i[0]] = i[1] for i in items2: if i[0] in w: w[i[0]] += i[1] else: w[i[0]] = i[1] ans=[] w_s=sorted(w) for i in w_s: ans.append([i,w[i]]) return ans
merge-similar-items
Easy hashmap [python3]
sunakshi132
0
12
merge similar items
2,363
0.753
Easy
32,373
https://leetcode.com/problems/merge-similar-items/discuss/2389970/Python3-or-Hashmap-%2B-Sorting-O(1)-time-O(1)-Space-Solution
class Solution: #Time-Complexity: O(2000 + 1000 + 1000lg(1000)), in worst case first two for loops run 1000 times based on constraints on #items1 and items2 arrays' length! In worst case, each item has distinct value for its worth -> at most 1000 keys in hashmap! #Lastly, the in-place sorting algorithm(timsort) is going to be 1000*log(1000) in worst case! -> O(1) #S.C = O(1000*1 + 1000*2) -> O(1) def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: hashmap = {} for item1 in items1: if item1[0] not in hashmap: hashmap[item1[0]] = item1[1] else: hashmap[item1[0]] += item1[1] for item2 in items2: if item2[0] not in hashmap: hashmap[item2[0]] = item2[1] else: hashmap[item2[0]] += item2[1] sort = [] for k,v in hashmap.items(): sort.append([k, v]) sort.sort(key = lambda x: x[0]) return sort
merge-similar-items
Python3 | Hashmap + Sorting O(1) time O(1) Space Solution
JOON1234
0
11
merge similar items
2,363
0.753
Easy
32,374
https://leetcode.com/problems/merge-similar-items/discuss/2389688/Python-simple-solutiion
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: ans = {} for k, v in items1+items2: if k in ans: ans[k] += v else: ans[k] = v return sorted([[k,v] for k,v in ans.items()], key=lambda x: x[0])
merge-similar-items
Python simple solutiion
StikS32
0
32
merge similar items
2,363
0.753
Easy
32,375
https://leetcode.com/problems/merge-similar-items/discuss/2389377/Python-Simple-Solution-HashMap-oror-Documented
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: dict = defaultdict(int) # dictionary for val, weight in items1: dict[val] = weight # add value: weight for val, weight in items2: dict[val] += weight # add value: weight (if exist do addition) # convert dict into the sorted [value, weight] list keys = sorted(dict.keys()) return [[key, dict[key]] for key in keys]
merge-similar-items
[Python] Simple Solution - HashMap || Documented
Buntynara
0
7
merge similar items
2,363
0.753
Easy
32,376
https://leetcode.com/problems/merge-similar-items/discuss/2389186/Python-or-Default-Dict-or-4-lines
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: ans = defaultdict(int) for value, weight in items1: ans[value] += weight for value, weight in items2: ans[value] += weight return list(sorted(ans.items()))
merge-similar-items
Python | Default Dict | 4 lines
leeteatsleep
0
15
merge similar items
2,363
0.753
Easy
32,377
https://leetcode.com/problems/merge-similar-items/discuss/2388961/Python-or-Easy-and-Understanding-Solution
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: n1=len(items1) n2=len(items2) items1.sort(key=lambda item:(item[0])) items2.sort(key=lambda item:(item[0])) i=j=0 ans=[] while(i<n1 and j<n2): if(items1[i][0]==items2[j][0]): ans.append([items1[i][0],items1[i][1]+items2[j][1]]) i+=1 j+=1 elif(items1[i][0]<items2[j][0]): ans.append([items1[i][0],items1[i][1]]) i+=1 else: ans.append([items2[j][0],items2[j][1]]) j+=1 while(i<n1): ans.append([items1[i][0],items1[i][1]]) i+=1 while(j<n2): ans.append([items2[j][0],items2[j][1]]) j+=1 return ans
merge-similar-items
Python | Easy & Understanding Solution
backpropagator
0
21
merge similar items
2,363
0.753
Easy
32,378
https://leetcode.com/problems/merge-similar-items/discuss/2388531/Python-dictionary
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: weight = {} # or defaultdict(int) values, weights = zip(*items1, *items2) for val, wt in zip(values, weights): weight[val] = weight.get(val, 0) + wt return sorted(weight.items())
merge-similar-items
Python dictionary
blest
0
14
merge similar items
2,363
0.753
Easy
32,379
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2388687/Python-oror-Detailed-Explanation-oror-Faster-Than-100-oror-Less-than-100-oror-Simple-oror-MATH
class Solution: def countBadPairs(self, nums: List[int]) -> int: nums_len = len(nums) count_dict = dict() for i in range(nums_len): nums[i] -= i if nums[i] not in count_dict: count_dict[nums[i]] = 0 count_dict[nums[i]] += 1 count = 0 for key in count_dict: count += math.comb(count_dict[key], 2) return math.comb(nums_len, 2) - count
count-number-of-bad-pairs
🔥 Python || Detailed Explanation ✅ || Faster Than 100% ✅|| Less than 100% ✅ || Simple || MATH
wingskh
32
648
count number of bad pairs
2,364
0.408
Medium
32,380
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2388329/Python-oror-O(n)-oror-Count-oror-Easy-Approaches
class Solution: def countBadPairs(self, nums: List[int]) -> int: n = len(nums) res = [] for i in range(n): res.append(nums[i] - i) a = Counter(res) ans = n * (n - 1) // 2 for x in a: if a[x] > 1: ans -= a[x] * (a[x] - 1) // 2 return ans
count-number-of-bad-pairs
✅Python || O(n) || Count || Easy Approaches
chuhonghao01
2
207
count number of bad pairs
2,364
0.408
Medium
32,381
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2471871/Python-Solution-or-Brute-Force-or-Hashing-or-O(N)
class Solution: def countBadPairs(self, nums: List[int]) -> int: count=0 n=len(nums) # for i in range(n): # for j in range(i+1, n): # if j-i!=nums[j]-nums[i]: # count+=1 # return count d={} for i in range(n): if nums[i]-i in d: count+=d[nums[i]-i] d[nums[i]-i]+=1 else: d[nums[i]-i]=1 return (n*(n-1)//2) - count
count-number-of-bad-pairs
Python Solution | Brute Force | Hashing | O(N)
Siddharth_singh
1
119
count number of bad pairs
2,364
0.408
Medium
32,382
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2388262/Remove-good-pairs-from-total-no-of-pairs
class Solution: def countBadPairs(self, nums: List[int]) -> int: res = 0 d = defaultdict(int) l = len(nums) total = l*(l-1)//2 for i,n in enumerate(nums): res += d[n-i] d[n-i] += 1 return total - res
count-number-of-bad-pairs
Remove good pairs from total no of pairs
amlanbtp
1
33
count number of bad pairs
2,364
0.408
Medium
32,383
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2737064/Count-bad-pairs
class Solution: def countBadPairs(self, nums: List[int]) -> int: n=len(nums) countgood=0 d=dict() for i in range(len(nums)): diff=i-nums[i] if diff not in d: d[diff]=1 else: d[diff]+=1 for key,value in d.items(): countgood+=(value*(value-1)//2) totalpairs=n*(n-1)//2 return totalpairs-countgood
count-number-of-bad-pairs
Count bad pairs
shivansh2001sri
0
6
count number of bad pairs
2,364
0.408
Medium
32,384
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2411422/100-Time-Efficient-100-Memory-Efficient
class Solution: def countBadPairs(self, nums: List[int]) -> int: d=defaultdict(int) for i in range(len(nums)): d[i-nums[i]]+=1 # create dictionary (hashmap) whose key is i-nums[i] and value is the frequency of i-nums[i] in nums array res=0 for i in d: x=d[i] res+=x*(len(nums)-x) return res//2 # since evry pair is taken twice in res
count-number-of-bad-pairs
100% Time Efficient, 100% Memory Efficient
pbhuvaneshwar
0
86
count number of bad pairs
2,364
0.408
Medium
32,385
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2409156/Python3-2-line
class Solution: def countBadPairs(self, nums: List[int]) -> int: freq = Counter(i-x for i, x in enumerate(nums)) return sum(v*(len(nums)-v) for v in freq.values())//2
count-number-of-bad-pairs
[Python3] 2-line
ye15
0
9
count number of bad pairs
2,364
0.408
Medium
32,386
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2390048/Python3-or-Little-Math-Trick-(check-all-positions-such-at-Ai-i-Aj-j)-with-Hashmap-DS
class Solution: #Time-Complexity: O(n) #Space-Complexity: O(n * 1 + n + n*n) -> O(n^2) def countBadPairs(self, nums: List[int]) -> int: #instead of thinking to computing total number of bad pairs, try thinking of computing #total number of good pairs -> thinking problem in reverse angle! #bad = total - good! #total pairs = len(nums)-1 + len(nums) - 2 + ... + 0 #a pair is bad if i < j and nums[j] - j != nums[i] - i #we can phrase good pair then as being opposite as i < j and nums[j] - j == nums[i] - i! #so transform array by taking each element and subtracting it by its index position! #linearly traverse L to R and if not already in hashmap add it! #if already in hashmap: update key's val += 1 #for each key in hashmap, if its val > 1: take the val -1 and sum from there down to 0 #and increment tot_good_pairs by this! for i in range(len(nums)): nums[i] -= i hashmap = {} for num in nums: if num not in hashmap: hashmap[num] = 1 else: hashmap[num] += 1 #iterate through each key value pair and see if val > 1: total_pairs_array = [i for i in range(len(nums))] total_pairs = sum(total_pairs_array) good_pairs = 0 for k,v in hashmap.items(): #if value is greater than 1, that means that nums[i] - i specific value #occurs somewhere else at jth index for nums[j] - j -> potential good pair! if v > 1: good_pairs_array = [i for i in range(v)] good_pairs += sum(good_pairs_array) bad_pairs = total_pairs - good_pairs return bad_pairs
count-number-of-bad-pairs
Python3 | Little Math Trick (check all positions such at A[i]-i == A[j]-j) with Hashmap DS
JOON1234
0
11
count number of bad pairs
2,364
0.408
Medium
32,387
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2389510/Python-Accurate-Faster-Solution-HashMap
class Solution: def countBadPairs(self, nums: List[int]) -> int: dict, ans = defaultdict(int), 0 for i, v in enumerate(nums): diff = v - i ans += i - dict[diff] dict[diff] += 1 return ans
count-number-of-bad-pairs
[Python] Accurate Faster Solution - HashMap
Buntynara
0
9
count number of bad pairs
2,364
0.408
Medium
32,388
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2388996/Python-or-Easy-and-Understanding-Solution
class Solution: def countBadPairs(self, nums: List[int]) -> int: n=len(nums) mapp={} for i in range(n): if(i-nums[i] not in mapp): mapp[i-nums[i]]=1 else: mapp[i-nums[i]]+=1 ans=0 for i in range(n): diff=i-nums[i] mapp[diff]-=1 ans+=n-i-1-mapp[diff] return ans
count-number-of-bad-pairs
Python | Easy & Understanding Solution
backpropagator
0
19
count number of bad pairs
2,364
0.408
Medium
32,389
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2388110/Python3-Count-the-good-pairs-6-lines
class Solution: def countBadPairs(self, nums: List[int]) -> int: k = len(nums) res = k * (k - 1) // 2 # (1) c = Counter([i - n for i, n in enumerate(nums)]) # (2) and (3) for n in c.values(): res -= n * (n - 1) // 2 # (4) return res
count-number-of-bad-pairs
[Python3] Count the good pairs, 6 lines
Unwise
0
41
count number of bad pairs
2,364
0.408
Medium
32,390
https://leetcode.com/problems/task-scheduler-ii/discuss/2388355/Python-oror-Easy-Approach
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: ans = 0 hashset = {} n = len(tasks) for x in set(tasks): hashset[x] = 0 i = 0 while i <= n - 1: flag = ans - hashset[tasks[i]] if flag >= 0: ans += 1 hashset[tasks[i]] = ans + space i += 1 else: ans += -flag return ans
task-scheduler-ii
✅Python || Easy Approach
chuhonghao01
2
75
task scheduler ii
2,365
0.462
Medium
32,391
https://leetcode.com/problems/task-scheduler-ii/discuss/2388216/Python-easy-solution
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: Dict = {} ans,l = 0,len(tasks) for i,n in enumerate(tasks): if n in Dict: ans += max(1,space-(ans-Dict[n])+1) else: ans+=1 Dict[n] = ans return ans
task-scheduler-ii
Python easy solution
amlanbtp
1
36
task scheduler ii
2,365
0.462
Medium
32,392
https://leetcode.com/problems/task-scheduler-ii/discuss/2576924/Python-Easy-to-Understand-Solution
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: day_checker = {} day = 1 for i in range(len(tasks)): if tasks[i] not in day_checker: day_checker[tasks[i]] = day else: if abs(day_checker[tasks[i]] - day) <= space: day = day_checker[tasks[i]] + space + 1 day_checker[tasks[i]] = day else: day_checker[tasks[i]] = day day += 1 return day - 1 ```
task-scheduler-ii
Python Easy to Understand Solution
NiazAhmad
0
21
task scheduler ii
2,365
0.462
Medium
32,393
https://leetcode.com/problems/task-scheduler-ii/discuss/2497539/Python-90-faster
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: map = {tasks[0]:0} i = 1 n = len(tasks) j = 1 dash = 0 while i<n: if tasks[i] in map and (i+dash)-map[tasks[i]] -1< space: count = space-((i+dash)-map[tasks[i]]-1) dash+=count j+= count map[tasks[i]] = i+dash i+=1 j+=1 else: map[tasks[i]] = i+dash j+=1 i+=1 return j
task-scheduler-ii
Python 90% faster
Abhi_009
0
46
task scheduler ii
2,365
0.462
Medium
32,394
https://leetcode.com/problems/task-scheduler-ii/discuss/2443897/One-pass-80-speed
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: day = 1 allowed = dict() space1 = space + 1 for task in tasks: if task in allowed: if day >= allowed[task]: allowed[task] = day + space1 else: day = allowed[task] allowed[task] = day + space1 else: allowed[task] = day + space1 day += 1 return day - 1
task-scheduler-ii
One pass, 80% speed
EvgenySH
0
25
task scheduler ii
2,365
0.462
Medium
32,395
https://leetcode.com/problems/task-scheduler-ii/discuss/2409166/Python3-4-line
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: ans = 0 prev = defaultdict(lambda: -inf) for t in tasks: ans = prev[t] = max(ans, prev[t]+space)+1 return ans
task-scheduler-ii
[Python3] 4-line
ye15
0
19
task scheduler ii
2,365
0.462
Medium
32,396
https://leetcode.com/problems/task-scheduler-ii/discuss/2389975/Python3-or-Basic-Traversal-and-Usage-of-Hashmap-or-Linear-Time-and-Space-Solution!
class Solution: #let n = tasks.length! #Time-Complexity: O(n) #Space-Complexity: O(n*1) -> O(n) def taskSchedulerII(self, tasks: List[int], space: int) -> int: #we need someway to keep track of each type of tasks when it was most recently completed! #We can utilize a hashmap -> Key: type of task mapped to Value: most recent day the type of task was completed! #I will use i as pointer that goes through each task one by one! #I will also use day counter to keep track of the current day! #If we ever encounter a task we did not do before, we can immediately do it now and record when we did it #in hashmap! #Otherwise, we need to check if the current day > space + hashmap[type of task] -> Only then can we do the task #we did before now! Otherwise, we need to wait certain number of days until day > space + hashmap[type_of_task] hashmap = {} day = 1 i= 0 #as long as pointer i is in-bounds, we can continue! while i < len(tasks): #check if current task is not seen yet! -> Do it now! if(tasks[i] not in hashmap): hashmap[tasks[i]] = day day += 1 i += 1 continue #otherwise, if the task is what we already seen before... else: last_completed = hashmap[tasks[i]] #then, we can do now! if(day > space + last_completed): hashmap[tasks[i]] = day day += 1 i += 1 continue #otherwise, we need to bring current day number to be 1 more than space + last_completed! Gotta #wait that many more days! else: day = last_completed + space + 1 hashmap[tasks[i]] = day day += 1 i += 1 #we should have days be min number of days + 1 return day - 1
task-scheduler-ii
Python3 | Basic Traversal and Usage of Hashmap | Linear Time and Space Solution!
JOON1234
0
9
task scheduler ii
2,365
0.462
Medium
32,397
https://leetcode.com/problems/task-scheduler-ii/discuss/2389917/PYTHON-or-HASH-or-KEEP-TRACK
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: """ Input: tasks = [1,2,1,2,3,1], space = 3 Output: 9 """ last = {} days = 0 for i in range(len(tasks)): days+=1 if len(last)==0: last[tasks[i]]=days+space+1 else: if tasks[i] in last: n = last[tasks[i]] days = max(days,n) last[tasks[i]] = days+space+1 else: last[tasks[i]]=days+space+1 return days
task-scheduler-ii
PYTHON | HASH | KEEP TRACK
Brillianttyagi
0
15
task scheduler ii
2,365
0.462
Medium
32,398
https://leetcode.com/problems/task-scheduler-ii/discuss/2389107/Python-or-Easy-and-Understanding-Solution
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: mapp={} ans=0 for task in tasks: ans+=1 if task not in mapp: mapp[task]=ans else: if(ans-mapp[task]<=space): ans+=(space-(ans-mapp[task]))+1 mapp[task]=ans else: mapp[task]=ans return ans
task-scheduler-ii
Python | Easy & Understanding Solution
backpropagator
0
4
task scheduler ii
2,365
0.462
Medium
32,399