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/count-unhappy-friends/discuss/2345920/Success-Details-Runtime%3A-394-ms-faster-than-99.40-of-Python3-online-submissions-oror-vimla_kushwaha
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: dd = {} for i,x in pairs: dd[i] = preferences[i][:preferences[i].index(x)] dd[x] = preferences[x][:preferences[x].index(i)] ans = 0 for i in dd: for x in dd[i]: if i in dd[x]: ans += 1 break return ans
count-unhappy-friends
Success Details Runtime: 394 ms, faster than 99.40% of Python3 online submissions || vimla_kushwaha
vimla_kushwaha
2
136
count unhappy friends
1,583
0.603
Medium
23,300
https://leetcode.com/problems/count-unhappy-friends/discuss/844034/Python-3-or-Brutal-Force-Hash-Table-O(n2)-or-Explanations
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: idx_table = collections.defaultdict(lambda: collections.defaultdict(int)) for i in range(n): for idx, person in enumerate(preferences[i]): idx_table[i][person] = idx unhappy = [0] * n for i in range(n//2): a, b = pairs[i] b_a_idx, a_b_idx = idx_table[b][a], idx_table[a][b] for j in range(i+1, n//2): c, d = pairs[j] c_a_idx = idx_table[c][a] c_b_idx = idx_table[c][b] c_d_idx = idx_table[c][d] d_a_idx = idx_table[d][a] d_b_idx = idx_table[d][b] d_c_idx = idx_table[d][c] a_c_idx = idx_table[a][c] a_d_idx = idx_table[a][d] b_c_idx = idx_table[b][c] b_d_idx = idx_table[b][d] if c_a_idx < c_d_idx and a_c_idx < a_b_idx: unhappy[a] = unhappy[c] = 1 # a &amp; c prefer each other if d_a_idx < d_c_idx and a_d_idx < a_b_idx: unhappy[a] = unhappy[d] = 1 # a &amp; d prefer each other if c_b_idx < c_d_idx and b_c_idx < b_a_idx: unhappy[b] = unhappy[c] = 1 # b &amp; c prefer each other if d_b_idx < d_c_idx and b_d_idx < b_a_idx: unhappy[b] = unhappy[d] = 1 # b &amp; d prefer each other return sum(unhappy)
count-unhappy-friends
Python 3 | Brutal Force, Hash Table, O(n^2) | Explanations
idontknoooo
2
510
count unhappy friends
1,583
0.603
Medium
23,301
https://leetcode.com/problems/count-unhappy-friends/discuss/1325617/13-line-simple-clean-python
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: likemore = {} for a,b in pairs: likemore[a] = set(preferences[a][:preferences[a].index(b)]) likemore[b] = set(preferences[b][:preferences[b].index(a)]) unhappy = set() for i in range(n): for j in range(i): if(i in likemore[j] and j in likemore[i]): unhappy.add(i) unhappy.add(j) return len(unhappy)
count-unhappy-friends
13 line simple clean python
artalukd
1
188
count unhappy friends
1,583
0.603
Medium
23,302
https://leetcode.com/problems/count-unhappy-friends/discuss/2845736/Python-O(n3)-follow-the-rules-word-by-word
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: # iterate through the pairs # add pairs to d: d[x] = y, d[y] = x # check each pair x, y in preferences to see if # for friends in preferences[x][:indexy]: # check the condition pd = {} for x, y in pairs: pd[x] = y pd[y] = x unhappy = 0 for x in pd.keys(): y = pd[x] indexy = preferences[x].index(y) betterFriends = preferences[x][:indexy] for u in betterFriends: v = pd[u] indexv = preferences[u].index(v) if x in preferences[u][:indexv]: unhappy += 1 break return unhappy
count-unhappy-friends
Python O(n^3) follow the rules word by word
monkecoder
0
1
count unhappy friends
1,583
0.603
Medium
23,303
https://leetcode.com/problems/count-unhappy-friends/discuss/1307222/Python3-10-lines-and-extended-solution-for-readability-or-HashtableDict
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: total = 0 pair_map = {p[0]:p[1] for p in pairs} | {p[1]:p[0] for p in pairs} for pair in pair_map.keys(): for i in range(preferences[pair].index(pair_map[pair]) + 1): if preferences[preferences[pair][i]].index(pair) < preferences[preferences[pair][i]].index(pair_map[preferences[pair][i]]): total += 1 break return total
count-unhappy-friends
[Python3] 10 lines and extended solution for readability | Hashtable/Dict
random_user_4389
0
101
count unhappy friends
1,583
0.603
Medium
23,304
https://leetcode.com/problems/count-unhappy-friends/discuss/1307222/Python3-10-lines-and-extended-solution-for-readability-or-HashtableDict
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: total = 0 pair_map = {p[0]:p[1] for p in pairs} | {p[1]:p[0] for p in pairs} for pair in pair_map.keys(): preferences_for_pair = preferences[pair] check_matches_till = preferences_for_pair.index(pair_map[pair]) + 1 for i in range(check_matches_till): priority_for_pair = preferences_for_pair[i] priority_match = pair_map[priority_for_pair] priority_preferences = preferences[priority_for_pair] if priority_preferences.index(pair) < priority_preferences.index(priority_match): total += 1 break return total
count-unhappy-friends
[Python3] 10 lines and extended solution for readability | Hashtable/Dict
random_user_4389
0
101
count unhappy friends
1,583
0.603
Medium
23,305
https://leetcode.com/problems/count-unhappy-friends/discuss/847802/O(n2)-solution-by-rearranging-data
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: indices = [[0] * n for i in range(n)] for i, p in enumerate(preferences): for j, f in enumerate(p): indices[i][f] = j pairedWith = [0] * n for i, j in pairs: pairedWith[i] = j pairedWith[j] = i count = 0 for x in range(n): y = pairedWith[x] for u in preferences[x]: if u == y: break v = pairedWith[u] if indices[u][x] < indices[u][v]: count += 1 break return count
count-unhappy-friends
O(n^2) solution by rearranging data
snibbets
0
81
count unhappy friends
1,583
0.603
Medium
23,306
https://leetcode.com/problems/count-unhappy-friends/discuss/844026/Python-Brute-Force-using-index-of-item
class Solution: def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: prefDict = {i:preferences[i] for i in range(n)} res = set() for i, (x1,y1) in enumerate(pairs): for j, (x2,y2) in enumerate(pairs): if i != j: if prefDict[x1].index(y2) < prefDict[x1].index(y1): # smaller index means higher preference if prefDict[y2].index(x1) < prefDict[y2].index(x2): res.add(x1) if prefDict[x1].index(x2) < prefDict[x1].index(y1): if prefDict[x2].index(x1) < prefDict[x2].index(y2): res.add(x1) if prefDict[y1].index(x2) < prefDict[y1].index(x1): if prefDict[x2].index(y1) < prefDict[x2].index(y2): res.add(y1) if prefDict[y1].index(y2) < prefDict[y1].index(x1): if prefDict[y2].index(y1) < prefDict[y2].index(x2): res.add(y1) return len(res)
count-unhappy-friends
Python Brute Force using index of item
akrishna06
0
52
count unhappy friends
1,583
0.603
Medium
23,307
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/843995/Python-3-or-Min-Spanning-Tree-or-Prim's-Algorithm
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: manhattan = lambda p1, p2: abs(p1[0]-p2[0]) + abs(p1[1]-p2[1]) n, c = len(points), collections.defaultdict(list) for i in range(n): for j in range(i+1, n): d = manhattan(points[i], points[j]) c[i].append((d, j)) c[j].append((d, i)) cnt, ans, visited, heap = 1, 0, [0] * n, c[0] visited[0] = 1 heapq.heapify(heap) while heap: d, j = heapq.heappop(heap) if not visited[j]: visited[j], cnt, ans = 1, cnt+1, ans+d for record in c[j]: heapq.heappush(heap, record) if cnt >= n: break return ans
min-cost-to-connect-all-points
Python 3 | Min Spanning Tree | Prim's Algorithm
idontknoooo
80
13,100
min cost to connect all points
1,584
0.641
Medium
23,308
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1982821/Python-Simple-and-Concise-MST-with-Explanation
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: d, res = {(x, y): float('inf') if i else 0 for i, (x, y) in enumerate(points)}, 0 while d: x, y = min(d, key=d.get) # obtain the current minimum edge res += d.pop((x, y)) # and remove the corresponding point for x1, y1 in d: # for the rest of the points, update the minimum manhattan distance d[(x1, y1)] = min(d[(x1, y1)], abs(x-x1)+abs(y-y1)) return res
min-cost-to-connect-all-points
[Python] Simple and Concise MST with Explanation
zayne-siew
60
4,100
min cost to connect all points
1,584
0.641
Medium
23,309
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1487547/Python-Kruskal's-with-Union-Find-and-explanation
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: if len(points) <= 1: return 0 graph = self.create_graph(points) graph.sort(key=lambda x: x[2]) n = len(points) uf = UnionFind(n) result = 0 count = 0 for i in graph: vertex, node, cost = i if count == n - 1: break if uf.union(vertex, node): result += cost count += 1 else: continue return result def create_graph(self, points): graph = [] for i in range(len(points) - 1): for j in range(i + 1, len(points)): curr_point = points[i] next_point = points[j] result = self.difference(curr_point[0], curr_point[1], next_point[0], next_point[1]) graph.append([i, j, result]) return graph def difference(self, a, b, c, d): return abs(a - c) + abs(b - d) class UnionFind: def __init__(self, size): self.root = [i for i in range(size)] self.rank = [1 for _ in self.root] def find(self, vertex): if vertex == self.root[vertex]: return vertex self.root[vertex] = self.find(self.root[vertex]) return self.root[vertex] def union(self, v1, v2): root1 = self.find(v1) root2 = self.find(v2) if root1 != root2: if self.rank[root1] > self.rank[root2]: self.root[root2] = root1 elif self.rank[root1] < self.rank[root2]: self.root[root1] = root2 else: self.root[root2] = root1 self.rank[root1] += 1 return True else: return False
min-cost-to-connect-all-points
Python Kruskal's with Union Find and explanation
SleeplessChallenger
12
455
min cost to connect all points
1,584
0.641
Medium
23,310
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1987578/Python-Prim-Algorithm-oror-Easy-and-Simple-Solution
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: N = len(points) adj = {i:[] for i in range(N)} for i in range(N): x1, y1 = points[i] for j in range(i+1, N): x2, y2 = points[j] dis = abs(x1-x2) + abs(y1-y2) adj[i].append([dis, j]) adj[j].append([dis, i]) res = 0 minHeap = [[0,0]] visit = set() while len(visit) < N: cost, node = heapq.heappop(minHeap) if node in visit: continue res += cost for neighCost, nei in adj[node]: if nei not in visit: heapq.heappush(minHeap, [neighCost, nei]) visit.add(node) return res
min-cost-to-connect-all-points
Python - Prim Algorithm || Easy and Simple Solution
dayaniravi123
1
27
min cost to connect all points
1,584
0.641
Medium
23,311
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/2799958/Python3-Submission-using-Union-Find-(Beats-~96-Time-and-~89-Space)
class Solution: def to_tuple(self, points): return tuple(tuple(point) for point in points) def getDistance(self, x, y): return abs(y[0]-x[0])+abs(y[1]-x[1]) def computeEdges(self, pointsTuple, length): edges = [] for point1 in range(length-1): for point2 in range(point1+1,length): dist = self.getDistance(pointsTuple[point1], pointsTuple[point2]) edges.append((pointsTuple[point1], pointsTuple[point2], dist)) return edges def minCostConnectPoints(self, points: List[List[int]]) -> int: def find(parent, node): if node != parent[node]: parent[node] = find(parent, parent[node]) return parent[node] def union(parent, rank, parent1, parent2): if rank[parent2] > rank[parent1]: parent[parent1] = parent2 rank[parent2] += rank[parent1] else: parent[parent2] = parent1 rank[parent1] += rank[parent2] pointsTuple = self.to_tuple(points) length = len(pointsTuple) edges = self.computeEdges(pointsTuple, length) edges.sort(key=lambda x:x[2]) parent, rank, visited, current, mincost = {}, {}, 0, 0, 0 for node in pointsTuple: parent[node] = node rank[node] = 1 while visited < length - 1: node1, node2, cost = edges[current] current += 1 parent1, parent2 = find(parent, node1), find(parent, node2) if parent1 != parent2: mincost += cost visited += 1 union(parent, rank, parent1, parent2) return mincost
min-cost-to-connect-all-points
Python3 Submission using Union-Find (Beats ~96% Time & ~89% Space)
frizzid07
0
3
min cost to connect all points
1,584
0.641
Medium
23,312
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/2529316/Python-3-or-Kruskal's-algo-or-union-find-or-easy-to-understand
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: if len(points) == 1: return 0 # calculates manhattan distance def dist(u, v): x1, y1 = points[u] x2, y2 = points[v] return abs(x1 - x2) + abs(y1 - y2) def find(n): p = parent[n] while p != parent[p]: p = parent[p] return p def union(u, v): p1 = find(u) p2 = find(v) # cycle found if p1 == p2: return True if rank[p1] > rank[p2]: parent[p2] = p1 rank[p1] += rank[p2] else: parent[p1] = p2 rank[p2] += rank[p1] return False n = len(points) edge_weight_map = defaultdict(int) # connect each pair of points with a weighted edge for i in range(0, n): for j in range(i + 1, n): edge_weight_map[(i, j)] = dist(i, j) # sort edges in non-decreasing order by weight sorted_edges_list = sorted(edge_weight_map.items(), key = lambda x : x[1]) parent = [i for i in range(0, n)] rank = [1 for _ in range(0, n)] cost = 0 edges_count = 0 # Find mst using Kruskal's algo for edge, weight in sorted_edges_list: u, v = edge # pick smallest edge # if it forms a cycle(detect using union-find), discard it # else include this edge in mst if not union(u, v): cost += weight edges_count += 1 # mst found if edges_count == n - 1: return cost
min-cost-to-connect-all-points
Python 3 | Kruskal's algo | union find | easy to understand
user7726Y
0
28
min cost to connect all points
1,584
0.641
Medium
23,313
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/2336838/Python-very-simple-beats-75-Prims-with-comments
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: cost = 0 heap = [] #set to store past points to prevent cycle visited = set([0]) #i == the index of current point i = 0 while len(visited) < len(points): #Add all costs from current point to unreached points to min heap for j in range(len(points)): if j == i or j in visited: continue distance = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]) heapq.heappush(heap, (distance, j)) #Add new min cost edge while True: dist, point = heapq.heappop(heap) if point not in visited: cost += dist #Add point to visited to prevent cycle visited.add(point) #Update point i = point break return cost
min-cost-to-connect-all-points
Python very simple beats 75% Prims with comments
mateobv07
0
75
min cost to connect all points
1,584
0.641
Medium
23,314
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/2035031/Python3-Prim's-algorithm
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: visited = set() def getManhattanDist(x1, y1): res = [] for x2, y2 in points: if (x2, y2) not in visited: res.append([abs(x1 - x2) + abs(y1 - y2), (x2, y2)]) return res minheap = [] heappush(minheap, [0, (points[0][0], points[0][1])]) ans = 0 while len(minheap) > 0: if len(visited) == len(points): break c, (x, y) = heappop(minheap) if (x, y) not in visited: ans += c visited.add((x, y)) values = getManhattanDist(x, y) for value in values: heappush(minheap, value) return ans
min-cost-to-connect-all-points
Python3 Prim's algorithm
user6397p
0
43
min cost to connect all points
1,584
0.641
Medium
23,315
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/2033061/Python3-solution-using-Prim's
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: """Given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi], return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.""" result = 0 MAX = 20000001 dist = {} for i in range(len(points)): dist[points[i][0], points[i][1]] = MAX if i else 0 while dist: temp_min = MAX for i in dist: if dist[i] <= temp_min: temp_min = dist[i] x, y = i[0], i[1] result += dist.pop((x, y)) for i in dist: temp_min = (abs(x - i[0]) + abs(y - i[1])) if temp_min < dist[i]: dist[i] = temp_min return result
min-cost-to-connect-all-points
Python3 solution using Prim's
plasticuproject
0
33
min cost to connect all points
1,584
0.641
Medium
23,316
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1984461/Python3-Solution-with-using-prims-algorithm
class Solution: def find_dist(self, pair1, pair2): return abs(pair1[0] - pair2[0]) + abs(pair1[1] - pair2[1]) def minCostConnectPoints(self, points: List[List[int]]) -> int: total_points = len(points) d = collections.defaultdict(list) for i in range(total_points): for j in range(i+1, total_points): dist = self.find_dist(points[i], points[j]) d[i].append((dist, j)) d[j].append((dist, i)) heap = d[0] heapq.heapify(heap) res = 0 """ inital visit '0' point + we also exclude this point, so as not to return here if the distance between the zero and the next point is the smallest. """ current_points_cnt = 1 visited = set([0]) while heap and current_points_cnt != total_points: dist, p = heapq.heappop(heap) # select minimum distance among the possible neighbors for the last visited point if p not in visited: visited.add(p) for v in d[p]: heapq.heappush(heap, v) # adding distances to neighbors res += dist # add min dist current_points_cnt += 1 # inc visited point count return res
min-cost-to-connect-all-points
[Python3] Solution with using prims algorithm
maosipov11
0
17
min cost to connect all points
1,584
0.641
Medium
23,317
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1984109/Python-Solution-using-Prims-algorithm
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: # Create adjacency graph n = len(points) adj = {i: [] for i in range(n)} for i in range(n): x1, y1 = points[i] for j in range(i + 1, n): x2, y2 = points[j] diff = abs(x1 - x2) + abs(y1 - y2) adj[i].append([diff, j]) adj[j].append([diff, i]) # Prims Algorithm hp = [[0,0]] res = 0 visited = set() while len(visited) < n: cost, cur_node = heapq.heappop(hp) if cur_node in visited: continue res += cost visited.add(cur_node) for neigh_cost, neigh in adj[cur_node]: if neigh in visited: continue heapq.heappush(hp, [neigh_cost, neigh]) return res
min-cost-to-connect-all-points
Python Solution using Prims algorithm
pradeep288
0
15
min cost to connect all points
1,584
0.641
Medium
23,318
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1982735/Python-solution-faster-than-77
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: n = len(points) mst_cost = 0 edges_used = 0 in_mst = [False] * n min_dist = [math.inf] * n min_dist[0] = 0 while edges_used < n: curr_min_edge = math.inf curr_node = -1 for node in range(n): if not in_mst[node] and curr_min_edge > min_dist[node]: curr_min_edge = min_dist[node] curr_node = node mst_cost += curr_min_edge edges_used += 1 in_mst[curr_node] = True for next_node in range(n): weight = abs(points[curr_node][0] - points[next_node][0]) +\ abs(points[curr_node][1] - points[next_node][1]) if not in_mst[next_node] and min_dist[next_node] > weight: min_dist[next_node] = weight return mst_cost
min-cost-to-connect-all-points
Python solution faster than 77 %
bad_karma25
0
43
min cost to connect all points
1,584
0.641
Medium
23,319
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1843171/Python-Two-solutions%3A-Kruskal's-and-Prim's-Algorithm-or-Complexity-analysis
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: import heapq def distance(i,j): return abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]) visited = [0] notvisited = set(range(1,len(points))) ret = 0 dist = [] while notvisited: # update distances between recent visited node and notvisited nodes for j in notvisited: heapq.heappush( dist, (distance(visited[-1],j),j) ) # find the min distance to non visited node d, nxt = heapq.heappop(dist) while nxt in visited: d, nxt = heapq.heappop(dist) visited.append(nxt) notvisited.remove(nxt) ret += d return ret
min-cost-to-connect-all-points
[Python] Two solutions: Kruskal's and Prim's Algorithm | Complexity analysis
haydarevren
0
82
min cost to connect all points
1,584
0.641
Medium
23,320
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1835990/Self-Understandable-Python-(Primes-%2B-Kruskal's)-%3A
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: if not points: return 0 adlist=[] size=len(points) visited=[False]*size x1,y1=points[0] for i in range(1,size): x2,y2=points[i] cost=abs(x1-x2)+abs(y1-y2) adlist.append([cost,0,i]) heapq.heapify(adlist) result=0 count=size-1 visited[0]=True while adlist and count>0: cost,x,y=heapq.heappop(adlist) if not visited[y]: result+=cost visited[y]=True for j in range(size): if not visited[j]: dist=abs(points[y][0]-points[j][0])+abs(points[y][1]-points[j][1]) heapq.heappush(adlist,[dist,y,j]) count-=1 return result
min-cost-to-connect-all-points
Self Understandable Python (Primes + Kruskal's) :
goxy_coder
0
90
min cost to connect all points
1,584
0.641
Medium
23,321
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1835990/Self-Understandable-Python-(Primes-%2B-Kruskal's)-%3A
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: if not points: return 0 size=len(points) adlist=[] uf=UnionFind(size) for i in range(size): x1,y1=points[i] for j in range(i+1,size): x2,y2=points[j] cost=abs(x1-x2)+abs(y1-y2) adlist.append([cost,i,j]) heapq.heapify(adlist) result=0 count=size-1 while adlist and count>0: popped=heapq.heappop(adlist) if not uf.connected(popped[1],popped[2]): uf.union(popped[1],popped[2]) result+=popped[0] count-=1 return result class UnionFind: def __init__(self,size): self.root=[i for i in range(size)] self.rank=[1]*size def find(self,x): if x==self.root[x]: return x self.root[x]=self.find(self.root[x]) return self.root[x] def union(self,x,y): rootx=self.find(x) rooty=self.find(y) if rootx!=rooty: if self.rank[rootx]>self.rank[rooty]: self.root[rooty]=rootx elif self.rank[rootx]<self.rank[rooty]: self.root[rootx]=rooty else: self.rank[rootx]+=1 self.root[rooty]=rootx def connected(self,x,y): return self.find(x)==self.find(y)
min-cost-to-connect-all-points
Self Understandable Python (Primes + Kruskal's) :
goxy_coder
0
90
min cost to connect all points
1,584
0.641
Medium
23,322
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1791389/Python-solution-Minimum-spanning-tree-%2B-Prim's-algorithm-(with-union-find)
class Solution: def initialize(self, n): # all nodes are root node self.parent = [i for i in range(n)] def findParent(self, i): parent = i while parent != self.parent[parent]: parent = self.parent[parent] # compression self.parent[i] = parent return parent def makeConnect(self, i, j): parent_i = self.findParent(i) parent_j = self.findParent(j) self.parent[parent_i] = parent_j def isConnected(self, i, j): return self.findParent(i) == self.findParent(j) def minCostConnectPoints(self, points: List[List[int]]) -> int: # it is a question to find the minimum spanning tree. # during the tree construction, we need to check if a cycle is formed, # so we still need to use union-find # construct a graph with all possible edges. # so every point pairs are connected # total len(points) n = len(points) edges = [] # now we get all edges for i in range(n - 1): p1 = points[i] for j in range(i+1, n): # two points p2 = points[j] cost = abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) edges.append([cost, i, j]) # now we have all possible edges, # sort with the cost edges.sort(key=lambda x: x[0]) # a minimum spanning tree for n points has edge number = n - 1 usedEdgesCount = 0 edgeIdx = 0 totalCost = 0 # construct the union-find, total n points self.initialize(n) while edgeIdx < len(edges) and usedEdgesCount < n-1: # we are prepare to insert a new edge to the final tree, # check if the two points are already connected newEdge = edges[edgeIdx] # for not connected if not self.isConnected(newEdge[1], newEdge[2]): # connect them self.makeConnect(newEdge[1], newEdge[2]) # increase the cost totalCost += newEdge[0] # increase counter for used edge usedEdgesCount += 1 # increase edgeIdx edgeIdx += 1 return totalCost
min-cost-to-connect-all-points
Python solution, Minimum spanning tree + Prim's algorithm (with union find)
luke-mao
0
69
min cost to connect all points
1,584
0.641
Medium
23,323
https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/1488747/Python-Prim's-algo-with-self-made-Heap-and-explanation
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: graph = {} self.create_graph(points, graph) print(graph) visited = {0} min_heap = MinHeap(graph[0]) result = 0 while len(visited) < len(points): cost, vertex = min_heap.remove() if vertex not in visited: visited.add(vertex) result += cost if vertex not in graph: continue for i in graph[vertex]: cost, node = i if node not in visited: min_heap.insert((cost, node)) return result def create_graph(self, points, graph): for point in range(len(points)): graph[point] = [] for i in range(len(points) - 1): # can be with -1 or without for j in range(i + 1, len(points)): curr_point = points[i] next_point = points[j] result = self.difference(curr_point[0], curr_point[1], next_point[0], next_point[1]) graph[i].append((result, j)) graph[j].append((result, i)) def difference(self, a, b, c, d): return abs(a - c) + abs(b - d) class MinHeap: def __init__(self, arr): self.heap = self.buildHeap(arr) def check(self): return len(self.heap) == 0 def buildHeap(self, arr): parentIdx = (len(arr) - 2) // 2 for i in reversed(range(parentIdx + 1)): self.siftDown(i, len(arr) - 1, arr) return arr def peek(self): return self.heap[0] def remove(self): to_remove = self.heap[0] node = self.heap.pop() if len(self.heap) > 0: self.heap[0] = node self.siftDown(0, len(self.heap) - 1, self.heap) return to_remove def insert(self, value): self.heap.append(value) self.siftUp() def siftDown(self, idx, length, arr): idxOne = idx * 2 + 1 while idxOne <= length: idxTwo = idx * 2 + 2 if idx * 2 + 2 <= length else -1 if idxTwo != -1 and arr[idxOne][0] > arr[idxTwo][0]: swap = idxTwo else: swap = idxOne if arr[swap][0] < arr[idx][0]: self.swapValues(swap, idx, arr) idx = swap idxOne = idx * 2 + 1 else: return def swapValues(self, i, j, arr): arr[i], arr[j] = arr[j], arr[i] def siftUp(self): idx = len(self.heap) - 1 while idx > 0: parentIdx = (idx - 1) // 2 if self.heap[idx][0] < self.heap[parentIdx][0]: self.swapValues(idx, parentIdx, self.heap) idx = parentIdx else: return
min-cost-to-connect-all-points
Python Prim's algo with self-made Heap and explanation
SleeplessChallenger
0
174
min cost to connect all points
1,584
0.641
Medium
23,324
https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/discuss/844119/Python3-8-line-deque
class Solution: def isTransformable(self, s: str, t: str) -> bool: if sorted(s) != sorted(t): return False # edge case pos = [deque() for _ in range(10)] for i, ss in enumerate(s): pos[int(ss)].append(i) for tt in t: i = pos[int(tt)].popleft() for ii in range(int(tt)): if pos[ii] and pos[ii][0] < i: return False # cannot swap return True
check-if-string-is-transformable-with-substring-sort-operations
[Python3] 8-line deque
ye15
2
198
check if string is transformable with substring sort operations
1,585
0.484
Hard
23,325
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/943380/Python-Simple-Solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: s=0 for i in range(len(arr)): for j in range(i,len(arr),2): s+=sum(arr[i:j+1]) return s
sum-of-all-odd-length-subarrays
Python Simple Solution
lokeshsenthilkumar
53
4,100
sum of all odd length subarrays
1,588
0.835
Easy
23,326
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1222855/44ms-Python-(with-comments-and-detailed-walkthrough)
class Solution(object): def sumOddLengthSubarrays(self, arr): """ :type arr: List[int] :rtype: int """ #We declare our output variable with the initial value as the sum of all elements as this is the 1st iteration of the sum of all individual elements. result = sum(arr) #Saving length of the input array beforehand for ease of writing length = len(arr) #As we already summed up the individual elements, now its time to start groups starting from 3,5,7 and so onnn for j in range(3,length+1,2): #Now we need to create pairs for each element with the previous loop sizes for i in range(length): #This condition is to make we dont search for indexes outside our list if (i+j) > length: break #We continously add the sum of each sublist to our output variable result += sum(arr[i:i+j]) return result
sum-of-all-odd-length-subarrays
44ms, Python (with comments and detailed walkthrough)
Akshar-code
31
1,500
sum of all odd length subarrays
1,588
0.835
Easy
23,327
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2117346/Python3-easy-solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: subs = [] for n in range(1,len(arr)+1,2): for i in range(len(arr)+1-n): subs.append(arr[i:i+n]) return(sum(sum(s) for s in subs))
sum-of-all-odd-length-subarrays
Python3 easy solution
yashkumarjha
4
246
sum of all odd length subarrays
1,588
0.835
Easy
23,328
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1982810/Python-Easy-math-Solution-or-O(n)-Beats-95-submits
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: length = len(arr) ans = 0 for i in range(length) : ans += ((i+1)*(length-i)+1)//2 * arr[i] return ans;
sum-of-all-odd-length-subarrays
[ Python ] Easy math Solution | O(n) Beats 95% submits
crazypuppy
4
301
sum of all odd length subarrays
1,588
0.835
Easy
23,329
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2063747/Python-TC%3A-O(n)-and-SC%3A-O(1)
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: # We check how many times each element in arr occurs in odd length subarray and finally multiply the value with its freq and add it to our ans # TC: O(n) and SC: O(n) # Total no. of subarrays including arr[i] is = No. of subarrays ending at arr[i] * no. of subarrays beginning with arr[i] # No. of odd length subarrays would be half of total subarrays, but since when total no. of subarrays could be odd, so we add 1 to total and then divide by 2 to get odd length subarrays containing the value ans = 0 for i in range(len(arr)): ne = i+1 ns = len(arr)-i total = ne*ns nodd = (total+1)//2 ans+=(arr[i]*nodd) return ans
sum-of-all-odd-length-subarrays
Python TC: O(n) and SC: O(1)
dsalgobros
3
204
sum of all odd length subarrays
1,588
0.835
Easy
23,330
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1473127/Two-loops-94-speed
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: len_arr, ans = len(arr), 0 for start in range(len_arr): sub_sum = 0 for i in range(start, len_arr): sub_sum += arr[i] if not (i - start) % 2: ans += sub_sum return ans
sum-of-all-odd-length-subarrays
Two loops, 94% speed
EvgenySH
3
550
sum of all odd length subarrays
1,588
0.835
Easy
23,331
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2501878/Python-99-faster-with-1-Line-or-O(n)-or-Explained
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: result = 0 length = len(arr) for idx, val in enumerate(arr): """ Start = how many sub arrays will be start with the value End = how many sub arrays will end with the value Total = how many times the value will be there in all sub arrays Odd = We have to get only the odd length of sub arrays so we divide them by 2 Result = multiply the Odd with the array index value and sum with previous value """ start = length - idx end = idx + 1 total = start * end + 1 odd = total // 2 result += odd * val return result
sum-of-all-odd-length-subarrays
✅ Python 99% faster with 1 Line | O(n) | Explained
sezanhaque
2
159
sum of all odd length subarrays
1,588
0.835
Easy
23,332
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2312922/Python-91.2-fasters-or-Python-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Prefix-sum
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: if len(arr) < 3: # if we are having only 2 elements then we cant perform anything with them, rather just provide there sum. return sum(arr) prefix_sum = [0] * (len(arr) + 1) # this will create a list of multiple zeros in it till the len(arr) + 1, i.e. [0, 0, 0, 0, 0, 0] for index, value in enumerate(arr): prefix_sum[index+1] = prefix_sum[index] + value # the above loop will give us a list of prefix_sum operation on arr. i.e. [0, 1, 5, 7, 12, 15] result = 0 for start in range(1, len(arr)+1): for end in range(start, len(arr)+1, 2): result += (prefix_sum[end] - prefix_sum[start-1]) ``` Outcome of the above loop will look like:- 1 8 23 27 38 40 50 55 58 ``` return result
sum-of-all-odd-length-subarrays
Python 91.2% fasters | Python Simplest Solution With Explanation | Beg to adv | Prefix sum
rlakshay14
2
307
sum of all odd length subarrays
1,588
0.835
Easy
23,333
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2057978/Python-List-Comprehension
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: return sum( sum(arr[i:i + odd_arr]) for odd_arr in range(1, len(arr) + 1, 2) for i, n in enumerate(arr) if i + odd_arr <= len(arr) )
sum-of-all-odd-length-subarrays
Python List Comprehension
kedeman
2
84
sum of all odd length subarrays
1,588
0.835
Easy
23,334
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2020988/Python-One-Liner!-Clean-and-Simple!
class Solution: def sumOddLengthSubarrays(self, arr): subs = [arr[i:j] for i in range(len(arr)) for j in range(i+1, len(arr)+1)] return sum(sum(sub) for sub in subs if len(sub)%2)
sum-of-all-odd-length-subarrays
Python - One-Liner! Clean and Simple!
domthedeveloper
2
278
sum of all odd length subarrays
1,588
0.835
Easy
23,335
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2020988/Python-One-Liner!-Clean-and-Simple!
class Solution: def sumOddLengthSubarrays(self, arr): ans = 0 for i in range(len(arr)): for j in range(i+1,len(arr)+1): if (j-i)%2: ans += sum(arr[i:j]) return ans
sum-of-all-odd-length-subarrays
Python - One-Liner! Clean and Simple!
domthedeveloper
2
278
sum of all odd length subarrays
1,588
0.835
Easy
23,336
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2020988/Python-One-Liner!-Clean-and-Simple!
class Solution: def sumOddLengthSubarrays(self, arr): return sum(sum(arr[i:j]) for i in range(len(arr)) for j in range(i+1, len(arr)+1) if (j-i)%2)
sum-of-all-odd-length-subarrays
Python - One-Liner! Clean and Simple!
domthedeveloper
2
278
sum of all odd length subarrays
1,588
0.835
Easy
23,337
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1609646/Python-3-oror-Prefix-Sum
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: prefix_sum = [0] * len(arr) prefix_sum[0] = arr[0] for i in range(1,len(arr)): prefix_sum[i] = prefix_sum[i-1]+arr[i] #construct odd length sub arrays: ans = 0 for i in range(len(arr)): end = i while end < len(arr): #calculate prefix_sum[i--end] if i == 0: ans += prefix_sum[end] else: val = prefix_sum[end] - prefix_sum[i-1] ans += val end += 2 return ans
sum-of-all-odd-length-subarrays
Python 3 || Prefix Sum
s_m_d_29
2
383
sum of all odd length subarrays
1,588
0.835
Easy
23,338
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1078897/easy-and-simple-using-python
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: res,n=[],0 for i in range(1,len(arr)+1,2): if i==1: res.append(sum(arr)) else: while n+i<=len(arr): res.append(sum(arr[n:n+i])) n +=1 n=0 return sum(res)
sum-of-all-odd-length-subarrays
easy and simple using python
yashwanthreddz
2
187
sum of all odd length subarrays
1,588
0.835
Easy
23,339
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/858491/Python3-an-alternative-O(N)-approach
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: ans = 0 for i, x in enumerate(arr): k = (i//2+1)*((len(arr)-i+1)//2) # odd-odd k += (i+1)//2*((len(arr)-i)//2) # even-even ans += k*x return ans
sum-of-all-odd-length-subarrays
[Python3] an alternative O(N) approach
ye15
2
144
sum of all odd length subarrays
1,588
0.835
Easy
23,340
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/858491/Python3-an-alternative-O(N)-approach
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: return sum(((i+1)*(len(arr)-i) + 1)//2 * x for i, x in enumerate(arr))
sum-of-all-odd-length-subarrays
[Python3] an alternative O(N) approach
ye15
2
144
sum of all odd length subarrays
1,588
0.835
Easy
23,341
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2352237/Sum-of-All-Odd-Length-Subarrays-Python-or-Easy-code-or-O(n2)-time-complexity
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: result = sum(arr) #as each subarray results in 1 element length = len(arr)+1 for l in range(3,length , 2): #odd length for i in range(length-l): result += sum(arr[i:l+i]) #sum of subaarays of odd length return result
sum-of-all-odd-length-subarrays
Sum of All Odd Length Subarrays- Python | Easy code | O(n^2)-time complexity
phanee16
1
130
sum of all odd length subarrays
1,588
0.835
Easy
23,342
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2134686/For-Loop-Solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: ls = [] s = 0 for i in range(len(arr)): for j in range(i,len(arr)): if (j-i+1)%2!=0: ls.append(arr[i:j+1]) for i in range(len(ls)): for j in range(len(ls[i])): s+=ls[i][j] return s
sum-of-all-odd-length-subarrays
For Loop Solution
jayeshvarma
1
90
sum of all odd length subarrays
1,588
0.835
Easy
23,343
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2129998/Memory-Usage%3A-13.9-MB-less-than-63.39-of-Python3
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: s = 0 for i in range(len(arr)): for j in range(i, len(arr), 2): s += sum(arr[i:j+1]) return s
sum-of-all-odd-length-subarrays
Memory Usage: 13.9 MB, less than 63.39% of Python3
writemeom
1
92
sum of all odd length subarrays
1,588
0.835
Easy
23,344
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2088524/Simple-Python-Solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: subs = [] for n in range(1, len(arr)+1, 2): for i in range(len(arr)+1-n): subs.append(arr[i:i+n]) return sum(sum(s) for s in subs)
sum-of-all-odd-length-subarrays
Simple Python Solution
pe-mn
1
48
sum of all odd length subarrays
1,588
0.835
Easy
23,345
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1533252/Python3-Prefix-Sum-and-List-slicing-solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: res = 0 for i in range(len(arr)): j = i while j < len(arr): res += sum(arr[i:j+1]) j += 2 return res
sum-of-all-odd-length-subarrays
[Python3] Prefix Sum and List slicing solution
deleted_user
1
117
sum of all odd length subarrays
1,588
0.835
Easy
23,346
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1016805/Python-Prefix-Sum-Technique-(Much-Faster-than-brute-force)
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: result = 0 prefix = [0] + list(itertools.accumulate(arr)) for i in range(1, len(prefix)): for j in range(i): if (i+j) % 2 == 0: continue result += prefix[i] - prefix[j] return result
sum-of-all-odd-length-subarrays
Python, Prefix Sum Technique (Much Faster than brute force)
dev-josh
1
139
sum of all odd length subarrays
1,588
0.835
Easy
23,347
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2846579/For-beginner-and-easy-approach
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: sum1 = 0 n=len(arr) for i in range (n): s=0 for j in range(i,n): s += arr[j] if (j-i)%2==0: # checking even because indexes starts from 0 as its even sum1 += s return sum1
sum-of-all-odd-length-subarrays
For beginner and easy approach
Soumodip
0
2
sum of all odd length subarrays
1,588
0.835
Easy
23,348
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2824147/Python-simple-solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: total=0 l=len(arr) for i in range(l): total += (((i+1)*(l-i) +1)//2)*arr[i] return total
sum-of-all-odd-length-subarrays
Python simple solution
Just_03
0
3
sum of all odd length subarrays
1,588
0.835
Easy
23,349
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2803049/Simple-7-lines-brute-force-solution.
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: """ Solution #1. Brute force. Iterate over each element in array. Iterate over all possible sizes of the odd arrays. Sum up current element with sums of all possible odd-lenght sub arrays. Runtime: O(N * N). Space (1) """ result = 0 for i in range(len(arr)): j = i + 1 while j <= len(arr): result += sum(arr[i:j]) j += 2 return result
sum-of-all-odd-length-subarrays
Simple 7-lines brute-force solution.
denisOgr
0
4
sum of all odd length subarrays
1,588
0.835
Easy
23,350
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2800899/Sum-of-All-Odd-Length-Subarrays-or-Python
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: total, n = 0, len(arr) for i in range(n): times = ((i+1)*(n-i)+1)//2 total += times * arr[i] return total
sum-of-all-odd-length-subarrays
Sum of All Odd Length Subarrays | Python
jashii96
0
4
sum of all odd length subarrays
1,588
0.835
Easy
23,351
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2793317/Easy-python-please-help-with-time-complexity
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: _sum = sum(arr) i=3 while i<=len(arr): for j in range((len(arr)-i)+1): _chunk = arr[j:j+i] _sum += sum(_chunk) i+=2 return _sum
sum-of-all-odd-length-subarrays
Easy python - please help with time complexity?
ATHBuys
0
3
sum of all odd length subarrays
1,588
0.835
Easy
23,352
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2787826/Sliding-Window-beginner-friendly-easy-to-DEBUG
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: k = 1 total = 0 while k <= len(arr): for i in range(len(arr)-k+1): total += sum(arr[i:i+k]) k += 2 return total
sum-of-all-odd-length-subarrays
Sliding Window, beginner friendly, easy to DEBUG
karanvirsagar98
0
4
sum of all odd length subarrays
1,588
0.835
Easy
23,353
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2773963/Python-or-O(n)-Maths-Solution-(57-ms)
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: n = len(arr) if n == 1: return arr[0] m = n // 2 ans = 0 if n &amp; 1: # That is, n is odd. k = m + 1 j = k if n % 4 == 1: # n ≡ 1 mod 4 # Take care of three "central" values. ans += (2*(n//4)**2 + (n+1)//2) * sum(arr[m-1:m+2]) - arr[m-1] - arr[m+1] else: # n ≡ 3 mod 4 # Take care of three "central" values. ans += (2*((n+1)//4)**2) * sum(arr[m-1:m+2]) # Now sum the rest... for i in range(m-1): if (i &amp; 1) == 0: j -= 2 ans += k*(arr[i] + arr[-i-1]) k += j else: # Even case j = m k = m for i in range(m): ans += k*(arr[i] + arr[-i-1]) j -= 1 k += j return ans
sum-of-all-odd-length-subarrays
Python | O(n) Maths Solution (57 ms)
on_danse_encore_on_rit_encore
0
3
sum of all odd length subarrays
1,588
0.835
Easy
23,354
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2713473/Python-easy-solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: ans = 0 # sum of all odd length subarrays j = 1 for i in range(len(arr)): s = 0 # sum of all odd length subarrays containing/starting with current element arr[i] # print('loop no.',i) -> breakpoint for help while j <= len(arr): s += sum(arr[i:j]) # print('s:',s, arr[i:j]) -> breakpoint for help j += 2 ans += s j = i return ans
sum-of-all-odd-length-subarrays
Python easy solution
anandanshul001
0
9
sum of all odd length subarrays
1,588
0.835
Easy
23,355
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2697777/Python-3-solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: len_arr = len(arr) check_for = [i for i in range(len_arr+1) if i&amp;1 and i>1] res = sum(arr) # case of 1 for r in check_for: i = 0 while i + r <= len_arr: res += sum(arr[i:r+i]) i += 1 return res
sum-of-all-odd-length-subarrays
Python 3 solution
sipi09
0
6
sum of all odd length subarrays
1,588
0.835
Easy
23,356
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2686444/PYTHON3
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: Sum=0 for i in range(1,len(arr)+1,2): for j in range(len(arr)-i+1): Sum += sum(arr[j:j+i]) return Sum
sum-of-all-odd-length-subarrays
PYTHON3
Gurugubelli_Anil
0
2
sum of all odd length subarrays
1,588
0.835
Easy
23,357
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2685336/Python-easy-solution.-No-fancy-stuff-but-it-does-the-job-quite-well
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: a=0 for i in range(len(arr)): for j in range(i,len(arr),2): a+=sum(arr[i:j+1]) return a
sum-of-all-odd-length-subarrays
Python easy solution. No fancy stuff but it does the job quite well
Navaneeth7
0
5
sum of all odd length subarrays
1,588
0.835
Easy
23,358
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2623551/Python3-or-Solved-Using-Prefix-Sum-and-Considering-Increasing-Length-of-Odd-Subarrays
class Solution: #Let n = len(arr)! #Time-Complexity: O(n + n + n + ((n - 3 // 2) + 1)) -> O(n) #Space-Complexity: O(n), due to prefix sum array! def sumOddLengthSubarrays(self, arr: List[int]) -> int: #Approach: Consider subarrays of increasing odd sizes: 1, 3, 5, etc. #However, for each subarray, you would have to linearly traverse to get it sum! #Instead, we can utilize prefix sum to do this in constant time! prefix_sum = [None for i in range(len(arr))] #initialize prefix_sum! prefix_sum[0] = arr[0] for i in range(1, len(prefix_sum),1): prefix_sum[i] = prefix_sum[i-1] + arr[i] #now, we try odd-length subarrs of increasing size! #first of all, we can try all length-1 odd subarrays, which is basically for each element! ans = sum(arr) #now deal with odd-length of 3, 5, 7, etc as allowable! #define helper function that computes all odd-length subarrays of given size k and returns #sum of all such subarrays! def helper(k): nonlocal arr,prefix_sum summation = 0 # i points to index pos. of first element for each subarray of odd size k! for i in range(0, len(arr) - k + 1): prev, end = i - 1, i + k - 1 #we need to subtract away sum of all elements up to index i - 1! #however, if i-1 is not greater than or equal to 0, we simply initialize it to 0! -> #This is the case when first element is at index pos. 0 and nothing comes before! subtract_away = prefix_sum[i-1] if i - 1 >= 0 else 0 up_to = prefix_sum[end] summation += (up_to - subtract_away) return summation #if a particular odd-length causes helper to return sum of 0, that means that #the current size of subarray exceeds size of input array so stop and return ans! #start from odd-length of 3! cur_length = 3 while True: res = helper(cur_length) if(res == 0): break else: ans += res #update current size of subarray to be 2 more: look at next higher odd length! cur_length += 2 return ans
sum-of-all-odd-length-subarrays
Python3 | Solved Using Prefix Sum and Considering Increasing Length of Odd-Subarrays
JOON1234
0
25
sum of all odd length subarrays
1,588
0.835
Easy
23,359
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2616974/Faster-and-clean-PYTHON-solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: pref_arr = [0]*len(arr) pref_arr[0]=arr[0] for i in range(1,len(arr)): pref_arr[i]=pref_arr[i-1]+arr[i] sum=0 for i in range(1,len(arr)+1,2): j=0 while i+j<=len(arr): if j==0: sum+=pref_arr[i+j-1] else: sum+=pref_arr[i+j-1]-pref_arr[j-1] j+=1 return sum
sum-of-all-odd-length-subarrays
Faster and clean PYTHON solution
Abdulahad_Abduqahhorov
0
45
sum of all odd length subarrays
1,588
0.835
Easy
23,360
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2589892/Python3-or-Easy-to-Understand-or-Hashing
class Solution: def sumOddLengthSubarrays(self, ar: List[int]) -> int: n = len(ar) max_len = n if n%2 else n-1 dict_ = {} dict_[(ar[0],0)] = ar[0] for idx in range(1,n): dict_[(ar[idx],idx)] = dict_.get((ar[idx-1],idx-1)) + ar[idx] sum = 0 for odd_len in range(1,max_len+1,2): for idx in range(odd_len-1,n): curr_sum = dict_[(ar[idx],idx)] if idx - odd_len >= 0: prev_idx = idx-odd_len curr_sum -= dict_[(ar[prev_idx],prev_idx)] #print(f'Odd_len {odd_len} of Ar val {ar[idx]} sum - {curr_sum}') sum += curr_sum return sum
sum-of-all-odd-length-subarrays
Python3 | Easy to Understand | Hashing
anurag899
0
65
sum of all odd length subarrays
1,588
0.835
Easy
23,361
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2577121/simple-python-solution.-easy-understand
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: result = 0 array_len = len(arr) for i in arr: result += i for x in range(array_len): for y in range(x+1, array_len): diff = y - x if diff % 2 == 0: result += sum(arr[x:y+1]) return result
sum-of-all-odd-length-subarrays
simple python solution. easy understand
maschwartz5006
0
53
sum of all odd length subarrays
1,588
0.835
Easy
23,362
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2448566/Python3-Solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: list1=[] for i in range(len(arr)+1): for j in range(i): if (len(arr[j:i])%2)!=0: list1.append(arr[j:i]) return sum(map(sum,list1))
sum-of-all-odd-length-subarrays
Python3 Solution
Coder0212
0
48
sum of all odd length subarrays
1,588
0.835
Easy
23,363
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2317660/Sum-of-all-odd-length-subarrays
```class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: sume = sum(arr) k = 2 i = 0 j = 2 while True: if j == len(arr): i = 0 j = k + 2 k = k + 2 if j >= len(arr): break sume += sum(arr[i:j+1]) i += 1 j += 1 return (sume)
sum-of-all-odd-length-subarrays
Sum of all odd length subarrays
Jonny69
0
137
sum of all odd length subarrays
1,588
0.835
Easy
23,364
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2289326/38ms-easy-fast-simplest-logic
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: output = sum(arr) length = len(arr)+1 for l in range(3,length , 2): for i in range(length-l): output += sum(arr[i:l+i]) return output
sum-of-all-odd-length-subarrays
38ms easy fast simplest logic
ashish_p34
0
81
sum of all odd length subarrays
1,588
0.835
Easy
23,365
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2185740/Python-Simple-Python-Solution-By-Generating-All-Subarray
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: result = 0 for i in range(len(arr)): for j in range(i,len(arr)): if (j+1-i) % 2 != 0: result = result + sum(arr[i:j+1]) return result
sum-of-all-odd-length-subarrays
[ Python ] ✅✅ Simple Python Solution By Generating All Subarray 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
148
sum of all odd length subarrays
1,588
0.835
Easy
23,366
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2159987/Piece-Of-Cake-Python
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: size = len(arr) max_step = size if size%2 else size-1 step = 1 ans = list() while step<=max_step: for i in range(size): if i+step>=size+1: continue else: ans.append(sum(arr[i:i+step])) step +=2 return sum(ans)
sum-of-all-odd-length-subarrays
Piece Of Cake 🍰 [Python]
2bumaher
0
137
sum of all odd length subarrays
1,588
0.835
Easy
23,367
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2063482/Python-easy-to-read-and-understand
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: ans = 0 n = len(arr) for i in range(n): starts, ends = n-i, i+1 temp = starts*ends if temp%2 == 0: ans += temp//2*arr[i] else: ans += (temp//2 + 1)*arr[i] return ans
sum-of-all-odd-length-subarrays
Python easy to read and understand
sanial2001
0
148
sum of all odd length subarrays
1,588
0.835
Easy
23,368
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/2019895/Python3-DP-O(N)
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: if len(arr) == 0: return 0 if len(arr) == 1: return 1 endCnt = [1, 1] for i in range(2, len(arr)): endCnt.append(endCnt[i-2]+1) preprocess = [arr[0], arr[1]] for i in range(2, len(arr)): preprocess.append(endCnt[i-2]*(arr[i-1]+arr[i])+preprocess[i-2]+arr[i]) return sum(preprocess)
sum-of-all-odd-length-subarrays
Python3 DP O(N)
Eminemozart
0
63
sum of all odd length subarrays
1,588
0.835
Easy
23,369
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1884998/Python-Solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: result = 0 arr_len = len(arr) for i in range(0, arr_len, 2): for j in range(arr_len - i): result += sum(arr[j:i + j + 1]) return result
sum-of-all-odd-length-subarrays
Python Solution
hgalytoby
0
194
sum of all odd length subarrays
1,588
0.835
Easy
23,370
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1878890/Python-easy-solution
class Solution: def sumOddLengthSubarrays(self, arr): summe = 0 length = len(arr) for i in range(length+1): if i%2 != 0: for ind in range(length): if len(arr[ind:(i+ind)]) == i: summe += sum(arr[ind:(i+ind)]) return summe
sum-of-all-odd-length-subarrays
Python easy solution
poliliu
0
144
sum of all odd length subarrays
1,588
0.835
Easy
23,371
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1878584/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: output = [] count = 0 for i in range(0, len(arr)+1): for j in range(0, len(arr)+1): if arr[i:j] != []: output.append(arr[i:j]) for i in output: if len(i) % 2 != 0: count+=sum(i) return count
sum-of-all-odd-length-subarrays
Python (Simple Approach and Beginner-Friendly)
vishvavariya
0
140
sum of all odd length subarrays
1,588
0.835
Easy
23,372
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1869667/Python-3-solution
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: final_sum = 0 for i in range(len(arr)): for j in range(len(arr) + 1): sliced = arr[:j] if len(sliced) % 2 == 1: final_sum += sum(sliced) if j == len(arr): arr.pop(0) return final_sum
sum-of-all-odd-length-subarrays
Python 3 solution
zuzannakilar
0
105
sum of all odd length subarrays
1,588
0.835
Easy
23,373
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1828013/4-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-80
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: ans=0 for i in range(len(arr)): for j in range(i,len(arr),2): ans+=sum(arr[i:j+1]) return ans
sum-of-all-odd-length-subarrays
4-Lines Python Solution || 75% Faster || Memory less than 80%
Taha-C
0
107
sum of all odd length subarrays
1,588
0.835
Easy
23,374
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1779472/Python3-Solution-or-99.04-lesser-memory
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: total = 0 for i in range(len(arr)): for j in range(i+1, len(arr)+1): if len(arr[i:j])%2 == 1: total += sum(arr[i:j]) return total
sum-of-all-odd-length-subarrays
✔Python3 Solution | 99.04% lesser memory
Coding_Tan3
0
153
sum of all odd length subarrays
1,588
0.835
Easy
23,375
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1558145/WEEB-DOES-PYTHON
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: queue = deque([]) for i in range(len(arr)): queue.append((i, arr[i])) return self.bfs(queue, arr) def bfs(self, queue, nums): total = 0 while queue: idx, curSum = queue.popleft() total += curSum if idx+2 < len(nums): queue.append((idx+2, curSum + sum(nums[idx+1:idx+3]))) return total
sum-of-all-odd-length-subarrays
WEEB DOES PYTHON
Skywalker5423
0
231
sum of all odd length subarrays
1,588
0.835
Easy
23,376
https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/discuss/858448/Python3-mark-and-sweep
class Solution: def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int: chg = [0]*len(nums) # change for i, j in requests: chg[i] += 1 if j+1 < len(nums): chg[j+1] -= 1 for i in range(1, len(nums)): chg[i] += chg[i-1] # cumulated change return sum(n*c for n, c in zip(sorted(nums), sorted(chg))) % 1_000_000_007
maximum-sum-obtained-of-any-permutation
[Python3] mark & sweep
ye15
0
39
maximum sum obtained of any permutation
1,589
0.37
Medium
23,377
https://leetcode.com/problems/make-sum-divisible-by-p/discuss/1760163/WEEB-DOES-PYTHONC%2B%2B
class Solution: def minSubarray(self, nums: List[int], p: int) -> int: dp = defaultdict(int) dp[0] = -1 target = sum(nums) % p curSum = 0 result = len(nums) if sum(nums) % p == 0: return 0 for i in range(len(nums)): curSum += nums[i] curMod = curSum % p temp = (curSum - target) % p if temp in dp: if i - dp[temp] < result: result = i - dp[temp] dp[curMod] = i return result if result < len(nums) else -1
make-sum-divisible-by-p
WEEB DOES PYTHON/C++
Skywalker5423
2
153
make sum divisible by p
1,590
0.28
Medium
23,378
https://leetcode.com/problems/make-sum-divisible-by-p/discuss/1444032/python-O(n)-time-O(1)-space
class Solution: def minSubarray(self, nums: List[int], p: int) -> int: s = sum(nums) if s % p == 0: return 0 moddict = {} minv = float('inf') t = 0 moddict[0] = 0 cnt = 1 for num in nums: t = (t + num) % p if (t-s) % p in moddict: minv = min(minv, cnt - moddict[(t-s)%p]) moddict[t] = cnt cnt += 1 if minv == float('inf') or minv == len(nums): return -1 else: return minv
make-sum-divisible-by-p
python O(n) time, O(1) space
byuns9334
0
244
make sum divisible by p
1,590
0.28
Medium
23,379
https://leetcode.com/problems/make-sum-divisible-by-p/discuss/858516/Python3-two-approaches
class Solution: def minSubarray(self, nums: List[int], p: int) -> int: suffix = [0] for x in reversed(nums): suffix.append((suffix[-1] + x)%p) suffix.reverse() if suffix[0] % p == 0: return 0 # edge case ans = inf prefix = 0 seen = {0: -1} for i, x in enumerate(nums): if (p - suffix[i+1])%p in seen: ans = min(ans, i - seen[(p - suffix[i+1])%p]) prefix = (prefix + x) % p seen[prefix] = i return ans if ans < len(nums) else -1
make-sum-divisible-by-p
[Python3] two approaches
ye15
0
117
make sum divisible by p
1,590
0.28
Medium
23,380
https://leetcode.com/problems/make-sum-divisible-by-p/discuss/858516/Python3-two-approaches
class Solution: def minSubarray(self, nums: List[int], p: int) -> int: target = sum(nums) % p # targetted remainder ans = inf seen = {(prefix := 0): -1} for i, x in enumerate(nums): seen[(prefix := (prefix+x)%p)] = i # update seen before check if (prefix-target) % p in seen: ans = min(ans, i - seen[(prefix-target) % p]) return ans if ans < len(nums) else -1 # not allowed to remove whole array
make-sum-divisible-by-p
[Python3] two approaches
ye15
0
117
make sum divisible by p
1,590
0.28
Medium
23,381
https://leetcode.com/problems/strange-printer-ii/discuss/911370/Same-as-CourseSchedule-Topological-sort.
class Solution: def isPrintable(self, targetGrid: List[List[int]]) -> bool: visited = [0] * 61 graph = collections.defaultdict(set) m, n = len(targetGrid), len(targetGrid[0]) for c in range(1, 61): l,r,t,b = n,-1,m,-1 #to specify the covered range of color c for i in range(m): for j in range(n): if targetGrid[i][j] == c: l = min(l, j) r = max(r, j) t = min(t, i) b = max(b, i) #to find the contained colors for i in range(t, b + 1): for j in range(l, r + 1): if targetGrid[i][j] != c: graph[targetGrid[i][j]].add(c) # to find if there is a cycle def dfs(graph,i): if visited[i] == -1: return False if visited[i] == 1: return True visited[i] = -1 for j in graph[i]: if not dfs(graph,j): return False visited[i] = 1 return True for c in range(61): if not dfs(graph,c): return False return True
strange-printer-ii
Same as CourseSchedule, Topological sort.
Sakata_Gintoki
17
810
strange printer ii
1,591
0.584
Hard
23,382
https://leetcode.com/problems/strange-printer-ii/discuss/1516602/toposort-concept-or-python-code
class Solution(object): def isPrintable(self, targetGrid): """ :type targetGrid: List[List[int]] :rtype: bool """ #doing reverse engineering like toposort concept find that reactangle which is completely independent,and remove and process futher m,n=len(targetGrid),len(targetGrid[0]) # strore upper,left,right,bottom most for every color colors={} for i in range(m): for j in range(n): c=targetGrid[i][j] if c not in colors: colors[c]=[sys.maxsize,sys.maxsize,-1*sys.maxsize,-1*sys.maxsize] colors[c][0]=min(colors[c][0],i) colors[c][1]=min(colors[c][1],j) colors[c][2]=max(colors[c][2],j) colors[c][3]=max(colors[c][3],i) # print(colors) # this is for check is it possible to fill with this color or not def isPossibleTofill(color): upper,left,right,bottom=colors[color] for i in range(upper,bottom+1): for j in range(left,right+1): if targetGrid[i][j]>0 and targetGrid[i][j]!=color:return False for i in range(upper,bottom+1): for j in range(left,right+1): targetGrid[i][j]=0 return True c1=colors.keys() while c1: c2=set() for col in c1: if isPossibleTofill(col)==False: c2.add(col) if len(c2)==len(c1):return False c1=c2 if len(c1)==0:return True return False
strange-printer-ii
toposort concept | python code
13as1827000713
2
163
strange printer ii
1,591
0.584
Hard
23,383
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1834393/Python-simple-and-elegant
class Solution(object): def reorderSpaces(self, text): word_list = text.split() words, spaces = len(word_list), text.count(" ") if words > 1: q, r = spaces//(words-1), spaces%(words-1) return (" " * q).join(word_list) + " " * r else: return "".join(word_list) + " " * spaces
rearrange-spaces-between-words
Python - simple and elegant
domthedeveloper
3
176
rearrange spaces between words
1,592
0.437
Easy
23,384
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1834393/Python-simple-and-elegant
class Solution(object): def reorderSpaces(self, text): word_list = text.split() words, spaces = len(word_list), text.count(" ") if words > 1: q, r = spaces//(words-1), spaces%(words-1) else: q, r = 0, spaces return (" " * q).join(word_list) + " " * r
rearrange-spaces-between-words
Python - simple and elegant
domthedeveloper
3
176
rearrange spaces between words
1,592
0.437
Easy
23,385
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1834393/Python-simple-and-elegant
class Solution(object): def reorderSpaces(self, text): word_list = text.split() words, spaces = len(word_list), text.count(" ") if words > 1: q, r = divmod(spaces, (words - 1)) else: q, r = 0, spaces return (" " * q).join(word_list) + " " * r
rearrange-spaces-between-words
Python - simple and elegant
domthedeveloper
3
176
rearrange spaces between words
1,592
0.437
Easy
23,386
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1834393/Python-simple-and-elegant
class Solution(object): def reorderSpaces(self, text): w, s = len(text.split()), text.count(" ") q, r = (divmod(s, (w - 1))) if w > 1 else (0, s) return (" " * q).join(text.split()) + " " * r
rearrange-spaces-between-words
Python - simple and elegant
domthedeveloper
3
176
rearrange spaces between words
1,592
0.437
Easy
23,387
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1834393/Python-simple-and-elegant
class Solution(object): def reorderSpaces(self, text): return "".join(text.split()) + " " * text.count(" ") if len(text.split()) <= 1 else (" " * (text.count(" ")//(len(text.split())-1))).join(text.split()) + " " * (text.count(" ") % (len(text.split())-1))
rearrange-spaces-between-words
Python - simple and elegant
domthedeveloper
3
176
rearrange spaces between words
1,592
0.437
Easy
23,388
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/858790/Python3-Intuitive-Simple
class Solution: def reorderSpaces(self, text: str) -> str: space = 0 # Count number of spaces for char in list(text): if char ==' ': space += 1 words = text.split() num_words = len(words) # Count number of spaces after each word spaces_per_word = space // (num_words-1) if num_words > 1 else num_words output = [] # Append the words, followed by the spaces (also keep a count of the number of spaces reduced) for idx in range(len(words)-1): output.append(words[idx]) for _ in range(spaces_per_word): output.append(' ') space -= 1 # Append the last word followed by the remaining spaces if len(words) > 0: output.append(words[-1]) while space > 0: output.append(' ') space -= 1 # Return the string return ''.join(output)
rearrange-spaces-between-words
[Python3] Intuitive Simple
nachiketsd
3
121
rearrange spaces between words
1,592
0.437
Easy
23,389
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/858193/Python3-concise-4-line
class Solution: def reorderSpaces(self, text: str) -> str: ns = text.count(" ") # count of spaces nw = len(text := text.split()) # count of words if nw > 1: nw, ns = divmod(ns, nw-1) # nw - between word spaces / ns - trailing spaces return (" "*nw).join(text) + " "*ns
rearrange-spaces-between-words
[Python3] concise 4-line
ye15
2
133
rearrange spaces between words
1,592
0.437
Easy
23,390
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/2761138/Simple-Python-Solution
class Solution: def reorderSpaces(self, text: str) -> str: spaces = 0 for i in text: if i == " ": spaces+=1 text1 = text.split(" ") temp = [] words = 0 for i in text1: if i == "": continue else: words += 1 temp.append(i) if words == 1: if spaces: return (temp[0]+(spaces*" ")) else: return text space_between_words = spaces//(words-1) if spaces%(words-1) == 0: return (((space_between_words*" ").join(temp))) else: ans = '' for i in temp: ans+=i if spaces >= space_between_words: ans+= (space_between_words*" ") spaces -= space_between_words return (ans+(spaces*" "))
rearrange-spaces-between-words
Simple Python Solution
aniketbhamani
1
29
rearrange spaces between words
1,592
0.437
Easy
23,391
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/2356961/Easy-understandable-Python-code
class Solution: def reorderSpaces(self, text: str) -> str: spaces = 0 for i in text: if i==" ": spaces+=1 words = text.split() num_words = len(words) if num_words==1: return words[0]+(" "*spaces) space = spaces//(num_words-1) extra= spaces%(num_words-1) ans="" for i in words: ans+=i ans+=space*" " ans=ans[:-space] ans+=extra*" " return ans
rearrange-spaces-between-words
Easy understandable Python code
sunakshi132
1
54
rearrange spaces between words
1,592
0.437
Easy
23,392
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1442638/Count-spaces-and-split-into-words-84-speed
class Solution: def reorderSpaces(self, text: str) -> str: spaces = text.count(" ") words = [w for w in text.strip(" ").split(" ") if w] len_words = len(words) if len_words > 1: equal_spaces, remainder = divmod(spaces, len_words - 1) separator = " " * equal_spaces return separator.join(words) + " " * remainder return words[0] + " " * spaces
rearrange-spaces-between-words
Count spaces and split into words, 84% speed
EvgenySH
1
174
rearrange spaces between words
1,592
0.437
Easy
23,393
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/975520/Python-A-one-liner*
class Solution: def reorderSpaces(self, text: str) -> str: words = text.split() cw = len(words) cs = text.count(' ') return f'{" "*(cs // (cw-1))}'.join(words) + " "*(cs % (cw-1)) if cw > 1 else ''.join(words) + " "*cs
rearrange-spaces-between-words
Python - A one-liner*
limtis
1
106
rearrange spaces between words
1,592
0.437
Easy
23,394
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/2194620/Python-solution
class Solution: def reorderSpaces(self, text: str) -> str: spc = text.count(' ') if spc == 0: return text words = [x for x in text.split() if x] word_count = len(words) if word_count == 1: return words[0]+ ' ' * spc sp_betw = spc//(word_count-1) last_space = spc%(word_count-1) return (' '*sp_betw).join(words) + ' '*last_space
rearrange-spaces-between-words
Python solution
StikS32
0
34
rearrange spaces between words
1,592
0.437
Easy
23,395
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/2156171/python-simple-solution
class Solution: def reorderSpaces(self, text: str) -> str: # evaluate the number of spaces num_spaces = sum(i == ' ' for i in text) # remove spaces and convert string to list of words text = text.split() # initialize variable to store - space btw words &amp; extra space to be added at the end spaces, extra_spaces = 0,0 if len(text) > 1: # use inbuilt divmod function spaces, extra_spaces = divmod(num_spaces,(len(text) - 1)) else: extra_spaces = num_spaces # make the new string return (" " * spaces).join(text) + (" " * extra_spaces)
rearrange-spaces-between-words
✅ python simple solution
Nk0311
0
35
rearrange spaces between words
1,592
0.437
Easy
23,396
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1789946/4-Lines-Python-Solution-oror-85-Faster-(31ms)-oror-Memory-Less-than-99
class Solution: def reorderSpaces(self, text: str) -> str: words, spaces = text.split(), len([x for x in text if x==' ']) if ' ' not in text: return text if len(words) == 1: return words[0]+' '*spaces return (' '*(spaces//(len(words)-1))).join(words) + ' '*(spaces%(len(words)-1))
rearrange-spaces-between-words
4-Lines Python Solution || 85% Faster (31ms) || Memory Less than 99%
Taha-C
0
68
rearrange spaces between words
1,592
0.437
Easy
23,397
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1759355/Python-dollarolution-(faster-than-98-and-better-memory-use-than-95)
class Solution: def reorderSpaces(self, text: str) -> str: d = {' ': 0} for i in text: if i == ' ': d[i] += 1 text = text.split() if len(text) == 1: return text[0]+(' '*d[' ']) l, x = d[' '] // (len(text) - 1), d[' '] % (len(text) - 1) return (' '*l).join(text) + (' '*x)
rearrange-spaces-between-words
Python $olution (faster than 98% and better memory use than 95%)
AakRay
0
93
rearrange spaces between words
1,592
0.437
Easy
23,398
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1755512/Python3-or-Faster-than-98.39
class Solution: def reorderSpaces(self, text: str) -> str: count_space = text.count(" ") words = text.split() if count_space == 0 or words is None: return text words_len = len(words) if words_len == 1: return text.lstrip().rstrip() + " " * count_space words_len -= 1 space_between_word = count_space // words_len end_space = count_space % words_len return (" " * space_between_word).join(words).lstrip() + " " * end_space
rearrange-spaces-between-words
Python3 | Faster than 98.39%
khalidhassan3011
0
45
rearrange spaces between words
1,592
0.437
Easy
23,399