post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/491784/Python3-Floyd-Warshall-algo
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: """Floyd-Warshall algorithm""" dist = [[float("inf")]*n for _ in range(n)] for i in range(n): dist[i][i] = 0 for i, j, w in edges: dist[i][j] = dist[j][i] = w for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) ans = {sum(d <= distanceThreshold for d in dist[i]): i for i in range(n)} return ans[min(ans)]
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
[Python3] Floyd-Warshall algo
ye15
2
98
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,000
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/1137275/Python-or-Dijkstra's-Algorithm-or-Faster-than-97
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: graph = {i:dict() for i in range(n)} for u,v,w in edges: graph[u][v] = w graph[v][u] = w neighbors = [0]*n for k in range(n): dist = [float('inf')]*n dist[k] = 0 visited = [False]*n queue = [(0, k)] heapify(queue) count = -1 while len(queue): minVal, minNode = heappop(queue) if minVal > distanceThreshold: break if visited[minNode]: continue visited[minNode] = True count += 1 for node in graph[minNode]: if not visited[node] and dist[minNode] + graph[minNode][node] < dist[node]: dist[node] = dist[minNode] + graph[minNode][node] heappush(queue, (dist[node], node)) neighbors[k] = count curMin = neighbors[0] ans = 0 for i in range(n): if neighbors[i] <= curMin: ans = i curMin = neighbors[i] return ans
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Python | Dijkstra's Algorithm | Faster than 97%
anuraggupta29
1
377
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,001
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/490606/Python-Floyd-Warshall-DP
class Solution: def findTheCity(self, n: int, edges: List[List[int]], dt: int) -> int: dist = [[int(1e9)] * n for i in range(n)] for i, j, d in edges: dist[i][j] = dist[j][i] = d for i in range(n): dist[i][i] = 0 for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) city_res = [[] for i in range(n)] city_min_cnt = int(1e9) for i in range(n): for j in range(n): if dist[i][j] <= dt: city_res[i].append(j) if len(city_res[i]): city_min_cnt = min(len(city_res[i]), city_min_cnt) res = [] for i in range(n): if len(city_res[i]) == city_min_cnt: res.append(i) return max(res)
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Python Floyd Warshall DP
Bug_Exceeded
1
201
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,002
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/2735594/Simple-floyd-warshall
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: distances = [[float("inf")]*n for _ in range(n)] for city1,city2,dist in edges: distances[city1][city2] = dist distances[city2][city1] = dist for city in range(n): distances[city][city] = 0 for via in range(n): for i in range(n): for j in range(n): distances[i][j] = min(distances[i][j], distances[i][via]+distances[via][j]) best_count = n+1 city = -1 for src_city in range(n): count = 0 for dist in distances[src_city]: if dist <= distanceThreshold: count += 1 if count <= best_count: best_count = count city = src_city return city
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Simple floyd warshall
shriyansnaik
0
2
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,003
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/2735576/Using-Djikstra
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: graph = defaultdict(list) for city1,city2,dist in edges: graph[city1].append((city2,dist)) graph[city2].append((city1,dist)) best_count = n+1 city = -1 for src_city in range(n): distance = [float("inf")]*n distance[src_city] = 0 minHeap = [] heappush(minHeap,(0,src_city)) while minHeap: dist,node = heappop(minHeap) for nei_node,nei_dist in graph[node]: new_dist = dist + nei_dist if new_dist < distance[nei_node]: distance[nei_node] = new_dist heappush(minHeap,(new_dist,nei_node)) count = 0 for dist in distance: if dist <= distanceThreshold: count += 1 if count <= best_count: best_count = count city = src_city return city
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Using Djikstra
shriyansnaik
0
4
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,004
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/2733062/Python-Dijksta's-Solution-explained
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: graph = {i:[] for i in range(n)} for u, v, wt in edges: graph[u].append((v, wt)) graph[v].append((u, wt)) def dijksta(city): dist = [float('inf')] * n dist[city] = 0 heap = [] heapq.heappush(heap, (0, city)) while heap: dis, node = heapq.heappop(heap) for adj in graph[node]: adj_city, adj_dis = adj[0], adj[1] if adj_dis + dist[node] < dist[adj_city]: dist[adj_city] = adj_dis + dist[node] heapq.heappush(heap, (dist[adj_city], adj_city)) return dist count = [0] * n res = 0 for city in range(n): distance = dijksta(city) count[city] = sum(1 if dis <= distanceThreshold else 0 for dis in distance) if count[city] <= count[res]: res = city return res
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Python Dijksta's Solution explained
kritikaparmar
0
17
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,005
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/2671727/Python-diji-beats-98.85
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: graph = {node : [] for node in range(n)} adj = [[float('inf')]*n for _ in range(n)] for i,j,k in edges: graph[i].append(j) graph[j].append(i) adj[i][j]=min(adj[i][j],k) adj[j][i]=min(adj[j][i],k) ans = [0]*n ma = 0 def diji(node:int): dis = [float('inf')]*n st = [0]*n dis[node]=0 heap = [] heapq.heapify(heap) heapq.heappush(heap,(0,node)) while heap: d,nod = heapq.heappop(heap) if st[nod]:continue st[nod]=1 if d<=distanceThreshold: ans[node]+=1 for ne in graph[nod]: if d+adj[nod][ne]<dis[ne]: dis[ne] = d+adj[nod][ne] heapq.heappush(heap,(d+adj[nod][ne],ne)) for i in range(n): diji(i) mi = float('inf') for i in range(n): mi = min(mi,ans[i]) for i in range(n-1,-1,-1): if ans[i]==mi:return i
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Python diji beats 98.85%
Ttanlog
0
19
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,006
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/2671719/Python-diji-beats-73.5
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: graph = {node : [] for node in range(n)} adj = [[float('inf')]*n for _ in range(n)] for i,j,k in edges: graph[i].append(j) graph[j].append(i) adj[i][j]=k adj[j][i]=k ans = [0]*n ma = 0 def diji(node:int): dis = [float('inf')]*n st = [0]*n dis[node]=0 heap = [] heapq.heapify(heap) heapq.heappush(heap,(0,node)) while heap: d,nod = heapq.heappop(heap) if st[nod]:continue st[nod]=1 if d<=distanceThreshold: ans[node]+=1 for ne in graph[nod]: if d+adj[nod][ne]<dis[ne]: dis[ne] = d+adj[nod][ne] heapq.heappush(heap,(d+adj[nod][ne],ne)) for i in range(n): diji(i) mi = float('inf') for i in range(n): mi = min(mi,ans[i]) for i in range(n-1,-1,-1): if ans[i]==mi:return i
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Python diji beats 73.5%
Ttanlog
0
8
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,007
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/2418868/City-with-smallest-number-of-neighbours-with-threshold-oror-Python3-oror-Floyd-Warshall
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: mat = [[math.inf] * n for i in range(n)] for i in range(n): # Distance of node to itself is zero mat[i][i] = 0 for i, j, wt in edges: # Adding weights of given edges in matrix mat[i][j] = wt mat[j][i] = wt # Using Floyd Warshall Algorithm for k in range(n): # For every vertice for i in range(n): for j in range(n): if(i == k or j == k): continue mat[i][j] = min(mat[i][j], mat[i][k] + mat[k][j]) # Count no. of neighbours reachable within threshold for every vertice min_neighbor = n ans = n-1 for i in range(n): count = 0 for j in range(n): if(mat[i][j] <= distanceThreshold and i != j): count += 1 if(count <= min_neighbor): min_neighbor = count ans = i return ans
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
City with smallest number of neighbours with threshold || Python3 || Floyd-Warshall
vanshika_2507
0
25
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,008
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/1060544/python3-dijkstra%3A-bfs-%2B-heap
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: # issue with DFS approach is that the typical seen set might cut off a # potential path, and maintaining a growing additional set for each # recursive call too slow (TLE) # so try breadth first (iterative), using min heap # heap inherently will choose the shortest edge to next vertex # and thus avoids the dfs "path cutoff" == dijsktra's algorithm # helper function takes (city) returns reachable cities # load heap with (net_cost, city) for correct min heap action! # O(V*E*logV) time g = defaultdict(list) for a,b,w in edges: g[a].append( (b,w) ) g[b].append( (a,w) ) def hlpr(city: int) -> int: h = [(0, city)] seen = set() while h: net_cost, city = heapq.heappop(h) if city in seen: continue seen.add(city) for path, fee in g[city]: if path not in seen and net_cost + fee <= distanceThreshold: heapq.heappush(h, (net_cost + fee, path)) return len(seen) - 1 min_reach, res = float("inf"), None for i in range(n): tmp = hlpr(i) if tmp <= min_reach: min_reach = tmp res = i return res def findTheCity1(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: # translate edges list to undirected, weighted graph # for each city (0 to n-1), use helper function to collect reachable cities # hlpr takes (city, funds, seen), stores reachable cities in visit set # if can cover cost / haven't already seen # recursive call with funds-cost and adding current city to seen # seen set passed within the helper function # TLE g = defaultdict(dict) for a,b,w in edges: g[a][b] = w g[b][a] = w def hlpr(city: int, funds: int, seen: Set) -> None: if funds == 0: return for path in g[city]: if path not in seen and g[city][path] <= funds: hlpr(path, funds - g[city][path], seen | set([city])) visit.add(path) min_reach, res = float("inf"), None for i in range(n): visit = set() hlpr(i, distanceThreshold, set()) if len(visit) <= min_reach: min_reach = len(visit) res = i return res
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
python3 - dijkstra: bfs + heap
dachwadachwa
0
76
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,009
https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/640979/Easy-Python-Solution-Floyd-Warshall-Algorithm
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: dis=[] for i in range(n): x=[] for j in range(n): x.append(float("inf")) dis.append(x) for i in range(len(edges)): x=edges[i] dis[x[0]][x[1]]=x[2] dis[x[1]][x[0]]=x[2] for k in range(n): for j in range(n): for i in range(n): if dis[i][j]>dis[i][k]+dis[k][j]: dis[i][j]=dis[i][k]+dis[k][j] d={} print(dis) for i in range(n): d[i]=0 for i in range(n): for j in range(n): if dis[i][j]<=distanceThreshold: if i==j: continue d[i]+=1 l=list(d.keys()) min=float("inf") for i in range(len(l)): if d[l[i]]<min: min=d[l[i]] ans=[] for i in range(len(l)): if d[l[i]]==min: ans.append(l[i]) return max(ans)
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Easy Python Solution-Floyd Warshall Algorithm
Ayu-99
0
108
find the city with the smallest number of neighbors at a threshold distance
1,334
0.533
Medium
20,010
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2709132/91-Faster-Solution
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: jobCount = len(jobDifficulty) if jobCount < d: return -1 @lru_cache(None) def topDown(jobIndex: int, remainDayCount: int) -> int: remainJobCount = jobCount - jobIndex if remainDayCount == 1: return max(jobDifficulty[jobIndex:]) if remainJobCount == remainDayCount: return sum(jobDifficulty[jobIndex:]) minDiff = float('inf') maxToday = 0 for i in range(jobIndex, jobCount - remainDayCount + 1): maxToday = max(maxToday, jobDifficulty[i]) minDiff = min(minDiff, maxToday + topDown(i+1, remainDayCount-1)) return minDiff return topDown(0, d)
minimum-difficulty-of-a-job-schedule
91% Faster Solution
namanxk
4
485
minimum difficulty of a job schedule
1,335
0.587
Hard
20,011
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2708974/Python-3-Memoized-and-Tabulated-Solution-(Credits%3A-Striver-DP-Series)
class Solution1: # Memoized Solution def minDifficulty(self, arr: List[int], d: int) -> int: if d>len(arr): return -1 n = len(arr) dp = [[-1 for i in range(d+1)] for j in range(n)] def f(ind,d): if ind==n: return float('inf') if d==1: # if we have only one day then we just take max of all remaining jobs return max(arr[ind:]) if dp[ind][d]!=-1: return dp[ind][d] ans = float('inf') mx = float('-inf') s = 0 for i in range(ind,n): mx = max(mx,arr[i]) s=mx+f(i+1,d-1) ans = min(ans,s) dp[ind][d] = ans return dp[ind][d] return f(0,d) class Solution: # Tabulation version def minDifficulty(self, arr: List[int], d: int) -> int: if d>len(arr): return -1 n = len(arr) dp = [[0 for i in range(d+1)] for j in range(n+1)] for i in range(d+1): # Base Cases dp[n][i] = float('inf') for i in range(n): # Base Case dp[i][1]=max(arr[i:]) for ind in range(n-1,-1,-1): for days in range(2,d+1): ans = float('inf') mx = float('-inf') s = 0 for i in range(ind,n): mx = max(mx,arr[i]) s=mx+dp[i+1][days-1] ans = min(ans,s) dp[ind][days] = ans return dp[0][d]
minimum-difficulty-of-a-job-schedule
Python 3 Memoized and Tabulated Solution (Credits: Striver DP Series)
Akash3502
2
91
minimum difficulty of a job schedule
1,335
0.587
Hard
20,012
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2708778/python3-or-dp-or-dfs-or-memoziation
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: n = len(jobDifficulty) @lru_cache(None) def dfs(index, remaining_days): if remaining_days == 0: if index == n: return 0 else: return sys.maxsize if index == n: if remaining_days == 0: return 0 else: return sys.maxsize ans = sys.maxsize count_max = 0 for i in range(index, n): count_max = max(count_max, jobDifficulty[i]) ans = min(ans, count_max + dfs(i+1, remaining_days-1)) return ans if n < d: return -1 return dfs(0, d)
minimum-difficulty-of-a-job-schedule
python3 | dp | dfs | memoziation
H-R-S
2
129
minimum difficulty of a job schedule
1,335
0.587
Hard
20,013
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2812707/Most-efficient-solution-with-detailed-comments-or-O(d*n)-100-or-O(n)-98.97
class Solution: def minDifficulty(self, diff: List[int], d: int) -> int: n = len(diff) if n < d: return -1 today = [None] * n yesterday = [diff[0]] + [None] * (n - 1) # Solution for day 0 is just the running maximum for i in range(1, n): yesterday[i] = max(yesterday[i - 1], diff[i]) for day in range(1, d): # stack contains all index i where today[i] has a solution with diff[i] # as the biggest stack = [] for i in range(day, n): today[i] = yesterday[i - 1] + diff[i] # Each iteration of the while loop we either add or remove an item. # Since each job is added and/or removed at most once for each day, # the time complexity is still O(d*n) while stack: # If the last job in the stack is less difficult than job i # then we can have the option to add job j+1 -> i to today[i] # Because solution at today[j] has diff[j] as the biggest, # so after add job j+1 -> i, the new biggest is diff[i], # thus the total diff is inceaseed by (diff[i] + diff[j]) if diff[stack[-1]] < diff[i]: j = stack.pop() today[i] = min(today[i], today[j] - diff[j] + diff[i]) else: # If we find a better solution at job i # then in this solution diff[i] is the biggest. # add it to the stack if today[i] < today[stack[-1]]: stack.append(i) # else job i is a part of the solution at today[stack[-1]] else: today[i] = today[stack[-1]] break else: # If stack is empty then of course we have a new solution at job i stack.append(i) yesterday = today.copy() return yesterday[-1]
minimum-difficulty-of-a-job-schedule
✨Most efficient solution with detailed comments | ⏱️O(d*n) - 100% | 💾O(n) - 98.97%
lone17
0
6
minimum difficulty of a job schedule
1,335
0.587
Hard
20,014
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2711599/Python-Memoized-Recursion-Simple-and-Intuitive
class Solution: def minDifficulty(self, jobDifficulties: List[int], days: int) -> int: n = len(jobDifficulties) @cache def dfs(i: int, days: int) -> int: if days == 0 or n - i < days: return -1 if days == 1: # we can't partition any more return max(jobDifficulties[i:]) res = math.inf curr_max = -math.inf for j in range(i, n - days + 1): # keep track of max in current "day" curr_max = max(curr_max, jobDifficulties[j]) # keep track of min difficulty seen res = min(res, curr_max + dfs(j + 1, days - 1)) return res return dfs(0, days)
minimum-difficulty-of-a-job-schedule
Python Memoized Recursion - Simple and Intuitive
CompileTimeError
0
22
minimum difficulty of a job schedule
1,335
0.587
Hard
20,015
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2711060/Python-Top-down-approach-with-mem-(Faster-than-93)
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: n = len(jobDifficulty) if n < d: return -1 dp = [[-1] * (d + 1) for _ in range(n + 1)] def helper(index, dayleft): if dp[index][dayleft] != -1: return dp[index][dayleft] if dayleft == 1: return max(jobDifficulty[index :]) else: best = float('inf') curr = 0 for i in range(index, n - dayleft + 1): curr = max(curr, jobDifficulty[i]) best = min(best, curr + helper(i + 1, dayleft - 1)) dp[index][dayleft] = best return best return helper(0, d)
minimum-difficulty-of-a-job-schedule
Python Top-down approach with mem (Faster than 93%)
KevinJM17
0
15
minimum difficulty of a job schedule
1,335
0.587
Hard
20,016
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2710875/PYTHON-solution-beats-96-users
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: @lru_cache(None) def dp(idx,d,curr): if idx == len(jobDifficulty) and d == 0: return curr if idx >= len(jobDifficulty) or d <= 0: return inf return min(dp(idx+1,d,max(curr,jobDifficulty[idx])), max(curr,jobDifficulty[idx])+dp(idx+1,d-1,0)) ans = dp(0,d,0) return ans if ans != inf else -1 10
minimum-difficulty-of-a-job-schedule
PYTHON solution beats 96% users
mritunjayyy
0
19
minimum difficulty of a job schedule
1,335
0.587
Hard
20,017
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2710476/DP-beating-95-in-time
class Solution: def minDifficulty(self, jd: List[int], d: int) -> int: n = len(jd) if n < d: return -1 elif n == d: return sum(jd) dic = {} def calc(i, restd, prev_max): if i == n or restd < 0: return float('inf') if (i, restd, prev_max) in dic: return dic[(i, restd, prev_max)] if n - i < restd: dic[(i, restd, prev_max)] = float('inf') return float('inf') elif n - i == restd: dic[(i, restd, prev_max)] = max(prev_max, jd[i]) + sum(jd[i + 1:]) return dic[(i, restd, prev_max)] else: if i == 0: dic[(i, restd, prev_max)] = calc(i + 1, restd, jd[i]) return dic[(i, restd, prev_max)] case1 = calc(i + 1, restd, max(prev_max, jd[i])) case2 = prev_max + calc(i + 1, restd - 1, jd[i]) dic[(i, restd, prev_max)] = min(case1, case2) return dic[(i, restd, prev_max)] return calc(0, d, 0)
minimum-difficulty-of-a-job-schedule
DP, beating 95% in time
leonine9
0
23
minimum difficulty of a job schedule
1,335
0.587
Hard
20,018
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2710470/Python-DP-solution
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: @cache def dfs(i,m,day): if day==d and i==len(jobDifficulty): return 0 if day==d or i==len(jobDifficulty): return inf return min(dfs(i+1,max(m,jobDifficulty[i]),day),max(m,jobDifficulty[i])+dfs(i+1,0,day+1)) ret=dfs(0,0,0) if ret==inf: return -1 else: return ret
minimum-difficulty-of-a-job-schedule
Python DP solution
DhruvBagrecha
0
13
minimum difficulty of a job schedule
1,335
0.587
Hard
20,019
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2710355/python3-Recursion-and-Dp-solution-for-reference
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: N = len(jobDifficulty) if len(jobDifficulty) < d: return -1 maxLookup = [-1]*N maxLookup[-1] = jobDifficulty[-1] for i in range(N-2, -1, -1): maxLookup[i] = max(jobDifficulty[i], maxLookup[i+1]) def bt(idx, dt, mincarry): print (idx, dt, mincarry) if idx == len(jobDifficulty) and dt > 0: return -1 if dt == 1: return mincarry+maxLookup[idx] maxi = jobDifficulty[idx] ret = 10**9 for i in range(idx+1, N-dt+2): ret = min(ret, bt(i, dt-1, mincarry+maxi)) maxi = max(jobDifficulty[i], maxi) return ret return bt(0, d, 0)
minimum-difficulty-of-a-job-schedule
[python3] Recursion and Dp solution for reference
vadhri_venkat
0
17
minimum difficulty of a job schedule
1,335
0.587
Hard
20,020
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2710355/python3-Recursion-and-Dp-solution-for-reference
class Solution: def minDifficulty(self, jobDifficulty, d: int) -> int: N = len(jobDifficulty) if len(jobDifficulty) < d: return -1 dp = [[defaultdict(int) for _ in range(N+1)] for _ in range(N+1)] for i in range(N+1): dp[0][i][0] = 0 for i in range(1, N+1): maxi_so_far = 0 for j in range(i,N+1): if i-1: for k, v in dp[i-1][j].items(): dp[i][j][k] = v maxi_so_far = max(jobDifficulty[j-1], maxi_so_far) for k, v in dp[i-1][i-1].items(): if k+1 <=d: dp[i][j][k+1] = min(v+maxi_so_far, dp[i][j][k+1] if dp[i][j][k+1] else 10**9) return (dp[-1][-1][d])
minimum-difficulty-of-a-job-schedule
[python3] Recursion and Dp solution for reference
vadhri_venkat
0
17
minimum difficulty of a job schedule
1,335
0.587
Hard
20,021
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2709117/Python-beats-100-solution-explained-11-lines
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: if len(jobDifficulty) < d: return -1 n = len(jobDifficulty) @lru_cache(None) def dp(cur_difficulty, i, d): if d == 1: return max(jobDifficulty[i:]) if i == n-1: return inf cur_difficulty = max(cur_difficulty, jobDifficulty[i]) change = cur_difficulty + dp(jobDifficulty[i+1], i+1, d-1) dont = dp(cur_difficulty, i+1, d) return min(change, dont) return dp(jobDifficulty[0], 0, d)
minimum-difficulty-of-a-job-schedule
Python beats 100 % solution explained [11 lines]
amuwal
0
25
minimum difficulty of a job schedule
1,335
0.587
Hard
20,022
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2709117/Python-beats-100-solution-explained-11-lines
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: if len(jobDifficulty) < d: return -1 # don't forget n = len(jobDifficulty) @lru_cache(None) def dp(cur_difficulty, i, d): # If there is only 1 day left # We simply return the max of remaining days if d == 1: return max(jobDifficulty[i:]) # If we are here that means d > 1 # So in this case we would have # free days on our hand so return inf if i == n-1: return inf # update cur_difficulty cur_difficulty = max(cur_difficulty, jobDifficulty[i]) # Option 1: We change days --> # If we decided to change days decrement # d(remaining days) and add cur difficulty # to our result change = cur_difficulty + dp(jobDifficulty[i+1], i+1, d-1) # Option 2: We don't change days --> dont = dp(cur_difficulty, i+1, d) # Return min of both options return min(change, dont) return dp(jobDifficulty[0], 0, d)
minimum-difficulty-of-a-job-schedule
Python beats 100 % solution explained [11 lines]
amuwal
0
25
minimum difficulty of a job schedule
1,335
0.587
Hard
20,023
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2709099/Python-Simple-Solution-With-Explanation
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: from functools import cache n = len(jobDifficulty) if d > n: # There will always be days that are empty return -1 @cache # Does memoization with key (ji, di, mx) def helper(ji, di, mx): # Job index, Day index, Current max value if ji == n: # We finished all jobs if di < d - 1: # There are still some days ahead that we did not use return float('inf') return 0 if di == d: # We used all days but did not finish all jobs yet return float('inf') newmx = max(mx, jobDifficulty[ji]) # Check if current job has a greater value than current one # Here we have two ways to go # # 1 - Add job to the same day and check for a new maximum value. If current job has a value # greater than current max value add up the difference and set it as the new max value # # 2 - Add job to the next day, add up it's value and set it as the new max value # since it is the now only the first job in the day # return min( newmx - mx + helper(ji + 1, di, newmx), jobDifficulty[ji] + helper(ji + 1, di + 1, jobDifficulty[ji]) ) return helper(0, -1, 0)
minimum-difficulty-of-a-job-schedule
Python Simple Solution With Explanation
abdotaker608
0
36
minimum difficulty of a job schedule
1,335
0.587
Hard
20,024
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2709089/Python-3-or-Beats-95.99-in-time
class Solution: def minDifficulty(self, arr: List[int], d: int) -> int: @lru_cache(None) def recurse(idx, d, currMax): if idx == len(arr): if d == 0: return currMax else: return math.inf if d == 0: return math.inf val = recurse(idx + 1, d - 1, 0) return min(recurse(idx + 1, d, max(currMax, arr[idx])), val + max(currMax, arr[idx])) res = recurse(0, d, 0) return res if res != math.inf else -1
minimum-difficulty-of-a-job-schedule
Python 3 | Beats 95.99 in time
TheMaroonKnight
0
34
minimum difficulty of a job schedule
1,335
0.587
Hard
20,025
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2708858/Python-Solution-or-Memoization
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: @cache def helper(ind, cut): if cut==d: return max(jobDifficulty[ind:]) curr=-1e9 ans=1e9 for i in range(ind, n-d+cut): curr=max(curr, jobDifficulty[i]) ans=min(ans, curr+helper(i+1, cut+1)) return ans n=len(jobDifficulty) if n<d: return -1 return helper(0, 1)
minimum-difficulty-of-a-job-schedule
Python Solution | Memoization
Siddharth_singh
0
21
minimum difficulty of a job schedule
1,335
0.587
Hard
20,026
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2708853/Python
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: n= len(jobDifficulty) @lru_cache(None) def dfs(idx,k,m): if idx == n : if k == 0: return 0 return math.inf if k <= 0: return math.inf ans = dfs(idx+1,k,max(m,jobDifficulty[idx])) ans = min(ans,max(m,jobDifficulty[idx]) +dfs(idx+1,k-1,0)) return ans a = dfs(0,d,0) if a == math.inf: return -1 return a
minimum-difficulty-of-a-job-schedule
Python
Akhil_krish_na
0
35
minimum difficulty of a job schedule
1,335
0.587
Hard
20,027
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2707950/Python-oror-Easily-Understood-oror-Faster-than-96-oror-explained-with-comments
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: # left_days: the number of days left # i: index of jobDifficulty # prev_max: the max difficulty at the same day @cache def foo1335(left_days: int, i: int, prev_max: int): if i == len(jobDifficulty): if left_days == 0: return prev_max else: return float("inf") # left_days > number of jobDifficulty left if left_days > len(jobDifficulty)-i: return float("inf") # do current job at another day another_day = float("inf") if left_days > 0 and i > 0: another_day = prev_max + foo1335( left_days - 1, i + 1, jobDifficulty[i] ) # do the current job at the same day with the previous ones same_day = foo1335(left_days, i+1, max(jobDifficulty[i], prev_max)) return min(another_day, same_day) # split jobs into d days, but only d-1 operations needed res = foo1335(d-1, 0, 0) return res if res != float("inf") else -1
minimum-difficulty-of-a-job-schedule
🔥 Python || Easily Understood ✅ || Faster than 96% || explained with comments
rajukommula
0
38
minimum difficulty of a job schedule
1,335
0.587
Hard
20,028
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2707821/python3-or-top-down-dp-(faster-than-95)
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: # left_days: the number of days left # i: index of jobDifficulty # prev_max: the max difficulty at the same day @cache def foo1335(left_days: int, i: int, prev_max: int): if i == len(jobDifficulty): if left_days == 0: return prev_max else: return float("inf") # left_days > number of jobDifficulty left if left_days > len(jobDifficulty)-i: return float("inf") # do current job at another day another_day = float("inf") if left_days > 0 and i > 0: another_day = prev_max + foo1335( left_days - 1, i + 1, jobDifficulty[i] ) # do the current job at the same day with the previous ones same_day = foo1335(left_days, i+1, max(jobDifficulty[i], prev_max)) return min(another_day, same_day) # split jobs into d days, but only d-1 operations needed res = foo1335(d-1, 0, 0) return res if res != float("inf") else -1
minimum-difficulty-of-a-job-schedule
python3 | top-down dp (faster than 95%)
henryluo108
0
12
minimum difficulty of a job schedule
1,335
0.587
Hard
20,029
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2650944/Python-Memo-dp-solution
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: memo = {} def dp(day,index): if day==1: return max(jobDifficulty[index:]) elif (day,index) in memo: return memo[(day,index)] m = float('-inf') k = float('inf') for i in range(index,len(jobDifficulty)-day+1): m = max(m,jobDifficulty[i]) k = min(k,m+dp(day-1,i+1)) memo[(day,index)] = k return memo[(day,index)] if len(jobDifficulty)<d: return -1 elif len(jobDifficulty)==d: return sum(jobDifficulty) return dp(d,0)
minimum-difficulty-of-a-job-schedule
Python Memo dp solution
Brillianttyagi
0
34
minimum difficulty of a job schedule
1,335
0.587
Hard
20,030
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2323905/Python3-or-Beats-98-or-O(n*d*max(jobDifficulty))-Solution-or-Memoization
class Solution: def minDifficulty(self, jd: List[int], d: int) -> int: @cache def res(pos = 0, d = d, mx = 0): if d == 0 and pos != len(jd): return math.inf elif d == 0 and pos == len(jd): return 0 elif d == 0 or pos == len(jd): return math.inf else: return min(res(pos+1, d, max(mx, jd[pos])), max(mx, jd[pos]) + res(pos+1, d-1, 0)) ret = res() return -1 if ret == math.inf else ret
minimum-difficulty-of-a-job-schedule
Python3 | Beats 98% | O(n*d*max(jobDifficulty)) Solution | Memoization
DheerajGadwala
0
112
minimum difficulty of a job schedule
1,335
0.587
Hard
20,031
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2148654/Python-easy-to-read-and-understand-or-memoization
class Solution: def solve(self, nums, index, d): if index == len(nums) or d == 1: #print(max(nums[index:])) return max(nums[index:]) ans = float("inf") for i in range(index, len(nums)-d+1): curr = max(nums[index:i+1]) + self.solve(nums, i+1, d-1) ans = min(ans, curr) return ans def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: ans = self.solve(jobDifficulty, 0, d) if ans == float("inf"): return -1 else: return ans
minimum-difficulty-of-a-job-schedule
Python easy to read and understand | memoization
sanial2001
0
173
minimum difficulty of a job schedule
1,335
0.587
Hard
20,032
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2148654/Python-easy-to-read-and-understand-or-memoization
class Solution: def solve(self, nums, index, d): if index == len(nums) or d == 1: #print(max(nums[index:])) return max(nums[index:]) if (index, d) in self.d: return self.d[(index, d)] self.d[(index, d)] = float("inf") for i in range(index, len(nums)-d+1): curr = max(nums[index:i+1]) + self.solve(nums, i+1, d-1) self.d[(index, d)] = min(self.d[(index, d)], curr) return self.d[(index, d)] def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: self.d = {} ans = self.solve(jobDifficulty, 0, d) if ans == float("inf"): return -1 else: return ans
minimum-difficulty-of-a-job-schedule
Python easy to read and understand | memoization
sanial2001
0
173
minimum difficulty of a job schedule
1,335
0.587
Hard
20,033
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/1762005/DP-3-Top-down
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: # dp state : index of the next job, i, and number of days left, j n = len(jobDifficulty) if n<d: return -1 @cache def max_job(i,k): # max(jobDifficulty[i:k]) if i == k-1: return jobDifficulty[i] return max(jobDifficulty[i],max_job(i+1,k)) @cache def sum_job_tail(i): #sum(jobDifficulty[i:]) if i == n-1: return jobDifficulty[-1] return jobDifficulty[i] + sum_job_tail(i+1) @cache def dp(i, j): # n-i jobs left for j days # base case 1: not enough days if n-i < j or j<0: return float("inf") # base case 2: only 1 job at a day if n-i == j: return sum_job_tail(i) # base case 3: only 1 day left if j == 1: return max_job(i,n) # j-1 <= n-k : k <= n-j+1 return min(max_job(i,k) + dp(k, j-1) for k in range(i+1,n-j+2)) return dp(0,d)
minimum-difficulty-of-a-job-schedule
DP 3 Top-down
haydarevren
0
158
minimum difficulty of a job schedule
1,335
0.587
Hard
20,034
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/1756141/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: n = len(jobDifficulty) if n < d: return -1 hardest_job_remaining = [0]*n hardest_job = 0 for i in range(n-1, -1, -1): hardest_job = max(hardest_job, jobDifficulty[i]) hardest_job_remaining[i] = hardest_job @lru_cache(None) def dp(i: int, day: int) -> int: # base case if d == day: return hardest_job_remaining[i] # recurrence relation best = float('inf') hardest = 0 for j in range(i, n-(d-day)): hardest = max(hardest, jobDifficulty[j]) best = min(best, hardest + dp(j+1, day+1)) return best return dp(0, 1)
minimum-difficulty-of-a-job-schedule
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
0
185
minimum difficulty of a job schedule
1,335
0.587
Hard
20,035
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/1756141/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up)
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: n = len(jobDifficulty) # If we cannot schedule at least one job per day, # it is impossible to create a schedule if n < d: return -1 dp = [[float("inf")] * (d + 1) for _ in range(n)] # Set base cases dp[-1][d] = jobDifficulty[-1] # On the last day, we must schedule all remaining jobs, so dp[i][d] # is the maximum difficulty job remaining for i in range(n - 2, -1, -1): dp[i][d] = max(dp[i + 1][d], jobDifficulty[i]) for day in range(d - 1, 0, -1): for i in range(day - 1, n - (d - day)): hardest = 0 # Iterate through the options and choose the best for j in range(i, n - (d - day)): hardest = max(hardest, jobDifficulty[j]) # Recurrence relation dp[i][day] = min(dp[i][day], hardest + dp[j + 1][day + 1]) return dp[0][1]
minimum-difficulty-of-a-job-schedule
✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up)
JawadNoor
0
185
minimum difficulty of a job schedule
1,335
0.587
Hard
20,036
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/1491916/Duplicate-Question-DP-or-Python3
class Solution: def minDifficulty(self, s: List[int], k: int) -> int: n = len(s) dp = {} def helper(i,k): if k<0: return float("inf") if k==0: if i<n: return max(s[i:n]) else: return float("inf") if (i,k) in dp: return dp[((i,k))] a = float("inf") curr_max = 0 for index in range(i,n): curr_max = max(curr_max,s[index]) temp = (curr_max+ helper(index+1, k-1)) a = min(a,temp) dp[((i,k))] = a return dp[((i,k))] ans = helper(0,k-1) return ans if ans<float("inf") else -1
minimum-difficulty-of-a-job-schedule
[Duplicate Question] DP | Python3
Sanjaychandak95
0
178
minimum difficulty of a job schedule
1,335
0.587
Hard
20,037
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/1462608/Python3-or-2-D-dp
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: jobs=len(jobDifficulty) dp=[[float('inf') for i in range(jobs)] for j in range(d)] dp[0][0]=jobDifficulty[0] for i in range(1,jobs): dp[0][i]=max(jobDifficulty[i],dp[0][i-1]) for day in range(1,d): for job in range(jobs): if job+1<day+1: dp[day][job]=-1 else: curr_max=jobDifficulty[job] for k in range(job,day-1,-1): curr_max=max(curr_max,jobDifficulty[k]) dp[day][job]=min(dp[day][job],dp[day-1][k-1]+curr_max) return dp[d-1][jobs-1]
minimum-difficulty-of-a-job-schedule
[Python3] | 2-D dp
swapnilsingh421
0
165
minimum difficulty of a job schedule
1,335
0.587
Hard
20,038
https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/1063122/Python-DP-O(n-*-n-*-d)
class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: n = len(jobDifficulty) if d > n: return -1 # Memoize maximum for every cut max_dp = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): for j in range(i, n): if i == j: max_dp[i][j] = jobDifficulty[i] else: max_dp[i][j] = max(max_dp[i][j - 1], jobDifficulty[j]) # Calculate minimum difficulty dp = [[0 for _ in range(n)] for _ in range(d)] for i in range(d): for j in range(i, min(n, n - d + i + 1)): if i == 0: dp[i][j] = max_dp[i][j] else: dp[i][j] = min( dp[i - 1][k - 1] + max_dp[k][j] for k in range(i, j + 1) ) return dp[d - 1][n - 1]
minimum-difficulty-of-a-job-schedule
Python DP O(n * n * d)
michaellin986
0
493
minimum difficulty of a job schedule
1,335
0.587
Hard
20,039
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1201679/C%2B%2B-Python3-No-Heap-No-BS-Simple-Sort-99.20
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: m = len(mat) rows = sorted(range(m), key=lambda i: (mat[i], i)) del rows[k:] return rows
the-k-weakest-rows-in-a-matrix
[C++, Python3] No Heap, No BS, Simple Sort 99.20%
mycoding1729
163
6,300
the k weakest rows in a matrix
1,337
0.728
Easy
20,040
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/496647/Python-3-(one-line)-(beats-100)
class Solution: def kWeakestRows(self, G: List[List[int]], k: int) -> List[int]: S = [[sum(g),i] for i,g in enumerate(G)] R = sorted(S) return [r[1] for r in R[:k]]
the-k-weakest-rows-in-a-matrix
Python 3 (one line) (beats 100%)
junaidmansuri
28
3,500
the k weakest rows in a matrix
1,337
0.728
Easy
20,041
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/496647/Python-3-(one-line)-(beats-100)
class Solution: def kWeakestRows(self, G: List[List[int]], k: int) -> List[int]: return [r[1] for r in heapq.nsmallest(k,[[sum(g),i] for i,g in enumerate(G)])] - Junaid Mansuri - Chicago, IL
the-k-weakest-rows-in-a-matrix
Python 3 (one line) (beats 100%)
junaidmansuri
28
3,500
the k weakest rows in a matrix
1,337
0.728
Easy
20,042
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1326292/Solution-3-line-with-python
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: matIndexAndSumRow = [[sum(val),idx] for idx,val in enumerate(mat)] matIndexAndSumRow.sort() return [matIndexAndSumRow[i][-1] for i in range(k)]
the-k-weakest-rows-in-a-matrix
Solution 3 line with python
qanghaa
9
311
the k weakest rows in a matrix
1,337
0.728
Easy
20,043
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1066759/Python.-Super-simple-and-Easy-understanding-solution.
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: helper = {} for index, row in enumerate(mat): helper[index] = 0 for num in row: if num: helper[index] += 1 else: break ans = sorted(helper, key = helper.get) return ans[:k]
the-k-weakest-rows-in-a-matrix
Python. Super simple & Easy-understanding solution.
m-d-f
8
599
the k weakest rows in a matrix
1,337
0.728
Easy
20,044
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2384316/Python-Accurate-Solution-using-Tuples-oror-Documented
class Solution:class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: sums = [] # list to store Tuples for i, row in enumerate(mat): sums.append((sum(row), i)) # append sum &amp; index of row as a Tuple sums.sort() # sort the tuples using first key i.e. sum return [y for x,y in sums[:k]] # Extract k tuples, return 2nd value of tuple i.e. index
the-k-weakest-rows-in-a-matrix
[Python] Accurate Solution using Tuples || Documented
Buntynara
6
94
the k weakest rows in a matrix
1,337
0.728
Easy
20,045
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2197823/Python3-solution-without-binary-search-and-heap
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: NoOfOnesInARow = {} for row in range(len(mat)): count = mat[row].count(1) if count in NoOfOnesInARow: NoOfOnesInARow[count].append(row) else: NoOfOnesInARow[count] = [row] counter = 0 result = [] while k>0: if counter in NoOfOnesInARow: x = NoOfOnesInARow.get(counter) x.sort() while k>0 and len(x): result.append(x.pop(0)) k-=1 counter+=1 return result
the-k-weakest-rows-in-a-matrix
📌 Python3 solution without binary search and heap
Dark_wolf_jss
6
105
the k weakest rows in a matrix
1,337
0.728
Easy
20,046
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1066761/Python.-One-liner-easy-solution.-faster-than-97.05
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: return sorted(range(len(mat)), key = lambda row: sum(mat[row]))[:k]
the-k-weakest-rows-in-a-matrix
Python. One-liner easy solution. faster than 97.05%
m-d-f
4
197
the k weakest rows in a matrix
1,337
0.728
Easy
20,047
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/496633/Python3-sorting
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: strength = ((sum(mat[i]), i) for i in range(len(mat))) return [x for _, x in sorted(strength)[:k]]
the-k-weakest-rows-in-a-matrix
[Python3] sorting
ye15
3
293
the k weakest rows in a matrix
1,337
0.728
Easy
20,048
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/496633/Python3-sorting
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: m, n = len(mat), len(mat[0]) vals = [] for i in range(m): lo, hi = 0, n while lo < hi: mid = lo + hi >> 1 if mat[i][mid]: lo = mid + 1 else: hi = mid vals.append((lo, i)) return [i for _, i in sorted(vals)[:k]]
the-k-weakest-rows-in-a-matrix
[Python3] sorting
ye15
3
293
the k weakest rows in a matrix
1,337
0.728
Easy
20,049
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2583290/SIMPLE-PYTHON3-SOLUTION-easy-to-understand
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: indexlist = [i for i in range(len(mat))] valuelist = [] ans = [] for i in mat: valuelist.append(i.count(1)) for j in range(k): m = valuelist.index(min(valuelist)) ans.append(m) valuelist[m] = 1999 return ans
the-k-weakest-rows-in-a-matrix
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ easy to understand
rajukommula
2
162
the k weakest rows in a matrix
1,337
0.728
Easy
20,050
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2550398/python3-oror-O(N)-oror-optimized-solution
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: def comp(val): return val[0] tmp = [] for x in mat: tmp.append(x.count(1)) for i in range(len(tmp)): tmp[i] = (tmp[i],i) tmp.sort(key = comp) res = [] for x,y in tmp: res.append(y) return res[:k]
the-k-weakest-rows-in-a-matrix
python3 || O(N) || optimized solution
shacid
2
69
the k weakest rows in a matrix
1,337
0.728
Easy
20,051
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2327425/Python3-or-solution
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: rowDict = {} for i in range(len(mat)): rowDict[i] = sum(mat[i]) weakestList = list(sorted(rowDict, key=rowDict.get)) return weakestList[:k]
the-k-weakest-rows-in-a-matrix
Python3 | solution
arvindchoudhary33
2
73
the k weakest rows in a matrix
1,337
0.728
Easy
20,052
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1888414/Python-One-Liner
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: return [i[0] for i in sorted(enumerate(mat), key = lambda x: x[1].count(1))[:k]]
the-k-weakest-rows-in-a-matrix
✅ Python One Liner
dhananjay79
2
60
the k weakest rows in a matrix
1,337
0.728
Easy
20,053
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1888414/Python-One-Liner
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: arr = [] for i in range(len(mat)): arr.append([mat[i].count(1), i]) return [i[1] for i in sorted(arr)[:k]]
the-k-weakest-rows-in-a-matrix
✅ Python One Liner
dhananjay79
2
60
the k weakest rows in a matrix
1,337
0.728
Easy
20,054
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1888414/Python-One-Liner
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: def countOne(row): lo, hi = 0, len(row) - 1 while lo <= hi: mid = (lo + hi) // 2 if row[mid]: lo = mid + 1 else: hi = mid - 1 return hi + 1 arr = [] for i in range(len(mat)): arr.append([countOne(mat[i]), i]) return [i[1] for i in sorted(arr)[:k]]
the-k-weakest-rows-in-a-matrix
✅ Python One Liner
dhananjay79
2
60
the k weakest rows in a matrix
1,337
0.728
Easy
20,055
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1888414/Python-One-Liner
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: def countOne(row): lo, hi = 0, len(row) - 1 while lo <= hi: mid = (lo + hi) // 2 if row[mid]: lo = mid + 1 else: hi = mid - 1 return hi + 1 dic, ans, c = defaultdict(list), [], 0 for i in range(len(mat)): dic[countOne(mat[i])].append(i) while k: for i in dic[c]: if k: ans.append(i) k -= 1 c += 1 return ans
the-k-weakest-rows-in-a-matrix
✅ Python One Liner
dhananjay79
2
60
the k weakest rows in a matrix
1,337
0.728
Easy
20,056
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1887878/Naive-Solution-Python3-oror-First-Daily-Challenge-Solved-oror-Without-Help-from-Discuss(999%2B)
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: ans=defaultdict() #dictionary to store count of 1s in each row c=0 for i,r in enumerate(mat): #keeps track of position i of row r c=r.count(1) #count 1s ans[i]=c #add to dictionary (i,c) as the (key,value) pair return sorted(ans, key=ans.get)[:k] #sort the dictionary from least to most value(c) of a row. And return the first k keys(i).
the-k-weakest-rows-in-a-matrix
Naïve Solution [Python3] || First Daily Challenge Solved || Without Help from Discuss(999+)
Sh4d0w-2099
2
32
the k weakest rows in a matrix
1,337
0.728
Easy
20,057
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1657613/PythonSimplest-Solution-Only-Need-Heap-Lexicographical-Ordering
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: new_array = [(mat[i],i) for i in range(len(mat))] heapq.heapify(new_array) return([heapq.heappop(new_array)[1] for _ in range(len(new_array))][:k])
the-k-weakest-rows-in-a-matrix
[Python][Simplest Solution] Only Need Heap - Lexicographical Ordering
ifanwang1028
2
113
the k weakest rows in a matrix
1,337
0.728
Easy
20,058
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2573955/Python3-Heap
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: pairs = [(sum(r),i) for i,r in enumerate(mat)] return [n[1] for n in heapq.nsmallest(k, pairs)]
the-k-weakest-rows-in-a-matrix
[Python3] Heap
ruosengao
1
43
the k weakest rows in a matrix
1,337
0.728
Easy
20,059
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2356501/python-3-liner
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: mat_with_indices = [(idx, elem) for (idx, elem) in enumerate(mat)] sorted_by_strength = sorted(mat_with_indices, key=lambda row: row[1].count(1)) return [elem[0] for elem in sorted_by_strength[:k]]
the-k-weakest-rows-in-a-matrix
python 3-liner
Potentis
1
56
the k weakest rows in a matrix
1,337
0.728
Easy
20,060
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2295733/Python-or-Faster-than-96.83-other-python-solution
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: res = [] # calculate the soldiers of each row, mark the row index and total for i in range(len(mat)): res.append((i, sum(mat[i]))) # resort the mark list by soldiers total value res.sort(key= lambda item: item[1]) # return the sub array of the `k` weakest return list(map(lambda item:item[0], res[:k]))
the-k-weakest-rows-in-a-matrix
Python | Faster than 96.83% other python solution
iamdhj
1
56
the k weakest rows in a matrix
1,337
0.728
Easy
20,061
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2169661/Python-Two-Simple-Solutions
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: #Approach 1 temp=[] for i,m in enumerate(mat): sol=(sum(m),i) #since it has only 1 and 0, the total sum will be total 1s. temp.append(sol) temp.sort() idx=[] for i in range(k): idx.append(temp[i][1]) return idx
the-k-weakest-rows-in-a-matrix
Python Two Simple Solutions
pruthashouche
1
191
the k weakest rows in a matrix
1,337
0.728
Easy
20,062
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2169661/Python-Two-Simple-Solutions
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: #Approach-2 row=len(mat) col=len(mat[0]) arr=[] for i, r in enumerate(mat): c=0 for j in range(col): if r[j]==0: break c=c+1 arr.append((c,i)) arr.sort() index=[] for i in range(k): index.append(arr[i][1]) return index
the-k-weakest-rows-in-a-matrix
Python Two Simple Solutions
pruthashouche
1
191
the k weakest rows in a matrix
1,337
0.728
Easy
20,063
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1963447/Python-Sort-and-Heap-Clean-and-Simple!
class Solution: def kWeakestRows(self, mat, k): soldiers = [(row.count(1), i) for i,row in enumerate(mat)] return [i for row,i in sorted(soldiers)][:k]
the-k-weakest-rows-in-a-matrix
Python - Sort and Heap - Clean and Simple!
domthedeveloper
1
151
the k weakest rows in a matrix
1,337
0.728
Easy
20,064
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1963447/Python-Sort-and-Heap-Clean-and-Simple!
class Solution: def kWeakestRows(self, mat, k): soldiers = [sum(row) for row in mat] return nsmallest(k, range(len(mat)), key=lambda i : soldiers[i])
the-k-weakest-rows-in-a-matrix
Python - Sort and Heap - Clean and Simple!
domthedeveloper
1
151
the k weakest rows in a matrix
1,337
0.728
Easy
20,065
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1963447/Python-Sort-and-Heap-Clean-and-Simple!
class Solution: def kWeakestRows(self, mat, k): return nsmallest(k, range(len(mat)), key=lambda i : sum(mat[i]))
the-k-weakest-rows-in-a-matrix
Python - Sort and Heap - Clean and Simple!
domthedeveloper
1
151
the k weakest rows in a matrix
1,337
0.728
Easy
20,066
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1941046/Python3-Easy-heap-solution-or-O(n-log-n)
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: heap = [] heapq.heapify(heap) for row in range(len(mat)): soldiers = mat[row].count(1) heapq.heappush(heap, (soldiers, row)) result = [] for i in range(k): result.append(heapq.heappop(heap)[1]) return result
the-k-weakest-rows-in-a-matrix
Python3 Easy heap solution | O(n log n)
YifanYang0527
1
77
the k weakest rows in a matrix
1,337
0.728
Easy
20,067
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1929168/Python-Solution-or-One-Liner-or-Sorting-Based-or-List-Comprehensions
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: return [x for _,x in sorted(zip([x.count(1) for x in mat],range(len(mat))))][:k]
the-k-weakest-rows-in-a-matrix
Python Solution | One Liner | Sorting Based | List Comprehensions
Gautam_ProMax
1
78
the k weakest rows in a matrix
1,337
0.728
Easy
20,068
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1888210/Python3-Solution-with-heap
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: heap = [] for i in range(len(mat)): cnt = 0 for j in range(len(mat[i])): cnt += mat[i][j] heapq.heappush(heap, (cnt, i)) res = [] while k: res.append(heapq.heappop(heap)[1]) k -= 1 return res
the-k-weakest-rows-in-a-matrix
[Python3] Solution with heap
maosipov11
1
26
the k weakest rows in a matrix
1,337
0.728
Easy
20,069
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1888099/Python-Shortest-Easiest-Solution-using-heap
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: minheap, ans = [], [] for i in range(len(mat)): heappush(minheap,(mat[i].count(1),i)) while k: ans.append( heappop(minheap)[1]) k-=1 return ans
the-k-weakest-rows-in-a-matrix
[Python] Shortest Easiest Solution using heap
RaghavGupta22
1
68
the k weakest rows in a matrix
1,337
0.728
Easy
20,070
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1865437/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: dict = {} for i,n in enumerate(mat): dict[i] = sum(n) abc = sorted(dict, key = dict.get) return abc[:k]
the-k-weakest-rows-in-a-matrix
Python (Simple Approach and Beginner-Friendly)
vishvavariya
1
67
the k weakest rows in a matrix
1,337
0.728
Easy
20,071
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1112694/Python3-Simple-solution-100-ms-runtime
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: count_mat = {} j = 0 for i in mat: ones = i.count(1) count_mat[j] = ones j = j + 1 count_mat = sorted(count_mat, key=lambda k: count_mat[k]) return count_mat[:k]
the-k-weakest-rows-in-a-matrix
Python3, Simple solution, 100 ms runtime
naiem_ece
1
59
the k weakest rows in a matrix
1,337
0.728
Easy
20,072
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1066599/Simple-python-solution-with-Binary-Search
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: t=[] def binarySearch(target,l,h,nums): while l<=h: mid=(l+h)//2 if nums[mid]>target: l=mid+1 else: h=mid-1 return l for i in range(len(mat)): low=binarySearch(0.5,0,len(mat[i])-1,mat[i]) high=binarySearch(1.5,0,len(mat[i])-1,mat[i]) t.append([i,low-high]) #as given array is a sorted ,low-high will give us the count of ones return [i[0] for i in sorted(t,key=lambda x:x[1])[:k]]
the-k-weakest-rows-in-a-matrix
Simple python solution with Binary Search
Umadevi_R
1
87
the k weakest rows in a matrix
1,337
0.728
Easy
20,073
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2832857/Simple-Python-Solution
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: answer = [] soldiers_and_index = [] for idx, soldiers in enumerate(mat): soldiers_and_index.append([sum(soldiers), idx]) soldiers_and_index.sort() for idx in range(k): answer.append(soldiers_and_index[idx][1]) return answer
the-k-weakest-rows-in-a-matrix
Simple Python Solution
corylynn
0
3
the k weakest rows in a matrix
1,337
0.728
Easy
20,074
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2818286/With-using-dictionary
class Solution: def kWeakestRows(self, matrix: List[List[int]], k: int) -> List[int]: dictionary = {} dict_sorted = {} for i in range(len(matrix)): dictionary[i] = matrix[i].count(1) for i in sorted(dictionary.values()): for key in dictionary.keys(): if dictionary[key] == i: dict_sorted[key] = dictionary[key] result = list(dict_sorted.keys()) for i in range(len(result) - k): result.pop() return result
the-k-weakest-rows-in-a-matrix
With using dictionary
pkozhem
0
4
the k weakest rows in a matrix
1,337
0.728
Easy
20,075
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2789663/Easy-Python-Solution
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: d = {}; n = len(mat); arr = [] for i in range(n): x = mat[i].count(1); d[i] = x; arr.append(i); arr.sort(key = lambda i: d[i]); return arr[:k]
the-k-weakest-rows-in-a-matrix
Easy Python Solution
avinashdoddi2001
0
9
the k weakest rows in a matrix
1,337
0.728
Easy
20,076
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2776556/Binary-search-to-find-the-first-0-or-last-1
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: res = [] for i in range(len(mat)): row = mat[i] left = 0 right = len(row) - 1 # find the index of first 0: while left < right: mid = left + (right - left) // 2 if row[mid] == 1: left = mid + 1 else: right = mid res.append((i, left + row[left])) # add 1 if all 1 print(res) res.sort(key = lambda x: (x[1], x[0])) return [x[0] for x in res[:k]]
the-k-weakest-rows-in-a-matrix
Binary search to find the first 0 or last 1
michaelniki
0
3
the k weakest rows in a matrix
1,337
0.728
Easy
20,077
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2776556/Binary-search-to-find-the-first-0-or-last-1
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: res = [] for i in range(len(mat)): row = mat[i] left = 0 right = len(row) - 1 # find the index of last 1: while left < right: mid = left + (right - left + 1) // 2 if row[mid] == 1: left = mid else: right = mid - 1 res.append((i, left + row[left])) # add 1 in case all 0. print(res) res.sort(key = lambda x: (x[1], x[0])) return [x[0] for x in res[:k]]
the-k-weakest-rows-in-a-matrix
Binary search to find the first 0 or last 1
michaelniki
0
3
the k weakest rows in a matrix
1,337
0.728
Easy
20,078
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2703617/My-solution-Python3
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: row = [] for i in range(len(mat)): n_s = mat[i].count(1) row.append((n_s, i)) row.sort() lst2 = [] for key, value in row[:k]: lst2.append(value) return lst2
the-k-weakest-rows-in-a-matrix
My solution, Python3
hafid-hub
0
7
the k weakest rows in a matrix
1,337
0.728
Easy
20,079
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2676008/Easy-Python-Solution-or-Hash-Maps-or-Sorting
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: hashmap = {} index = 0 for i in mat: hashmap[index] = i.count(1) index += 1 sorted_map = [k for k, v in sorted(hashmap.items(), key=lambda a:a[1], reverse=False)] return sorted_map[:k]
the-k-weakest-rows-in-a-matrix
Easy Python Solution | Hash Maps | Sorting
atharva77
0
4
the k weakest rows in a matrix
1,337
0.728
Easy
20,080
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2650754/Python-Hash-Table-no-Sorting-beats-90.58
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: shape = (len(mat), len(mat[0])) # (rows, cols) # A dictionary to collect indices of rows with the calculated ones amount # The following structure: { ones_amount : array[row_index_1, ...] } count = { i : [-1] for i in range(0, shape[1] + 1) } for i in range(0, shape[0]): ones = 0 for j in range(0, shape[1]): if (mat[i][j] == 0): break ones += 1 if (count[ones][0] != -1): count[ones].append(i) else: count[ones][0] = i weakest = [] w_len = 0 for i in range(0, shape[1] + 1): if (count[i][0] != -1): for j in count[i]: weakest.append(j) w_len += 1 if (w_len == k): return weakest
the-k-weakest-rows-in-a-matrix
Python Hash Table, no Sorting, beats 90.58 %
Andrii_Ihnatiuk
0
3
the k weakest rows in a matrix
1,337
0.728
Easy
20,081
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2556722/python-heap-solution
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: mat=[[sum(val),i] for i,val in enumerate(mat)] ans=[] heapq.heapify(mat) for i in range(k): x=heappop(mat) ans.append(x[1]) return ans
the-k-weakest-rows-in-a-matrix
python heap solution
pranjalmishra334
0
48
the k weakest rows in a matrix
1,337
0.728
Easy
20,082
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2540340/Python3-One-Liner
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: return list(dict(sorted({i: sum(mat[i]) for i in range(len(mat))}.items(), key=(lambda x: x[1]))))[:k]
the-k-weakest-rows-in-a-matrix
[Python3] One-Liner
ivnvalex
0
67
the k weakest rows in a matrix
1,337
0.728
Easy
20,083
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2537784/python-solution-95.28-faster-using-dictionary!-O(n)
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: dict_num_soldiers = {} count_soldiers = 0 for i in range(len(mat)): for j in range(len(mat[i])): if mat[i][j] == 1: count_soldiers += 1 dict_num_soldiers[i] = count_soldiers count_soldiers = 0 sorted_dict = {key: val for key, val in sorted(dict_num_soldiers.items(), key=lambda item: item[1])} list_k_weakest = [] for key, val in sorted_dict.items(): if len(list_k_weakest) != k: list_k_weakest.append(key) return list_k_weakest
the-k-weakest-rows-in-a-matrix
python solution 95.28% faster using dictionary! O(n)
samanehghafouri
0
99
the k weakest rows in a matrix
1,337
0.728
Easy
20,084
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2514353/Python3-oror-One-Liner-oror-97-speed-90-memory
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: return [a for _,a in sorted([(sum(mat[row]),row) for row in range(len(mat))], key = lambda x: (x[0],x[1]))[:k]]
the-k-weakest-rows-in-a-matrix
Python3 || One-Liner || 97% speed 90% memory
TimGrimbergen
0
48
the k weakest rows in a matrix
1,337
0.728
Easy
20,085
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2450116/C%2B%2BPython-or-O(nlogn)-or-Optimized-Solution
class Solution: def binarysearch(self,arr): l,r = 0,len(arr) while(l<=r and l<len(arr) and r>=0): m = (l+r)//2 if m == len(arr)-1: if arr[m] == 1: return len(arr) else: r = m-1 elif arr[m] == 0: r = m-1 elif arr[m] == 1: if arr[m+1] == 0: return m+1 else: l = m+1 return 0 def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: d = {} for i in range(len(mat)): count = self.binarysearch(mat[i]) if count in d: d[count].append([mat[i],i]) else: d[count] = [[mat[i],i]] output = [] for i in sorted(d.keys()): for j in range(len(d[i])): output.append(d[i][j][1]) if len(output)==k: break if len(output)==k: break return output
the-k-weakest-rows-in-a-matrix
C++/Python | O(nlogn) | Optimized Solution
arpit3043
0
80
the k weakest rows in a matrix
1,337
0.728
Easy
20,086
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2437677/easy-python-code-or-O(n-log-n)-or-heap-sort-or-binary-search
class Solution: def binarysearch(self,arr): l,r = 0,len(arr) while(l<=r and l<len(arr) and r>=0): m = (l+r)//2 if m == len(arr)-1: if arr[m] == 1: return len(arr) else: r = m-1 elif arr[m] == 0: r = m-1 elif arr[m] == 1: if arr[m+1] == 0: return m+1 else: l = m+1 return 0 def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: d = {} for i in range(len(mat)): count = self.binarysearch(mat[i]) if count in d: d[count].append([mat[i],i]) else: d[count] = [[mat[i],i]] output = [] for i in sorted(d.keys()): for j in range(len(d[i])): output.append(d[i][j][1]) if len(output)==k: break if len(output)==k: break return output
the-k-weakest-rows-in-a-matrix
easy python code | O(n log n) | heap sort | binary search
dakash682
0
61
the k weakest rows in a matrix
1,337
0.728
Easy
20,087
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2390249/Python-simple-solutions-or-sort-or-heap
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: row = [] for i in range(len(mat)): row.append((sum(mat[i]), i)) row.sort() ans = [idx for (val, idx) in row[:k]] return ans
the-k-weakest-rows-in-a-matrix
Python simple solutions | sort | heap
wilspi
0
73
the k weakest rows in a matrix
1,337
0.728
Easy
20,088
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/2390249/Python-simple-solutions-or-sort-or-heap
class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: row = [] for i in range(len(mat)): row.append((sum(mat[i]), i)) heapq.heapify(row) ans = [] while k>0: (val, idx) = heapq.heappop(row) ans.append(idx) k -= 1 return ans
the-k-weakest-rows-in-a-matrix
Python simple solutions | sort | heap
wilspi
0
73
the k weakest rows in a matrix
1,337
0.728
Easy
20,089
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/2443490/Easy-to-understand-or-C%2B%2B-or-PYTHON-or
class Solution: def minSetSize(self, arr: List[int]) -> int: freq = Counter(arr); f = []; for val in freq.values(): f.append(val); f.sort(reverse=True) ans = 0; n = 0; while(len(arr)//2>n): n += f[ans]; ans += 1; return ans;
reduce-array-size-to-the-half
Easy to understand | C++ | PYTHON |
dharmeshkporiya
3
43
reduce array size to the half
1,338
0.697
Medium
20,090
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/2441786/Python-100-runtime-Simple-and-Fast-please-upvote-%3A)
class Solution(object): def minSetSize(self, arr): d = {} for x in arr: if x not in d: d[x] = 1 else: d[x] += 1 l = sorted(d.values()) N = len(arr) // 2 idx = 0 while N > 0: N -= l[-idx-1] idx += 1 return idx
reduce-array-size-to-the-half
[Python] 100% runtime, Simple & Fast; please upvote :)
SteveShin_
2
233
reduce array size to the half
1,338
0.697
Medium
20,091
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/496667/Python-3-(two-lines)-(beats-100)
class Solution: def minSetSize(self, A: List[int]) -> int: L, C = len(A), collections.Counter(A) S = sorted(C.values(), reverse = True) T = itertools.accumulate(S) for i,v in enumerate(T): if v >= len(A)//2: return i + 1
reduce-array-size-to-the-half
Python 3 (two lines) (beats 100%)
junaidmansuri
2
616
reduce array size to the half
1,338
0.697
Medium
20,092
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/496667/Python-3-(two-lines)-(beats-100)
class Solution: def minSetSize(self, A: List[int]) -> int: for i,v in enumerate(itertools.accumulate(sorted(collections.Counter(A).values(), reverse = True))): if v >= len(A)//2: return i + 1 - Junaid Mansuri - Chicago, IL
reduce-array-size-to-the-half
Python 3 (two lines) (beats 100%)
junaidmansuri
2
616
reduce array size to the half
1,338
0.697
Medium
20,093
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/2443552/Removing-most-common-99-speed
class Solution: def minSetSize(self, arr: List[int]) -> int: n_removed = count = 0 half_len_arr = ceil(len(arr) / 2) for _, n in Counter(arr).most_common(): n_removed += 1 count += n if count >= half_len_arr: return n_removed
reduce-array-size-to-the-half
Removing most common, 99% speed
EvgenySH
1
37
reduce array size to the half
1,338
0.697
Medium
20,094
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/2441633/Python3-Counter-%2B-PQ
class Solution: def minSetSize(self, arr: List[int]) -> int: counts = Counter(arr) pq = [] for num in counts.keys(): heapq.heappush(pq, -1 * counts[num]) length = len(arr) cutoff = length//2 res = 0 while length > cutoff: length += heapq.heappop(pq) res += 1 return res
reduce-array-size-to-the-half
Python3 Counter + PQ
answer610
1
72
reduce array size to the half
1,338
0.697
Medium
20,095
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/1371858/Easy-and-Simple-Python-Solution
class Solution: def minSetSize(self, arr): arr_len=(len(arr)-1)//2 dic={} for i in arr: if i not in dic: dic[i]=1 else: dic[i]+=1 sum=0 count=0 for key,val in sorted(dic.items(),key = lambda x: x[1], reverse = True): if sum >arr_len: return count else: sum+=val count+=1 return count
reduce-array-size-to-the-half
Easy and Simple Python Solution
sangam92
1
151
reduce array size to the half
1,338
0.697
Medium
20,096
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/1038032/Python-3-2-LINE-Commented-Solution.
class Solution: def minSetSize(self, arr: List[int]) -> int: #Sort the array in increasing order based on FREQUENCY. result = [item for items, c in Counter(arr).most_common() for item in [items] * c][::-1] # Instead of removing elements, we can simply iterate through the second half of the "result" list # and obtain it's set. This will give us the distinct elements and we can then return len(set). return len(set(result[int(len(arr)/2):]))
reduce-array-size-to-the-half
[Python 3] - 2 LINE Commented Solution.
mb557x
1
155
reduce array size to the half
1,338
0.697
Medium
20,097
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/2597246/python3-using-counters
class Solution: def minSetSize(self, arr: List[int]) -> int: counts = Counter(arr) counts_sorted = sorted(counts.items(), key=lambda items:items[1], reverse=True) s=0 for i in range(len(counts_sorted)): s+=counts_sorted[i][1] if s>=(len(arr)/2): return i+1
reduce-array-size-to-the-half
[python3] using counters
hhlinwork
0
17
reduce array size to the half
1,338
0.697
Medium
20,098
https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/2588629/Python-Solution-faster-than-97.33-of-Python3
class Solution: def minSetSize(self, arr: List[int]) -> int: d = Counter(arr) val = sorted(d.values())[::-1] out = len(arr)//2 i = 0 res=0 for i in val: out -= i res +=1 if out <= 0: break return res
reduce-array-size-to-the-half
Python Solution faster than 97.33% of Python3
anshsharma17
0
29
reduce array size to the half
1,338
0.697
Medium
20,099