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/is-graph-bipartite/discuss/2269192/Clear-simple-Python-solution-using-DFS-traversal
class Solution: isBipartite = True; colors = [] visited = [] def __init(self): self.isBipartite = isBipartite; self.colors = colors self.visited = visited def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) self.isBipartite = True self.colors = [False] * n self.visited = [False] * n for v in range(n): if (self.visited[v] == False): self.traverse(graph, v); return self.isBipartite; def traverse(self, graph, v): self.visited[v] = True; for w in graph[v]: if (self.visited[w] == False): self.colors[w] = not self.colors[v] self.traverse(graph, w) else: if (self.colors[w] == self.colors[v]): self.isBipartite = False; return;
is-graph-bipartite
Clear simple Python solution using DFS traversal
leqinancy
0
9
is graph bipartite
785
0.527
Medium
12,800
https://leetcode.com/problems/is-graph-bipartite/discuss/1992330/Python3-Solution-with-using-dfs
class Solution: def dfs(self, graph, color, source): for neigb in graph[source]: if neigb in color: if color[neigb] == color[source]: return False else: color[neigb] = 1 - color[source] if not self.dfs(graph, color, neigb): return False return True def isBipartite(self, graph: List[List[int]]) -> bool: color = {} # 0 - red/1 - black for i in range(len(graph)): if i not in color: color[i] = 0 if not self.dfs(graph, color, i): return False return True
is-graph-bipartite
[Python3] Solution with using dfs
maosipov11
0
8
is graph bipartite
785
0.527
Medium
12,801
https://leetcode.com/problems/is-graph-bipartite/discuss/1992000/Python-3-Solution-or-BFS-or-Clean-Code
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: # -1 = no colour | 0 = first colour | 1 = second colour colours = [-1] * len(graph) q = deque() def checkBipartite(): # BFS while q: node, currColour = q.popleft() # assign the next colour nextColour = 1 if currColour == 0 else 0 for nei in graph[node]: # if the adjacent node has the same colour then it can't be a bipartite if colours[nei] == currColour: return False # if the adjacent isn't coloured apply the next colour to the adjacent nodes and append to the queue if colours[nei] == -1: colours[nei] = nextColour q.append((nei, nextColour)) return True # traverse every node for i in range(len(graph)): if colours[i] == -1: colours[i] = 0 q.append((i, 0)) if not checkBipartite(): return False return True
is-graph-bipartite
Python 3 Solution | BFS | Clean Code
Raja03
0
11
is graph bipartite
785
0.527
Medium
12,802
https://leetcode.com/problems/is-graph-bipartite/discuss/1991032/Python-3-DFS
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: visited = [9 for i in range(len(graph))] res = [True] def dfs(node,color): if visited[node]==9: visited[node] = color for i in graph[node]: if visited[i]==9: dfs(i, not color) else: if visited[i] == (color): res[0] = False return for j in range(len(graph)): if visited[j]==9: dfs(j,True) return res[0]
is-graph-bipartite
Python 3 DFS
Brillianttyagi
0
23
is graph bipartite
785
0.527
Medium
12,803
https://leetcode.com/problems/is-graph-bipartite/discuss/1990705/Python-3-BFS-Solution
class Solution: def isBipartite(self, graph: list[list[int]]) -> bool: vis = [False for n in range(0, len(graph))] while sum(vis) != len(graph): # Since graph isn't required to be connected this process needs to be repeated ind = vis.index(False) # Find the first entry in the visited list that is false vis[ind] = True grp = {ind:True} # initialize first node as part of group 1 q = [ind] # Add current index to queue while q: # Go to each node in the graph u = q.pop(0) for v in graph[u]: # Go to each vertice connected to the current node if vis[v] == True: # If visited check that it is in the opposite group of the current node if grp[u] == grp[v]: return False # If a single edge does not lead to a group change return false else: # If not visited put v in opposite group of u, set to visited, and append to q vis[v] = True grp[v] = not grp[u] q.append(v) return True
is-graph-bipartite
[Python 3] BFS Solution
arsrbt
0
8
is graph bipartite
785
0.527
Medium
12,804
https://leetcode.com/problems/is-graph-bipartite/discuss/1990552/Python-Dictionary-Solution
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: dict_graph = collections.defaultdict(list) for i, v in enumerate(graph) : if v : dict_graph[i] = v dict_tmp = dict_graph while dict_tmp : groupA = set() groupB = set() dict_graph = dict_tmp dict_tmp = collections.defaultdict(list) for k in dict_graph : if k not in groupA and k not in groupB : anyA = any(map(lambda x: x in groupA, dict_graph[k])) anyB = any(map(lambda x: x in groupB, dict_graph[k])) if anyA and anyB : return 0 elif anyA : groupB.add(k) groupA.update(dict_graph[k]) elif anyB : groupA.add(k) groupB.update(dict_graph[k]) else : if not groupA and not groupB : groupA.add(k) groupB.update(dict_graph[k]) else : dict_tmp[k] = dict_graph[k] if k in groupA : for v in dict_graph[k] : if v in groupA : return 0 groupB.add(v) if k in groupB : for v in dict_graph[k] : if v in groupB : return 0 groupA.add(v) return 1
is-graph-bipartite
[ Python ] Dictionary Solution
crazypuppy
0
34
is graph bipartite
785
0.527
Medium
12,805
https://leetcode.com/problems/is-graph-bipartite/discuss/1875232/Python3-DFS-solution
class Solution: ok = True colors = [] visited = [] def __init(self): self.ok = ok self.colors = colors self.visited = visited def isBipartite(self, graph: List[List[int]]) -> bool: n = len(graph) # bool array storing color(true/false) for each node self.colors = [False]*n # bool array storing whether the node is visited or not self.visited = [False]*n # traverse every node as starting node # since not every node is connected for i in range(0, len(graph)): if (self.visited[i] == False): self.dfsTraverse(graph, i) return self.ok def dfsTraverse(self, graph, v): # if already known not bipartite, no need to keep traversing if self.ok == False: return; # mark the current node as visited self.visited[v] = True for i in graph[v]: # if the neighbour is not visited, set its color to opposite to current node if (self.visited[i] == False): self.colors[i] = not self.colors[v] self.dfsTraverse(graph, i) # if the neighbor is visited, and the color is the same as the current node, we've detected a false case else: if (self.colors[i] == self.colors[v]): self.ok = False
is-graph-bipartite
[Python3] DFS solution
leqinancy
0
16
is graph bipartite
785
0.527
Medium
12,806
https://leetcode.com/problems/is-graph-bipartite/discuss/1806072/Python-or-DFS-or-Notice-Separate-Nodes-Situation
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: def traverse(graph, s): nonlocal visited, colored, res # if the res has already been set to False, end backtracking if not res: return # Mark this node as visited visited[s] = True for v in graph[s]: # If this neighbor has already visited if not visited[v]: # set the color different from the neighbor colored[v] = 'Green' if colored[s] == 'Red' else 'Red' if s == 4: print(f'{v}') # visit neighbor traverse(graph, v) else: if colored[v] == colored[s]: res = False visited = [None] * len(graph) colored = [None] * len(graph) res = True for s in range(0, len(graph)-1): if not visited[s]: colored[s] = 'Red' traverse(graph, s) return res
is-graph-bipartite
Python | DFS | Notice Separate Nodes Situation
Fayeyf
0
37
is graph bipartite
785
0.527
Medium
12,807
https://leetcode.com/problems/is-graph-bipartite/discuss/1743166/EASY-or-COLORING-or-DFS-or-PYTHON3
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: # 1 red # -1 blue # 0 uncolored N = len(graph) color = [0]*N def valid_color(node, color_code): for neighbor in graph[node]: if color[neighbor] == color_code: continue elif color[neighbor] == 0: color[neighbor] = color_code if not valid_color(neighbor, -color_code): return False else: return False return True for i in range(N): if color[i] == 0: color[i]=1 if not valid_color(i, -1): return False return True
is-graph-bipartite
EASY | COLORING | DFS | PYTHON3
SN009006
0
49
is graph bipartite
785
0.527
Medium
12,808
https://leetcode.com/problems/is-graph-bipartite/discuss/1696188/785-Bipartite-Graph-with-DFS
class Solution: def isBipartite(self, graph): visited = [False] * len(graph); color = visited[:] bipartite = [True] for u in range(len(graph)): if not visited[u]: self.dfs(graph, u, visited, color, bipartite) return bipartite[0] def dfs(self, graph, u, visited, color, bipartite): if not bipartite[0]: return ### if we already know it cannot be a bipartite graph based on previouse same color, then directly return the result visited[u] = True for v in graph[u]: if not visited[v]: color[v] = not color[u] self.dfs(graph, v, visited, color, bipartite) else: if color[v] == color[u]: bipartite[0] = False
is-graph-bipartite
785 Bipartite Graph with DFS
zwang198
0
61
is graph bipartite
785
0.527
Medium
12,809
https://leetcode.com/problems/is-graph-bipartite/discuss/1694953/Python-DFS-coloring
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: def dfs(node, color): if node in seen: return seen[node] != color color ^= 1 seen[node] = color for neighbor in graph[node]: if not dfs(neighbor, color): return False return True seen = {} for node in range(len(graph)): if node not in seen and not dfs(node, 0): return False return True
is-graph-bipartite
Python DFS coloring
blue_sky5
0
42
is graph bipartite
785
0.527
Medium
12,810
https://leetcode.com/problems/is-graph-bipartite/discuss/1544587/Python-simple-dfs-solution-with-coloring
class Solution: def isBipartite(self, g: List[List[int]]) -> bool: graph = defaultdict(set) color = {} n = 0 for i in range(len(g)): v = g[i] for x in v: n = max(n, x) graph[i].add(x) unseen = set() for i in range(n): unseen.add(i) # unseen = {0, 1, ..., n-1} while unseen: for e in unseen: break ## just picking any element from unseen set stack = [(e, 0)] # 0: b, 1: r seen = set() while stack: node, c = stack.pop() seen.add(node) color[node] = c for nei in graph[node]: if nei in color and color[nei] == c: return False elif nei not in color: stack.append((nei, 1-c)) color[nei] = 1-c unseen = unseen - seen return True
is-graph-bipartite
Python simple dfs solution with coloring
byuns9334
0
133
is graph bipartite
785
0.527
Medium
12,811
https://leetcode.com/problems/is-graph-bipartite/discuss/1168736/python-fastest-dfs-with-two-colors-set!
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: connections: dict[int, list[int]] = {index: nodelist for index, nodelist in enumerate(graph)} result: list[bool] = [True] two_colors: list[set] = [set(), set()] visited: dict[int, bool] = {vertex: False for vertex in connections} level: int = 0 def dfs_visit(current: int, two_colors: list[set], level: int) -> None: visited[current] = True two_colors[level].add(current) for neighbour in graph[current]: if neighbour in two_colors[level]: result[0] = False return result[0] if not visited[neighbour]: dfs_visit(neighbour, two_colors, result, 1 if level == 0 else 0) for vertex in connections: if not visited[vertex]: dfs_visit(vertex, two_colors, level) return result[0]
is-graph-bipartite
python fastest dfs with two colors set!
rahul_sawhney
0
90
is graph bipartite
785
0.527
Medium
12,812
https://leetcode.com/problems/is-graph-bipartite/discuss/1031608/Python-simple-DFS-solution-with-comments
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: colors = [0]*len(graph) # 0: no color, 1: red, -1: green def dfs(node: int, node_color: int) -> bool: # node: current node, node_color: current node's color if colors[node] != 0: # if current node was already colored return colors[node] == node_color # return True if current node was colored the same colors[node] = node_color # color current node for neighbor in graph[node]: # iterate current node's neighbor nodes if not dfs(neighbor, -1*node_color): # DFS neighbor nodes with different color return False # return False if neighbors are non-bipartite (short-circuit) return True for node in range(len(graph)): if colors[node] == 0 and not dfs(node, 1): # iterate for nodes that are not connected return False # return False if a connected nodes are non-bipartite (short-circuit) return True
is-graph-bipartite
Python simple DFS solution with comments
cj1989
0
259
is graph bipartite
785
0.527
Medium
12,813
https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/2121258/Explained-Easiest-Python-Solution
class Solution: def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: if len(arr) > 2: res = [] # list for storing the list: [prime fraction of arr[i]/arr[j], arr[i], arr[j]] for i in range(len(arr)): for j in range(i + 1, len(arr)): # creating and adding the sublist to res tmp = [arr[i] / arr[j], arr[i], arr[j]] res.append(tmp) # sorting res on the basis of value of arr[i] res.sort(key=lambda x: x[0]) # creating and returning the required list return [res[k - 1][1], res[k - 1][2]] else: return arr
k-th-smallest-prime-fraction
[Explained] Easiest Python Solution
the_sky_high
2
180
k th smallest prime fraction
786
0.509
Medium
12,814
https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/2744456/Binary-Search-%2B-Sliding-Window-(Beats-91.21)
class Solution: def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: N = len(arr) def count_less(v): """1. the number of fractions < v 2. the largest fraction l/r that is < v""" li = 0 cnt, l, r = 0, arr[0], arr[-1] for ri in range(1, N): while li < ri and arr[li]/arr[ri] < v: if arr[li]/arr[ri] > l/r: l, r = arr[li], arr[ri] li += 1 cnt += li return cnt, l, r lo, hi = arr[0]/arr[-1], 1 while lo <= hi: v = (lo+hi)/2 cnt, l, r = count_less(v) if cnt == k: return [l, r] if cnt < k: lo = v else: hi = v
k-th-smallest-prime-fraction
Binary Search + Sliding Window (Beats 91.21%)
GregHuang
1
60
k th smallest prime fraction
786
0.509
Medium
12,815
https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/2848235/Python-Collect-(num1-num2-num1num2)-then-sort-on-fraction-ASC
class Solution: def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: ''' I want to go from Input: arr = [1,2,3,5], k = 3 ; Output: [2,5] Each [(num1, num2, fraction), ...] To: [(1, 5, 1/5), (1, 3, 1/3), (2, 5, 2/5), (1, 2, 1/2), (3, 5, 3/5), (2, 3, 2/3)] ^^^^^^^^^ after sorting by fraction ASC and return the [num1, num2] of the kth-smallest fraction -> [2, 5] from (2, 5, 2/5) ''' N, data = len(arr), [] # Collect the data in the target data structure for one in range(N - 1): for two in range(one + 1, N): data.append((arr[one], arr[two], arr[one] / arr[two])) # Sort the data based on logic pre-defined above -> sorting on fraction ASC data.sort(key=lambda x: x[2]) # Return k-th data in required format, [num_one, num_two] kth_data = data[k - 1] num_one, num_two, fraction = kth_data return [num_one, num_two]
k-th-smallest-prime-fraction
[Python] Collect (num1, num2, num1/num2), then sort on fraction ASC
graceiscoding
0
1
k th smallest prime fraction
786
0.509
Medium
12,816
https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/2599568/Python3-or-Solved-Using-Sorting-and-Trying-Every-Possible-Pairings
class Solution: #Time-Complexity: O(n^2 + n^2log(n^2)) -> O(n^2*log(n^2)) ->O(n^2*log(n)) #Space-Complexity: O(n^2) def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: array = [] for i in range(0, len(arr)-1): numerator = arr[i] for j in range(i+1, len(arr)): denominator = arr[j] division = numerator / denominator array.append([numerator, denominator, division]) array.sort(key = lambda x : x[2]) ans = [] ans.append(array[k-1][0]) ans.append(array[k-1][1]) return ans
k-th-smallest-prime-fraction
Python3 | Solved Using Sorting and Trying Every Possible Pairings
JOON1234
0
19
k th smallest prime fraction
786
0.509
Medium
12,817
https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/1669752/Python-SubOptimal-but-Easy-to-understand
class Solution: def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: minHeap=[] n = len(arr) x=y=0 for i in range(n): for j in range(i+1,n): if arr[j] !=0: heapq.heappush(minHeap, (arr[i]/arr[j], (arr[i],arr[j]))) for _ in range(k): _,(x,y) = heapq.heappop(minHeap) return [x,y]
k-th-smallest-prime-fraction
[Python] SubOptimal but Easy to understand
JimmyJammy1
0
89
k th smallest prime fraction
786
0.509
Medium
12,818
https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/1305847/Python3-priority-queue
class Solution: def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: pq = [(arr[i]/arr[-1], i, -1) for i in range(len(arr)-1)] for _ in range(k): _, i, j = heappop(pq) if i - j + 1 < len(arr): heappush(pq, (arr[i]/arr[j-1], i, j-1)) return [arr[i], arr[j]]
k-th-smallest-prime-fraction
[Python3] priority queue
ye15
0
90
k th smallest prime fraction
786
0.509
Medium
12,819
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2066105/Python-Easy-Solution-using-Dijkstra's-Algorithm
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: #Make graph adj_list = {i:[] for i in range(n)} for frm, to, price in flights: adj_list[frm].append((to, price)) best_visited = [2**31]*n # Initialized to maximum prior_queue = [ (0, -1, src) ] # weight, steps, node while prior_queue: cost, steps, node = heapq.heappop(prior_queue) if best_visited[node] <= steps: # Have seen the node already, and the current steps are more than last time continue if steps > k: # More than k stops, invalid continue if node==dst: # reach the destination # as priority_queue is a minHeap so this cost is the most minimum cost. return cost best_visited[node] = steps # Update steps for neighb, weight in adj_list[node]: heapq.heappush(prior_queue, (cost + weight, steps + 1, neighb)) return -1 # Time: O(n * len(flights) * log(n)) # Space: O(n)
cheapest-flights-within-k-stops
Python Easy Solution using Dijkstra's Algorithm
samirpaul1
6
445
cheapest flights within k stops
787
0.359
Medium
12,820
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/790296/Readable-Python-(Djikstra)
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int: graph = {} for u in range(n): graph[u] = [] for u,v,w in flights: graph[u].append((v,w)) heap = [(0,-K,src)] while heap: (cost,i,u) = heapq.heappop(heap) if u == dst: return cost for v,w in graph[u]: nc = cost + w if i <= 0: heapq.heappush(heap, (nc,i+1,v)) return -1
cheapest-flights-within-k-stops
Readable Python (Djikstra)
2kvai777
6
911
cheapest flights within k stops
787
0.359
Medium
12,821
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2831572/Pythonordpbfs
class Solution: def dp(self, cur, price, step): if cur == self.dst: return price if step == 0: return inf if self.memo[cur][step]: return self.memo[cur][step] res = inf for item in self.graph[cur]: neighbor, cost = item[0], item[1] res = min(res, self.dp(neighbor, price, step-1) + cost) self.memo[cur][step] = res return res def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: self.dst = dst self.graph = {key: [] for key in range(n)} for flight in flights: self.graph[flight[0]].append((flight[1], flight[2])) self.memo = [[None for _ in range(k+2)] for _ in range(n)] res = self.dp(src, 0, k+1) res = res if res != inf else -1 return res
cheapest-flights-within-k-stops
Python|dp/bfs
lucy_sea
0
8
cheapest flights within k stops
787
0.359
Medium
12,822
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2831030/BFS
class Solution: def findCheapestPrice(self, n: int, edges: List[List[int]], src: int, dst: int, k: int) -> int: adj = [[] for _ in range(n)] m = len(edges) for i in range(m): u, v, w = edges[i] adj[u].append((v, w)) @lru_cache(None) def dp(u, k): if u == dst: return 0 if k == 0: return math.inf ans = math.inf for v, w in adj[u]: ans = min(ans, w+dp(v, k-1)) return ans ans = dp(src, k+1) return ans if ans != math.inf else -1
cheapest-flights-within-k-stops
BFS
lillllllllly
0
5
cheapest flights within k stops
787
0.359
Medium
12,823
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2807007/Python-(Simple-Dynamic-Programming)
class Solution: def findCheapestPrice(self, n, flights, src, dst, k): dp = [[float("inf")]*(k+2) for _ in range(n)] dp[src][0] = 0 for col in range(1,k+2): for row in range(n): dp[row][col] = dp[row][col-1] for s,e,v in flights: dp[e][col] = min(dp[s][col-1] + v,dp[e][col]) return dp[dst][-1] if dp[dst][-1] != float("inf") else -1
cheapest-flights-within-k-stops
Python (Simple Dynamic Programming)
rnotappl
0
11
cheapest flights within k stops
787
0.359
Medium
12,824
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2740287/dictionary-solution-python
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int: # Build the adjacency matrix adj_matrix = [[0 for _ in range(n)] for _ in range(n)] for s, d, w in flights: adj_matrix[s][d] = w # Shortest distances dictionary distances = {} distances[(src, 0)] = 0 # BFS Queue bfsQ = deque([src]) # Number of stops remaining stops = 0 ans = float("inf") # Iterate until we exhaust K+1 levels or the queue gets empty while bfsQ and stops < K + 1: # Iterate on current level length = len(bfsQ) for _ in range(length): node = bfsQ.popleft() # Loop over neighbors of popped node for nei in range(n): if adj_matrix[node][nei] > 0: dU = distances.get((node, stops), float("inf")) dV = distances.get((nei, stops + 1), float("inf")) wUV = adj_matrix[node][nei] # No need to update the minimum cost if we have already exhausted our K stops. if stops == K and nei != dst: continue if dU + wUV < dV: distances[nei, stops + 1] = dU + wUV bfsQ.append(nei) # Shortest distance of the destination from the source if nei == dst: ans = min(ans, dU + wUV) stops += 1 return -1 if ans == float("inf") else ans
cheapest-flights-within-k-stops
dictionary solution python
yhu415
0
2
cheapest flights within k stops
787
0.359
Medium
12,825
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2710124/Simple-Djikstra
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: graph = defaultdict(list) for flight in flights: s,d,price = flight graph[s].append((d,price)) prices = [float("inf")]*n prices[src] = 0 minHeap = [] heappush(minHeap,(0,0,src)) while minHeap: steps,price,node = heappop(minHeap) if node == dst or steps > k: continue for nei in graph[node]: nei_node,nei_price = nei new_price = price + nei_price if new_price < prices[nei_node]: prices[nei_node] = new_price heappush(minHeap,(steps+1,new_price,nei_node)) if prices[dst] == float("inf"): return -1 return prices[dst]
cheapest-flights-within-k-stops
Simple Djikstra
shriyansnaik
0
12
cheapest flights within k stops
787
0.359
Medium
12,826
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2672100/9-line-python-bellman-ford-beats-57
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: dis = [float('inf')]*n dis[src]=0 for i in range(k+1): backup = dis[:] for a,b,c in flights: dis[b] = min(dis[b],backup[a]+c) return dis[dst] if dis[dst]!=float('inf') else -1
cheapest-flights-within-k-stops
9 line python bellman-ford beats 57%
Ttanlog
0
4
cheapest flights within k stops
787
0.359
Medium
12,827
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2607312/Python3-DFS-w-Cache-or-O(k-*-(V-%2B-E))
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: @cache def dfs(cur, stops): if stops > k: return float('inf') cheapest = float('inf') for nxt, price in adj[cur]: if nxt == dst: cheapest = min(cheapest, price) else: cheapest = min(cheapest, price + dfs(nxt, stops + 1)) return cheapest adj = [[] for _ in range(n)] for fro, to, price in flights: adj[fro].append((to, price)) cost = dfs(src, 0) return -1 if cost == float('inf') else cost
cheapest-flights-within-k-stops
Python3 DFS w/ Cache | O(k * (V + E))
ryangrayson
0
32
cheapest flights within k stops
787
0.359
Medium
12,828
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2345657/python-easy-fast
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: prices = [float("inf")] * n prices[src] = 0 for i in range(k + 1): tempPrices = prices.copy() for s,d,p in flights: if prices[s] == float("inf"): continue if prices[s] + p < tempPrices[d]: tempPrices[d] = prices[s] + p prices = tempPrices return -1 if prices[dst] == float("inf") else prices[dst]
cheapest-flights-within-k-stops
python easy fast
soumyadexter7
0
142
cheapest flights within k stops
787
0.359
Medium
12,829
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2249651/HELP-NEEDED!-Why-does-DFS-does-not-work-in-this-solution
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: adj = [[] for _ in range(n)] costs = {} for flight_info in flights: c1 = flight_info[0] c2 = flight_info[1] cost = flight_info[2] costs[(c1, c2)] = cost adj[c1].append(c2) q = [(src, 0, 0)] visited = {} while(q): node = q.pop(0) # <-- node = q.pop() makes it dfs c1 = node[0] curr_cost = node[1] depth = node[2] if c1 == dst or depth==k+1: continue for c2 in adj[c1]: additional = curr_cost+costs[(c1,c2)] if additional >= visited.get(c2, float('inf')): continue q.append([c2, additional, depth+1]) visited[c2] = additional return visited.get(dst, -1)
cheapest-flights-within-k-stops
HELP NEEDED! Why does DFS does not work in this solution?
gabhinav001
0
93
cheapest flights within k stops
787
0.359
Medium
12,830
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/1132908/Python-Simple-DP-O(n3)
class Solution: def findCheapestPrice(self, n: int, edges: List[List[int]], src: int, dst: int, k: int) -> int: adj = [[] for _ in range(n)] m = len(edges) for i in range(m): u, v, w = edges[i] adj[u].append((v, w)) @lru_cache(None) def dp(u, k): if u == dst: return 0 if k == 0: return math.inf ans = math.inf for v, w in adj[u]: ans = min(ans, w+dp(v, k-1)) return ans ans = dp(src, k+1) return ans if ans != math.inf else -1
cheapest-flights-within-k-stops
[Python] Simple DP O(n^3)
carloscerlira
0
109
cheapest flights within k stops
787
0.359
Medium
12,831
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/687236/Python3-solution
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int: graph = defaultdict(list) # adjacency list for u, v, w in flights: graph[u].append([v, w]) Q = deque([ [ src, 0] ]) # current node, cum cost min_cost = float('inf') while Q: qs = len(Q) # current q size for _ in range(qs): # we will pop all there was in that BFS-level city, cumcost = Q.popleft() if city == dst: # check to see if we need to update min_cost min_cost = min(min_cost, cumcost) else: # cist != dst for neigh, cost in graph[city]: if cumcost + cost < min_cost: #only if total cost to get to the next node is less than current min_cost, otherwise you are TLEing... Q.append([neigh, cumcost + cost]) if K==-1: # after max of K-stops we return break K -= 1 return min_cost if min_cost != float('inf') else -1
cheapest-flights-within-k-stops
Python3 solution
dalechoi
0
66
cheapest flights within k stops
787
0.359
Medium
12,832
https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/1042290/Bellman-Ford-Solution-in-C%2B%2B-and-Python3
class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int: dist_price = [float('inf') for _ in range(n)] dist_price[src]=0 for source,dest,cost in flights: if src==source: dist_price[dest] = cost for times in range(0,K): temp = [*dist_price] for srce,dest,cost in flights: temp[dest] = min(temp[dest] , cost + dist_price[srce]) dist_price = temp if dist_price[dst] == float('inf'): return -1 return dist_price[dst]
cheapest-flights-within-k-stops
Bellman Ford Solution in C++ and Python3
aparna_g
-4
338
cheapest flights within k stops
787
0.359
Medium
12,833
https://leetcode.com/problems/rotated-digits/discuss/1205605/Python3-simple-solution-using-two-approaches
class Solution: def rotatedDigits(self, N: int) -> int: count = 0 for x in range(1, N+1): x = str(x) if '3' in x or '4' in x or '7' in x: continue if '2' in x or '5' in x or '6' in x or '9' in x: count+=1 return count
rotated-digits
Python3 simple solution using two approaches
EklavyaJoshi
4
207
rotated digits
788
0.568
Medium
12,834
https://leetcode.com/problems/rotated-digits/discuss/1205605/Python3-simple-solution-using-two-approaches
class Solution: def rotatedDigits(self, N: int) -> int: d = {'0':'0','1':'1','2':'5','5':'2','6':'9','8':'8','9':'6'} count = 0 for i in range(1,N+1): x = '' flag = True for j in str(i): if j not in d.keys(): flag = False break else: x += d[j] if flag and x != str(i): count += 1 return count
rotated-digits
Python3 simple solution using two approaches
EklavyaJoshi
4
207
rotated digits
788
0.568
Medium
12,835
https://leetcode.com/problems/rotated-digits/discuss/551837/Python3-solution-using-a-string-conversion
class Solution: def rotatedDigits(self, N: int) -> int: quantity = 0 for num in range(1, N+1): tally = str(num) if any([True if x in '347' else False for x in tally]): continue if all([True if x in '018' else False for x in tally]): continue quantity += 1 return quantity
rotated-digits
Python3 solution, using a string conversion
altareen
2
191
rotated digits
788
0.568
Medium
12,836
https://leetcode.com/problems/rotated-digits/discuss/343982/Solution-in-Python-3-(beats-~100)-O(log-n)-(Combinatoric-Solution)-(Not-Brute-Force)
class Solution: def rotatedDigits(self, N: int) -> int: N, t, c = str(N), 0, 1 L, a, b = len(N) - 1, [1,2,3,3,3,4,5,5,6,7], [1,2,2,2,2,2,2,2,3,3] for i in range(L): if N[i] == '0': continue t += a[int(N[i])-1]*7**(L-i) - c*b[int(N[i])-1]*3**(L-i) if N[i] in '347': return t if N[i] not in '18': c = 0 return t + a[int(N[-1])] - c*b[int(N[-1])] - Junaid Mansuri
rotated-digits
Solution in Python 3 (beats ~100%) O(log n) (Combinatoric Solution) (Not Brute Force)
junaidmansuri
2
671
rotated digits
788
0.568
Medium
12,837
https://leetcode.com/problems/rotated-digits/discuss/2063497/Python-straightforward-solution
class Solution: def rotatedDigits(self, n: int) -> int: ans = 0 for i in range(1, n+1): p = '' if '3' in str(i) or '4' in str(i) or '7' in str(i): continue for j in str(i): if j == '0': p += '0' elif j == '1': p += '1' elif j == '8': p += '8' elif j == '2': p += '5' elif j == '5': p += '2' elif j == '6': p += '9' elif j == '9': p += '6' if p != str(i): ans += 1 return ans
rotated-digits
Python straightforward solution
StikS32
1
161
rotated digits
788
0.568
Medium
12,838
https://leetcode.com/problems/rotated-digits/discuss/454860/Python3%3A-20ms-(99.86-faster)-12.7MB-(100-memory)
class Solution: def rotatedDigits(self, N: int) -> int: smallSet = {0,1,8} bigSet = {2,5,6,9} smallNum = [0,0,1,1,1,2,3,3,3,4][N % 10] bigNum = [1,2,3,3,3,4,5,5,6,7][N % 10] N = N // 10 smInc, bgInc = 4, 7 while N: x = N % 10 N = N // 10 sm, bg = 0, 0 for i in range(x): if i in smallSet: sm += smInc bg += bgInc elif i in bigSet: sm += bgInc bg += bgInc if x in smallSet: smallNum += sm bigNum += bg elif x in bigSet: smallNum = bigNum + sm bigNum += bg else: smallNum = sm bigNum = bg smInc, bgInc = 4*bgInc + 3*smInc, bgInc * 7 return smallNum
rotated-digits
Python3: 20ms (99.86% faster) 12.7MB (100% memory)
andnik
1
326
rotated digits
788
0.568
Medium
12,839
https://leetcode.com/problems/rotated-digits/discuss/325045/Python-solution-using-dictionary
class Solution: def rotatedDigits(self, N: int) -> int: count=0 d={0:0,1:1,2:5,3:-1,4:-1,5:2,6:9,7:-1,8:8,9:6} for i in range(1,N+1): l=list(str(i)) res=[] for j in l: if d[int(j)]!=-1: res.append(str(d[int(j)])) else:break if len(res)==len(l) and int(''.join(res))!=i: count+=1 return count
rotated-digits
Python solution using dictionary
ketan35
1
189
rotated digits
788
0.568
Medium
12,840
https://leetcode.com/problems/rotated-digits/discuss/2810782/Python-(Simple-Dynamic-Programming)
class Solution: def dfs(self,x): dict1, x, str1 = {"0":"0","1":"1","8":"8","2":"5","5":"2","6":"9","9":"6"}, str(x), "" for i in x: if i not in dict1: return False else: str1 += dict1[i] return str1 != x def rotatedDigits(self, n): dict1 = {0:0,1:1,8:8,2:5,5:2,6:9,9:6} dp = [1]*(n+1) for i in range(1,n+1): if self.dfs(i): dp[i] = max(1 + dp[i-1],dp[i]) else: dp[i] = dp[i-1] return dp[-1] - 1
rotated-digits
Python (Simple Dynamic Programming)
rnotappl
0
5
rotated digits
788
0.568
Medium
12,841
https://leetcode.com/problems/rotated-digits/discuss/1463538/Brute-force-and-walrus
class Solution: not_allowed = {"3", "4", "7"} mirrored = {"0", "1", "8"} def rotatedDigits(self, n: int) -> int: return n - sum(int(bool((s := set(str(i))) &amp; Solution.not_allowed) or s.issubset(Solution.mirrored)) for i in range(1, n + 1))
rotated-digits
Brute force and walrus
EvgenySH
0
42
rotated digits
788
0.568
Medium
12,842
https://leetcode.com/problems/rotated-digits/discuss/1328227/Python3-dollarolution
class Solution: def rotatedDigits(self, n: int) -> int: v, l = ['0','1','8','2','5','6','9'], [] c = 0 for i in range(2,n+1): x = 1 l = [] y = str(i) for j in y: if j not in v: x = 0 break l.append(v.index(j)) if x == 1 and not all(e < 3 for e in l): c += 1 return c
rotated-digits
Python3 $olution
AakRay
0
171
rotated digits
788
0.568
Medium
12,843
https://leetcode.com/problems/rotated-digits/discuss/408795/Python-Simple-Solution
class Solution: def rotatedDigits(self, N: int) -> int: numb = set(['6','9','2','5', '1', '0', '8']) cnt = 0 for i in range(1,N+1): t = set(str(i)) if t-numb==set(): if t-set(['8', '0', '1'])==set(): pass else: cnt+=1 return cnt
rotated-digits
Python Simple Solution
saffi
0
502
rotated digits
788
0.568
Medium
12,844
https://leetcode.com/problems/escape-the-ghosts/discuss/1477363/Python-3-or-Manhattan-Distance-Math-or-Explanation
class Solution: def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool: t_x, t_y = target m_x, m_y = abs(t_x), abs(t_y) for x, y in ghosts: manhattan = abs(t_x - x) + abs(t_y - y) if manhattan <= m_x + m_y: return False return True
escape-the-ghosts
Python 3 | Manhattan Distance, Math | Explanation
idontknoooo
1
117
escape the ghosts
789
0.607
Medium
12,845
https://leetcode.com/problems/escape-the-ghosts/discuss/930127/Python3-brainteaser
class Solution: def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool: xx, yy = target return all(abs(x-xx) + abs(y-yy) > abs(xx) + abs(yy) for x, y in ghosts)
escape-the-ghosts
[Python3] brainteaser
ye15
1
86
escape the ghosts
789
0.607
Medium
12,846
https://leetcode.com/problems/escape-the-ghosts/discuss/1427939/Python3-simple-O(N)-time-and-O(1)-space-solution
class Solution: def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool: for i in ghosts: if abs(i[0]-target[0]) + abs(i[1]-target[1]) <= abs(target[0])+abs(target[1]): return False return True
escape-the-ghosts
Python3 simple O(N) time and O(1) space solution
EklavyaJoshi
0
55
escape the ghosts
789
0.607
Medium
12,847
https://leetcode.com/problems/escape-the-ghosts/discuss/1085358/python-2-line-easy-faster-than-80
class Solution: def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool: l = [abs(ghost[0]-target[0])+abs(ghost[1]-target[1]) for ghost in ghosts] return min(l)>abs(target[0])+abs(target[1])
escape-the-ghosts
python 2-line easy faster than 80%
zzj8222090
0
105
escape the ghosts
789
0.607
Medium
12,848
https://leetcode.com/problems/domino-and-tromino-tiling/discuss/1620809/PythonJAVACC%2B%2B-DP-oror-Image-Visualized-Explanation-oror-100-Faster-oror-O(N)
class Solution(object): def numTilings(self, n): dp = [1, 2, 5] + [0] * n for i in range(3, n): dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007 return dp[n - 1]
domino-and-tromino-tiling
✅ [Python/JAVA/C/C++] DP || Image Visualized Explanation || 100% Faster || O(N)
linfq
84
2,800
domino and tromino tiling
790
0.484
Medium
12,849
https://leetcode.com/problems/domino-and-tromino-tiling/discuss/1620809/PythonJAVACC%2B%2B-DP-oror-Image-Visualized-Explanation-oror-100-Faster-oror-O(N)
class Solution(object): def numTilings(self, n): dp, dpa = [1, 2] + [0] * n, [1] * n for i in range(2, n): dp[i] = (dp[i - 1] + dp[i - 2] + dpa[i - 1] * 2) % 1000000007 dpa[i] = (dp[i - 2] + dpa[i - 1]) % 1000000007 return dp[n - 1]
domino-and-tromino-tiling
✅ [Python/JAVA/C/C++] DP || Image Visualized Explanation || 100% Faster || O(N)
linfq
84
2,800
domino and tromino tiling
790
0.484
Medium
12,850
https://leetcode.com/problems/domino-and-tromino-tiling/discuss/1620640/Python-dynamic-programming-in-4-lines-O(N)-time-and-O(1)-space
class Solution: def numTilings(self, n: int) -> int: full_0, full_1, incomp_1 = 1, 2, 2 for i in range(2, n): full_0, full_1, incomp_1 = full_1, full_0 + full_1 + incomp_1, 2 * full_0 + incomp_1 return full_1 % (10 ** 9 + 7) if n >= 2 else 1
domino-and-tromino-tiling
Python dynamic programming in 4 lines, O(N) time and O(1) space
kryuki
8
567
domino and tromino tiling
790
0.484
Medium
12,851
https://leetcode.com/problems/domino-and-tromino-tiling/discuss/1620640/Python-dynamic-programming-in-4-lines-O(N)-time-and-O(1)-space
class Solution: def numTilings(self, n: int) -> int: #edge case if n == 1: return 1 mod = 10 ** 9 + 7 dp_full = [0 for _ in range(n)] dp_incomp = [0 for _ in range(n)] dp_full[0] = 1 dp_full[1] = 2 dp_incomp[1] = 2 for i in range(2, n): dp_full[i] = dp_full[i - 2] + dp_full[i - 1] + dp_incomp[i - 1] dp_incomp[i] = dp_full[i - 2] * 2 + dp_incomp[i - 1] return dp_full[-1] % mod
domino-and-tromino-tiling
Python dynamic programming in 4 lines, O(N) time and O(1) space
kryuki
8
567
domino and tromino tiling
790
0.484
Medium
12,852
https://leetcode.com/problems/domino-and-tromino-tiling/discuss/1621616/Python3-recursion-%2B-memo-(-dp-on-broken-profile-)
class Solution: def __init__(self): self.table = {(0,0):1, (0,3):1} self.mod = 1000000007 def func(self, pos, state): if pos < 0: return 0 elif (pos, state) not in self.table: if state == 0: self.table[(pos, state)] = self.func(pos-1, 3) elif state == 1: self.table[(pos, state)] = self.func(pos-1, 0) + self.func(pos-1, 2) elif state == 2: self.table[(pos, state)] = self.func(pos-1, 0) + self.func(pos-1, 1) elif state == 3: self.table[(pos, state)] = self.func(pos-1, 0) + self.func(pos-1, 1) + self.func(pos-1, 2) + self.func(pos-1, 3) self.table[(pos, state)] %= self.mod return self.table[(pos, state)] def numTilings(self, n: int) -> int: return self.func(n-1, 3)
domino-and-tromino-tiling
Python3 recursion + memo ( dp on broken profile )
aditya04848
0
19
domino and tromino tiling
790
0.484
Medium
12,853
https://leetcode.com/problems/domino-and-tromino-tiling/discuss/1621456/Simple-Fast-Python-Solution
class Solution: def numTilings(self, n: int) -> int: a, b, c = 0, 1, 1 i = 1 while i < n: a, b, c = a+b, c, a*2 + b + c i += 1 return c % (10**9 + 7)
domino-and-tromino-tiling
Simple Fast Python Solution
VicV13
0
61
domino and tromino tiling
790
0.484
Medium
12,854
https://leetcode.com/problems/domino-and-tromino-tiling/discuss/930186/Python3-top-down-and-bottom-up-dp
class Solution: def numTilings(self, N: int) -> int: @cache def fn(n): """Return number of ways to tile board.""" if n < 0: return 0 if n <= 1: return 1 return (2*fn(n-1) + fn(n-3)) % 1_000_000_007 return fn(N)
domino-and-tromino-tiling
[Python3] top-down & bottom-up dp
ye15
0
130
domino and tromino tiling
790
0.484
Medium
12,855
https://leetcode.com/problems/domino-and-tromino-tiling/discuss/930186/Python3-top-down-and-bottom-up-dp
class Solution: def numTilings(self, N: int) -> int: ans = [1]*(N+1) prefix = 2 for i in range(2, N+1): ans[i] = 2*prefix - ans[i-1] - ans[i-2] prefix += ans[i] return ans[-1] % 1_000_000_007
domino-and-tromino-tiling
[Python3] top-down & bottom-up dp
ye15
0
130
domino and tromino tiling
790
0.484
Medium
12,856
https://leetcode.com/problems/domino-and-tromino-tiling/discuss/930186/Python3-top-down-and-bottom-up-dp
class Solution: def numTilings(self, N: int) -> int: f0, f1, f2 = 0, 1, 1 for i in range(N-1): f0, f1, f2 = f1, f2, (2*f2 + f0) % 1_000_000_007 return f2
domino-and-tromino-tiling
[Python3] top-down & bottom-up dp
ye15
0
130
domino and tromino tiling
790
0.484
Medium
12,857
https://leetcode.com/problems/custom-sort-string/discuss/2237060/Simple-yet-interview-friendly-or-Faster-than-99.97-or-Custom-Sorting-in-Python
class Solution: def customSortString(self, order: str, s: str) -> str: rank = [26]*26 for i in range(len(order)): rank[ord(order[i]) - ord('a')] = i return "".join(sorted(list(s), key= lambda x: rank[ord(x) - ord('a')]))
custom-sort-string
✅ Simple yet interview friendly | Faster than 99.97% | Custom Sorting in Python
reinkarnation
2
62
custom sort string
791
0.693
Medium
12,858
https://leetcode.com/problems/custom-sort-string/discuss/2237060/Simple-yet-interview-friendly-or-Faster-than-99.97-or-Custom-Sorting-in-Python
class Solution: def customSortString(self, order: str, s: str) -> str: def serialOrder(x): return rank[ord(x) - ord('a')] rank = [26]*26 for i in range(len(order)): rank[ord(order[i]) - ord('a')] = i print(rank) arr = [i for i in s] arr.sort(key= serialOrder) s = "".join(arr) return s
custom-sort-string
✅ Simple yet interview friendly | Faster than 99.97% | Custom Sorting in Python
reinkarnation
2
62
custom sort string
791
0.693
Medium
12,859
https://leetcode.com/problems/custom-sort-string/discuss/1813444/Python-easy-to-read-and-understand
class Solution: def customSortString(self, order: str, s: str) -> str: ans = "" for ch in order: cnt = s.count(ch) for i in range(cnt): ans += ch for ch in s: if ch not in order: ans += ch return ans
custom-sort-string
Python easy to read and understand
sanial2001
1
82
custom sort string
791
0.693
Medium
12,860
https://leetcode.com/problems/custom-sort-string/discuss/1735581/Python-99.8-Less-Memory-38.1-Faster-easy-to-understand
class Solution: def customSortString(self, order: str, s: str) -> str: #output string sout = '' count = 0 #iterate though the order for sortletter in order: #check if sortletter is in s, add to output var count = s.count(sortletter) if count > 0: sout = sout+ sortletter*(count) #remove the letter from s s = s.replace(sortletter,'',count) count = 0 return(sout+s)
custom-sort-string
Python 99.8% Less Memory, 38.1 Faster - easy to understand
ovidaure
1
127
custom sort string
791
0.693
Medium
12,861
https://leetcode.com/problems/custom-sort-string/discuss/1191458/Python3-simple-solution-beats-99-users
class Solution: def customSortString(self, S: str, T: str) -> str: x = '' t = {} for i in T: if i not in S: x += i t[i] = t.get(i,0) + 1 for i in S: if i in T: x += i*t[i] return x
custom-sort-string
Python3 simple solution beats 99% users
EklavyaJoshi
1
60
custom sort string
791
0.693
Medium
12,862
https://leetcode.com/problems/custom-sort-string/discuss/2808426/using-built-in-sorted-and-hashmap
class Solution: def customSortString(self, order: str, s: str) -> str: # Q does not say we cannot use built-in sort # len(s) = n, len(order) = m # Space Complexity: O(m+n) # Time Complexity: O(nlogn) # average case for built in Python Tim Sort order_map = {o: i for i, o in enumerate(order)} # 27 to ensure any letter not in `order` is returned last return "".join(sorted(s, key= lambda x : order_map.get(x, 27)))
custom-sort-string
using built in `sorted` and hashmap
curiosity_kids
0
2
custom sort string
791
0.693
Medium
12,863
https://leetcode.com/problems/custom-sort-string/discuss/2796144/Beats-91.2-2-Liner
class Solution: def customSortString(self, order: str, s: str) -> str: cmap=collections.Counter(s) return "".join(i*cmap[i] for i in order if i in s) + "".join(i for i in s if i not in order)
custom-sort-string
Beats 91.2% - 2 Liner
avinash_konduri
0
2
custom sort string
791
0.693
Medium
12,864
https://leetcode.com/problems/custom-sort-string/discuss/2796143/Beats-91.2-2-Liner
class Solution: def customSortString(self, order: str, s: str) -> str: cmap=collections.Counter(s) return "".join(i*cmap[i] for i in order if i in s) + "".join(i for i in s if i not in order)
custom-sort-string
Beats 91.2% - 2 Liner
avinash_konduri
0
2
custom sort string
791
0.693
Medium
12,865
https://leetcode.com/problems/custom-sort-string/discuss/2778186/Clean-and-Concise-python-1-line-beats-69-memory
class Solution: def customSortString(self, order: str, s: str) -> str: return "".join(sorted(s, key=(lambda x: order.index(x) if x in order else 100)))
custom-sort-string
Clean and Concise python 1 line beats 69% memory
AryaDot
0
2
custom sort string
791
0.693
Medium
12,866
https://leetcode.com/problems/custom-sort-string/discuss/2614831/python-easy-solution
class Solution: def customSortString(self, order: str, s: str) -> str: str1="" for i in s: if i not in order: str1+=i res="" d = Counter(s) for i in order: if i in d: res+=i*d[i] return res+str1
custom-sort-string
python easy solution
anshsharma17
0
13
custom sort string
791
0.693
Medium
12,867
https://leetcode.com/problems/custom-sort-string/discuss/2608411/Python-or-3-Liner-Solution-or-Easy-to-understand-or-Detailed-Solution
class Solution: def customSortString(self, order: str, s: str) -> str: # Assign each character a value in order and store it in hash map. orderMap = {c: i for i, c in enumerate(order)} # On the basis of order hash map, create the array of character map. If the char is not there in order map then push that element to the last, by assigning 27 to that char. charMap = [(c, orderMap.get(c, 27)) for i, c in enumerate(s)] # Then sort the character map on the basis of value, join the characters and return the final word. return ''.join([c for c, i in sorted(charMap, key=lambda x:x[1])])
custom-sort-string
Python | 3 Liner Solution | Easy to understand | Detailed Solution
Aexki
0
16
custom sort string
791
0.693
Medium
12,868
https://leetcode.com/problems/custom-sort-string/discuss/2471050/easy-python-solution
class Solution: def customSortString(self, order: str, s: str) -> str: orderChar = [i for i in order] sChar = [i for i in s] notPresent = [] ans = '' for i in orderChar : if i in sChar : for times in range(sChar.count(i)) : ans += i for i in sChar : if i not in orderChar : notPresent.append(i) notPresent.sort() for i in notPresent : ans += i return ans
custom-sort-string
easy python solution
sghorai
0
20
custom sort string
791
0.693
Medium
12,869
https://leetcode.com/problems/custom-sort-string/discuss/2293310/Python3-or-using-Counter
class Solution: def customSortString(self, order: str, s: str) -> str: count_s, res = Counter(s), "" for char in order: if char in count_s: res += (char * count_s[char]) del count_s[char] return res + "".join([(k*v) for k, v in count_s.items()])
custom-sort-string
Python3 | using Counter
Ploypaphat
0
36
custom sort string
791
0.693
Medium
12,870
https://leetcode.com/problems/custom-sort-string/discuss/2186078/python-solution-with-explanation
class Solution: def customSortString(self, order: str, s: str) -> str: """ Example: Input: order = "cba", s = "abcdeab" Output: "cbbaade" 1. Create a map of string s 2. Iterate over the string order and add similar characters from the map to keep the ans strings characters in correct order and set those characters value to zero 3. Now iterate over the map to add characters that were not present in the string order """ map_ = collections.Counter(s) ans = "" for char in order: if char in map_: ans += (char)*map_[char] map_[char] = 0 for char in map_: if map_[char] > 0: ans += (char)*map_[char] return ans
custom-sort-string
python solution with explanation
yash921
0
20
custom sort string
791
0.693
Medium
12,871
https://leetcode.com/problems/custom-sort-string/discuss/1779999/Python-really-simple-using-hashmap
class Solution: def customSortString(self, order: str, s: str) -> str: o = collections.defaultdict(lambda: 0) for i, c in enumerate(order): o[c] = i; return ''.join(sorted(s, key = lambda c: o[c]))
custom-sort-string
Python really simple using hashmap
kaichamp101
0
80
custom sort string
791
0.693
Medium
12,872
https://leetcode.com/problems/custom-sort-string/discuss/1684699/Simple-Python3-beats-87.41
class Solution: def customSortString(self, order: str, s: str) -> str: ranking = {v:i for i, v in enumerate(order)} rest = '' ans = '' for x in s: if x not in ranking: rest += x continue ans += x ans = sorted(ans, key = lambda x: ranking[x]) return ''.join(ans) + rest
custom-sort-string
Simple Python3 beats 87.41%
mclovin286
0
53
custom sort string
791
0.693
Medium
12,873
https://leetcode.com/problems/custom-sort-string/discuss/1569065/Python-hashmap
class Solution: def customSortString(self, order: str, s: str) -> str: order_map = collections.defaultdict(lambda: -1) for i, c in enumerate(order): order_map[c] = i return ''.join(sorted(s, key=lambda x: order_map[x]))
custom-sort-string
Python hashmap
dereky4
0
161
custom sort string
791
0.693
Medium
12,874
https://leetcode.com/problems/custom-sort-string/discuss/1559181/Python3-2-liners
class Solution: def customSortString(self, order: str, s: str) -> str: order_dict = {c: i + 1 for i, c in enumerate(order)} return ''.join(sorted(s, key=lambda x: order_dict.get(x, 0)))
custom-sort-string
Python3 2 liners
needforspeed
0
51
custom sort string
791
0.693
Medium
12,875
https://leetcode.com/problems/custom-sort-string/discuss/1559181/Python3-2-liners
class Solution: def customSortString(self, order: str, s: str) -> str: order_dict = {c: i + 1 for i, c in enumerate(order)} return ''.join(sorted(s, key=lambda x: order_dict.get(x, len(order_dict))))
custom-sort-string
Python3 2 liners
needforspeed
0
51
custom sort string
791
0.693
Medium
12,876
https://leetcode.com/problems/custom-sort-string/discuss/1531759/Python3-Time%3A-O(s%2Bo)-and-Space%3A-O(s)
class Solution: def customSortString(self, order: str, s: str) -> str: # "cba", "abcd" => cbad # "cbafg", "abcd" => "cbad" # create dict for s # iterate thru order and append it to new string if it exists in dict # append left over characters from dict # Time: O(s+o) # Space: O(s) sDict = defaultdict(int) for c in s: sDict[c] += 1 # print(sDict) ans = "" for c in order: if c in sDict: for count in range(sDict[c]): ans += c sDict[c] = 0 # print(ans) for key,value in sDict.items(): if value != 0: for count in range(value): ans += key return ans
custom-sort-string
[Python3] Time: O(s+o) & Space: O(s)
jae2021
0
67
custom sort string
791
0.693
Medium
12,877
https://leetcode.com/problems/custom-sort-string/discuss/1257901/Python3-Straight-Forward-Method-easy-to-understand
class Solution: def customSortString(self, order: str, strs: str) -> str: res = [''] * len(strs) not_appear = -1 for s in strs: if s in order: res[order.index(s)] += s else: res[not_appear] = s not_appear -= 1 return ''.join(res)
custom-sort-string
Python3 Straight Forward Method, easy to understand
georgeqz
0
89
custom sort string
791
0.693
Medium
12,878
https://leetcode.com/problems/custom-sort-string/discuss/1087673/Python-One-Liner-Sort-and-Lambda
class Solution: def customSortString(self, S: str, T: str) -> str: return ''.join(sorted(T,key=lambda k:[S.index(c) if c in S else len(S) for c in k]))
custom-sort-string
Python One Liner - Sort & Lambda
ashishpawar517
0
48
custom sort string
791
0.693
Medium
12,879
https://leetcode.com/problems/custom-sort-string/discuss/930194/Python3-custom-sorting
class Solution: def customSortString(self, S: str, T: str) -> str: mp = {c: i for i, c in enumerate(S)} return "".join(sorted(T, key=lambda x: mp.get(x, 26)))
custom-sort-string
[Python3] custom sorting
ye15
0
62
custom sort string
791
0.693
Medium
12,880
https://leetcode.com/problems/custom-sort-string/discuss/930194/Python3-custom-sorting
class Solution: def customSortString(self, order: str, str: str) -> str: freq = {} for c in str: freq[c] = 1 + freq.get(c, 0) ans = [] for c in order: if c in freq: ans.append(c * freq.pop(c)) return "".join(ans) + "".join(k*v for k, v in freq.items())
custom-sort-string
[Python3] custom sorting
ye15
0
62
custom sort string
791
0.693
Medium
12,881
https://leetcode.com/problems/custom-sort-string/discuss/594065/Python-Super-Easy-Runtime-24ms-Complexity-O(n)
class Solution: def customSortString(self, S: str, T: str) -> str: m=len(S) n=len(T) sl=S.split() l=[""]*n left=[] d={} for i in range(n): d[T[i]]=0 for i in range(n): d[T[i]]+=1 print(d) for i in range(n): if T[i] in S: x=S.index(T[i]) l[x]=T[i]*d[T[i]] else: left.append(T[i]) str1=''.join(l) str2=''.join(left) return (str1+str2)
custom-sort-string
Python Super Easy Runtime-24ms Complexity- O(n)
Ayu-99
0
47
custom sort string
791
0.693
Medium
12,882
https://leetcode.com/problems/custom-sort-string/discuss/455460/Python-3-(one-line)
class Solution: def customSortString(self, S: str, T: str) -> str: return ''.join(sorted(T, key = lambda x: {c:i for i,c in enumerate(S)}.get(x,0))) - Junaid Mansuri - Chicago, IL
custom-sort-string
Python 3 (one line)
junaidmansuri
0
117
custom sort string
791
0.693
Medium
12,883
https://leetcode.com/problems/custom-sort-string/discuss/403513/Python-one-liner
class Solution: def customSortString(self, S: str, T: str) -> str: return "".join([x*(T.count(x)) for x in list(S)]+[x for x in T if x not in S])
custom-sort-string
Python one liner
saffi
0
112
custom sort string
791
0.693
Medium
12,884
https://leetcode.com/problems/custom-sort-string/discuss/315615/Python3-straightforward-and-concise-solution-beats-80
class Solution: def customSortString(self, S: str, T: str) -> str: m={} for i in S: m.setdefault(i,len(m)) tem=[] tem2=[] for i in T: if i in S: tem.append(i) else: tem2.append(i) tem=sorted(tem,key=lambda x:m[x]) return ''.join(tem)+''.join(tem2)
custom-sort-string
Python3 straightforward and concise solution beats 80%
jasperjoe
0
50
custom sort string
791
0.693
Medium
12,885
https://leetcode.com/problems/custom-sort-string/discuss/304618/Python-O(S%2BT)-solution
class Solution: def customSortString(self, S: str, T: str) -> str: letter_count = collections.Counter(T) other_letters = set(string.ascii_lowercase) - set(S) order = S + ''.join(other_letters) result = [] for letter in order: result.extend([letter * letter_count[letter]]) return ''.join(result)
custom-sort-string
Python O(S+T) solution
FooBarFooBarFooBar
0
126
custom sort string
791
0.693
Medium
12,886
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1289476/Easy-Approach-oror-Well-explained-oror-95-faster
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: def is_sub(word): index=-1 for ch in word: index=s.find(ch,index+1) if index==-1: return False return True c=0 for word in words: if is_sub(word): c+=1 return c
number-of-matching-subsequences
📌 Easy-Approach || Well-explained || 95% faster 🐍
abhi9Rai
27
1,200
number of matching subsequences
792
0.519
Medium
12,887
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2077197/Python3-oror-cache-w-explanation-oror-TM%3A-99.995
class Solution: # The plan is to iterate through the words and, for each word w, move # letter by letter of w though the string s if possible to determine # whether w is a subsequence of s. If so, we add to ans. # # We use a function and a cache because many of the words share letter # sequences. def numMatchingSubseq(self, s: str, words: list[str]) -> int: @lru_cache(None) def checkWord(word): start = 0 for ch in word: start = s.find(ch, start) + 1 # <-- find gives us the index of the if not start: return False # the next occurence of ch after # the index "start" return True return sum(checkWord(w) for w in words) # <-- we count all the words that # returned True.
number-of-matching-subsequences
Python3 || cache, w explanation || T/M: 99.9%/95%
warrenruud
4
134
number of matching subsequences
792
0.519
Medium
12,888
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1734042/Python-or-HashMap-or-Counter-or-faster-that-90
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: alpha = defaultdict(list) for w in words: alpha[w[0]].append(w) counter = 0 for c in s: old_bucket = alpha[c] alpha[c] = [] for w in old_bucket: next_word = w[1:] if next_word: alpha[next_word[0]].append(next_word) else: counter+=1 return counter
number-of-matching-subsequences
Python | HashMap | Counter | faster that 90%
holdenkold
4
340
number of matching subsequences
792
0.519
Medium
12,889
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1289470/Number-of-Matching-Subsequences-Python-Easy
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: def issub(x, y): it = iter(y) return all(c in it for c in x) c=0 wordsset = set(words) for i in wordsset: if issub(i,s): c = c+words.count(i) return c
number-of-matching-subsequences
Number of Matching Subsequences Python Easy
user8744WJ
4
342
number of matching subsequences
792
0.519
Medium
12,890
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1712999/Python-solution-Faster-than-99.32-of-python-Submissions
class Solution: def check(self,original,new,index): for ch in new: index= original.find(ch,index) if index==-1:return False index+=1 return True def numMatchingSubseq(self, s: str, words: List[str]) -> int: ans=0 for w in words:ans+=self.check(s,w,0) return ans
number-of-matching-subsequences
Python solution Faster than 99.32% of python Submissions
reaper_27
2
186
number of matching subsequences
792
0.519
Medium
12,891
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2310050/Python3-oror-Fast-97-3-Approaches-oror-simple-oror-Explained
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: """ # OPTIMAL Approach # create wordMap = {a: [a, acd, ace], b: [bb] ...} # on each iter it becomes {a:[], b: [b], c: [cd, ce] ...} and small # Time Complexity: O(n) + O(m) """ count = 0 wordMap = defaultdict(list) for w in words: wordMap[w[0]].append(w) for c in s: wordList = wordMap[c] wordMap[c] = [] for w in wordList: if len(w) == 1: count += 1 else: wordMap[w[1]].append(w[1:]) return count """ # Brute Force 2 (ACCEPTED) # Time Complexity: O(kn) + O(m) (Approx. O(kn)) # Where, k = num of unique subseq in words, m = len(words) # n = len(s) """ count = 0 seqInWords = {} for seq in words: seqInWords[seq] = 1 + seqInWords.get(seq, 0) for seq in seqInWords: n = len(seq) i = 0 for c in s: if i == n: break if c == seq[i]: i += 1 if i == n: count += seqInWords[seq] return count """ # brute force 1 """ count = 0 for seq in words: n = len(seq) i = 0 idx = -1 for x in range(len(seq)): c = seq[x] ind = idx+1 while ind < len(s): if c == s[ind]: idx = ind i += 1 break ind += 1 if i == n: count += 1 return count
number-of-matching-subsequences
Python3 || Fast 97% 3 Approaches || simple || Explained
Dewang_Patil
1
102
number of matching subsequences
792
0.519
Medium
12,892
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2308688/Python-Solution
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: result = len(words) for word in words: index = -1 for w in word: index = s.find(w, index + 1) if index == -1: result -= 1 break return result
number-of-matching-subsequences
Python Solution
hgalytoby
1
81
number of matching subsequences
792
0.519
Medium
12,893
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2307644/Python3-Preprocessing-Next-Characters
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: # radix R = 26 def char_to_int(ch: chr) -> int: return ord(ch) - ord('a') # preprocessng recent_ind = [len(s)] * R next_char = [()] * len(s) # next_char[i][j] gives next ind of char j after an index i for i in range(len(s) - 1, -1, -1): next_char[i] = tuple(recent_ind) # R operations recent_ind[char_to_int(s[i])] = i # processing res = 0 for word in words: # loop through words cur = recent_ind[char_to_int(word[0])] # start at first letter for i in range(1, len(word)): # find if next_char exists for all chars in word if not cur < len(s): break cur = next_char[cur][char_to_int(word[i])] # go to index of next char if cur < len(s): # if next char exists for all chars, add 1 to answer res += 1 return res
number-of-matching-subsequences
[Python3] Preprocessing Next Characters
jeffreyhu8
1
11
number of matching subsequences
792
0.519
Medium
12,894
https://leetcode.com/problems/number-of-matching-subsequences/discuss/2306885/Python-T%3A1001-ms-oror-Mem%3A17.4MB-oror-Commented-oror-Easy-to-understand-oror-HashMap
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: dict = {} # fill dictionary for all letters with empty list for c in 'abcdefghijklmnopqrstuvwxyz': dict[c] = [] # fill lists occurance-indices in super string for i, c in enumerate(s): if c in dict.keys(): dict[c].append(i) def firstOccuranceGreaterThanKey(arr, key): for j in arr: if j > key: return j return None # pick words one by one, if match, increment the result count resultCount = 0 for w in words: # try if the word is sub-sequence by comparing characters one by one moving right side last = -1 for i, c in enumerate(w): ind = firstOccuranceGreaterThanKey(dict[c], last) # if character found at index if ind is not None: # if we reached at end of word, increment count and break if i == len(w)-1: resultCount += 1 else: last = ind else: break return resultCount```
number-of-matching-subsequences
[Python] T:1001 ms || Mem:17.4MB || Commented || Easy to understand || HashMap
Buntynara
1
115
number of matching subsequences
792
0.519
Medium
12,895
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1428238/PythonPython3-Simple-readable-solution-using-find-method
class Solution: def mactchChars(self, s: str, word: str): # For each char in a word for char in word: # Find the current char in the string index = s.find(char) # If char not found return false if index == -1: return False else: # if char found, truncate portion of the string # trainling the char including itself s = s[index+1:] return True def numMatchingSubseq(self, s: str, words: List[str]) -> int: count = 0 # Match each word with string for word in words: if self.mactchChars(s, word): count = count + 1 return count
number-of-matching-subsequences
[Python/Python3] Simple readable solution using find method
ssshukla26
1
212
number of matching subsequences
792
0.519
Medium
12,896
https://leetcode.com/problems/number-of-matching-subsequences/discuss/1103585/PythonPython3-Number-of-Matching-Subsequences
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: cnt = 0 final_count = Counter(words) for word in set(words): it = iter(s) if all(letter in it for letter in word): cnt += final_count[word] return cnt
number-of-matching-subsequences
[Python/Python3] Number of Matching Subsequences
newborncoder
1
395
number of matching subsequences
792
0.519
Medium
12,897
https://leetcode.com/problems/number-of-matching-subsequences/discuss/932263/Python3-two-approaches
class Solution: def numMatchingSubseq(self, S: str, words: List[str]) -> int: mp = {} for i, w in enumerate(words): mp.setdefault(w[0], []).append((i, 0)) ans = 0 for c in S: for i, k in mp.pop(c, []): if k+1 == len(words[i]): ans += 1 else: mp.setdefault(words[i][k+1], []).append((i, k+1)) return ans
number-of-matching-subsequences
[Python3] two approaches
ye15
1
198
number of matching subsequences
792
0.519
Medium
12,898
https://leetcode.com/problems/number-of-matching-subsequences/discuss/932263/Python3-two-approaches
class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: loc = {} for i, ch in enumerate(s): loc.setdefault(ch, []).append(i) ans = 0 for word in words: x = 0 for ch in word: i = bisect_left(loc.get(ch, []), x) if i == len(loc.get(ch, [])): break x = loc[ch][i] + 1 else: ans += 1 return ans
number-of-matching-subsequences
[Python3] two approaches
ye15
1
198
number of matching subsequences
792
0.519
Medium
12,899