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/minimum-height-trees/discuss/923881/Python-Clean-and-Simple | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1: return [0]
graph = defaultdict(set)
for src, dst in edges:
graph[src].add(dst)
graph[dst].add(src)
leaves = [node for node in graph if len(graph[node]) == 1]
while n > 2:
n -= len(leaves)
temp = []
for leaf in leaves:
neighbor = graph[leaf].pop()
graph[neighbor].remove(leaf)
if len(graph[neighbor]) == 1:
temp.append(neighbor)
leaves = temp
return leaves | minimum-height-trees | [Python] Clean & Simple | yo1995 | 2 | 120 | minimum height trees | 310 | 0.385 | Medium | 5,400 |
https://leetcode.com/problems/minimum-height-trees/discuss/2132725/Python-topological-sort | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n <= 2:
return [i for i in range(n)]
adj = defaultdict(list)
edge_count = defaultdict(int)
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
edge_count[a] += 1
edge_count[b] += 1
q = deque(n for n in adj if len(adj[n]) == 1)
visited = set(q)
while len(visited) < n:
length = len(q)
for _ in range(length):
node = q.popleft()
for neighbor in adj[node]:
if neighbor not in visited:
edge_count[neighbor] -= 1
if edge_count[neighbor] == 1:
q.append(neighbor)
visited.add(neighbor)
return q | minimum-height-trees | Python, topological sort | blue_sky5 | 1 | 130 | minimum height trees | 310 | 0.385 | Medium | 5,401 |
https://leetcode.com/problems/minimum-height-trees/discuss/799117/Python3-two-BFSs | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def fn(x):
"""Return most distant node and trace."""
queue = deque([x])
trace = [-1] * n
trace[x] = -2
while queue:
u = queue.popleft()
for v in graph[u]:
if trace[v] == -1:
queue.append(v)
trace[v] = u
return u, trace
x, _ = fn(0)
x, trace = fn(x)
vals = []
while x >= 0:
vals.append(x)
x = trace[x]
k = len(vals)
return vals[(k-1)//2 : k//2+1] | minimum-height-trees | [Python3] two BFSs | ye15 | 1 | 195 | minimum height trees | 310 | 0.385 | Medium | 5,402 |
https://leetcode.com/problems/minimum-height-trees/discuss/799117/Python3-two-BFSs | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
graph = [set() for _ in range(n)]
for u, v in edges:
graph[u].add(v)
graph[v].add(u)
leaves = [x for x in range(n) if len(graph[x]) <= 1]
while n > 2:
n -= len(leaves)
newl = []
for u in leaves:
v = graph[u].pop()
graph[v].remove(u)
if len(graph[v]) == 1: newl.append(v)
leaves = newl
return leaves | minimum-height-trees | [Python3] two BFSs | ye15 | 1 | 195 | minimum height trees | 310 | 0.385 | Medium | 5,403 |
https://leetcode.com/problems/minimum-height-trees/discuss/2816738/My-DFS-solution-(backtracking) | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1: return [0]
adj = defaultdict(list)
for i, j in edges:
adj[i].append(j)
adj[j].append(i)
def backtracking(node, parenet, path, longestPath):
if len(adj[node]) == 1 and adj[node][0] == parenet and len(path) > len(longestPath):
return path.copy()
for child in adj[node]:
if child != parenet:
path.append(child)
longestPath = backtracking(child, node, path, longestPath)
path.pop()
return longestPath
node = backtracking(0, None, [0], [])[-1]
path = backtracking(node, None, [node], [])
return [path[(L := len(path)) // 2]] + ([path[L // 2 - 1]] if L % 2 == 0 else []) | minimum-height-trees | My DFS solution (backtracking) | toshiwu006 | 0 | 4 | minimum height trees | 310 | 0.385 | Medium | 5,404 |
https://leetcode.com/problems/minimum-height-trees/discuss/2769386/Naive-Solution-and-Efficient-Solution-Explained | class Solution:
# O(n^2) solution using dfs and treating all nodes as roots for once
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1: return [0]
graph = defaultdict(list)
nodes = set()
for a, b in edges:
nodes.add(a)
nodes.add(b)
graph[a].append(b)
graph[b].append(a)
dist = defaultdict(int)
def dfs(node, parent, curr, visited):
dist[parent] = max(dist[parent], curr)
for nei in graph[node]:
if nei not in visited:
visited.add(nei)
dfs(nei, parent, curr + 1, visited)
visited.discard(nei)
for node in nodes:
dfs(node, node, 0, {node})
mini = min(dist.values())
res = set()
for k, v in dist.items():
if v == mini:
res.add(k)
return res | minimum-height-trees | Naive Solution and Efficient Solution Explained | shiv-codes | 0 | 11 | minimum height trees | 310 | 0.385 | Medium | 5,405 |
https://leetcode.com/problems/minimum-height-trees/discuss/2769386/Naive-Solution-and-Efficient-Solution-Explained | class Solution:
# Fast Efficient solution using topological sorting
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
graph = defaultdict(list)
indegree = defaultdict(int)
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
indegree[a] += 1
indegree[b] += 1
q = deque()
res = []
for node in graph:
if indegree[node] == 1: q.append(node); indegree[node] -= 1
visited = set()
while q:
res.clear()
for i in range(len(q)):
node = q.popleft()
res.append(node)
for nei in graph[node]:
indegree[nei] -= 1
if indegree[nei] == 1:
q.append(nei)
return res if res else [0] | minimum-height-trees | Naive Solution and Efficient Solution Explained | shiv-codes | 0 | 11 | minimum height trees | 310 | 0.385 | Medium | 5,406 |
https://leetcode.com/problems/minimum-height-trees/discuss/2730030/Multi-source-BFS-similar-to-Rotting-Oranges-problem | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1:
return [0]
adjMap = {i:[] for i in range(n)}
indegree = {i:0 for i in range(n)}
for source1,source2 in edges:
adjMap[source1].append(source2)
adjMap[source2].append(source1)
indegree[source1] += 1
indegree[source2] += 1
queue = collections.deque()
for i in range(n):
if indegree[i] == 1:
queue.append(i)
remainNodes = n
while queue and remainNodes>2:
for i in range(len(queue)):
removed = queue.popleft()
indegree[removed] -= 1
remainNodes -= 1
for child in adjMap[removed]:
indegree[child] -= 1
if indegree[child] == 1:
queue.append(child)
return list(queue) | minimum-height-trees | Multi-source BFS similar to Rotting Oranges problem | ngnhatnam188 | 0 | 16 | minimum height trees | 310 | 0.385 | Medium | 5,407 |
https://leetcode.com/problems/minimum-height-trees/discuss/2506370/Python-BFS-Queue-80-faster | class Solution:
def findMinHeightTrees(self, total_node: int, edges: List[List[int]]) -> List[int]:
graph = defaultdict(list)
for u,v in edges:
graph[u].append(v)
graph[v].append(u)
queue = deque()
degree = {}
for node, val in graph.items():
if len(val) == 1:
queue.append(node)
else:
degree[node] = len(val)
def bfs(total_node, graph,queue):
while total_node>2:
total_node -= len(queue)
for i in range(len(queue)):
v = queue.popleft()
for child in graph[v]:
if child in degree:
degree[child]-=1
if degree[child] == 1:
queue.append(child)
return [queue.popleft() for i in range(len(queue))] if len(queue) else [i for i in range(total_node)]
return bfs(total_node, graph, queue) | minimum-height-trees | Python BFS Queue 80% faster | Abhi_009 | 0 | 173 | minimum height trees | 310 | 0.385 | Medium | 5,408 |
https://leetcode.com/problems/minimum-height-trees/discuss/1392181/Easy-to-read-solution | class Solution:
def make_graph(self, n: int, edges: List[List[int]]) -> Dict:
graph = {k: set() for k in range(n)}
for edge in edges:
graph[edge[0]].add(edge[1])
graph[edge[1]].add(edge[0])
return graph
def make_leaves(self, graph: Dict) -> Set:
leaves = set()
for key, val in graph.items():
if len(val) == 1:
leaves.add(key)
return leaves
def trim_nodes(self, graph: Dict, nodes: Set) -> None:
# Remove nodes from graph
for node in nodes:
node = graph.pop(node, None)
# Remove nodes connection in graph
for key, val in graph.items():
graph[key] = val - nodes
return
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
ret = [0] # default return value
if len(edges):
# make graph
graph = self.make_graph(n, edges)
# Loop till no more than 2 nodes are left
while len(graph) > 2:
# Make leaves
leaves = self.make_leaves(graph)
# Trim leaves
self.trim_nodes(graph, leaves)
# Return remaining nodes
ret = [k for k in graph.keys()]
return ret | minimum-height-trees | Easy to read solution | ssshukla26 | 0 | 105 | minimum height trees | 310 | 0.385 | Medium | 5,409 |
https://leetcode.com/problems/minimum-height-trees/discuss/1304406/Python3-DFS-with-memorization | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
dicts = {}
for source, target in edges:
if source not in dicts:
dicts[source] = {target}
else:
dicts[source].add(target)
if target not in dicts:
dicts[target] = {source}
else:
dicts[target].add(source)
mini_height = sys.maxsize
res = []
@lru_cache(None)
def search(prev, current):
temp_res = 1
if prev == None:
if current in dicts:
for element in dicts[current]:
temp_res = max(temp_res, search(current, element) + 1)
else:
if current in dicts:
for element in dicts[current]:
if element != prev:
temp_res = max(temp_res, search(current, element) + 1)
return temp_res
for i in range(n):
temp_res = search(None, i)
if temp_res < mini_height:
mini_height = temp_res
res = [i]
elif temp_res == mini_height:
res.append(i)
return res | minimum-height-trees | Python3 DFS with memorization | xxHRxx | 0 | 154 | minimum height trees | 310 | 0.385 | Medium | 5,410 |
https://leetcode.com/problems/minimum-height-trees/discuss/1258380/Python-Solution-based-on-Topological | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n<2:
return range(n)
graph=defaultdict(set)
indegree=[0]*n
for u,v in edges:
graph[u].add(v)
graph[v].add(u)
indegree[u]+=1
indegree[v]+=1
queue=[]
for i in range(n):
if indegree[i]==1:
queue.append(i)
count=n
while count>2:
new_queue=[]
for current in queue:
for neighbour in graph[current]:
indegree[neighbour]-=1
graph[neighbour].remove(current)
if indegree[neighbour]==1:
new_queue.append(neighbour)
count-=1
queue=new_queue
return queue | minimum-height-trees | Python Solution based on Topological | jaipoo | 0 | 223 | minimum height trees | 310 | 0.385 | Medium | 5,411 |
https://leetcode.com/problems/burst-balloons/discuss/1477014/Python3-or-Top-down-Approach | class Solution(object):
def maxCoins(self, nums):
n=len(nums)
nums.insert(n,1)
nums.insert(0,1)
self.dp={}
return self.dfs(1,nums,n)
def dfs(self,strt,nums,end):
ans=0
if strt>end:
return 0
if (strt,end) in self.dp:
return self.dp[(strt,end)]
for i in range(strt,end+1):
lmax=self.dfs(strt,nums,i-1)
rmax=self.dfs(i+1,nums,end)
curr_coins=nums[strt-1]*nums[i]*nums[end+1]+lmax+rmax
ans=max(ans,curr_coins)
self.dp[(strt,end)]=ans
return self.dp[(strt,end)] | burst-balloons | [Python3] | Top-down Approach | swapnilsingh421 | 2 | 269 | burst balloons | 312 | 0.568 | Hard | 5,412 |
https://leetcode.com/problems/burst-balloons/discuss/1191940/Python3-why-1-less-n-less-500 | class Solution:
def maxCoins(self, nums: List[int]) -> int:
nums = [1] + nums + [1] # augmented
n = len(nums)
dp = [[0]*n for _ in range(n)]
for i in reversed(range(n)):
for j in range(i, n):
for k in range(i+1, j):
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i]*nums[k]*nums[j])
return dp[0][-1] | burst-balloons | [Python3] why 1 <= n <= 500? | ye15 | 2 | 123 | burst balloons | 312 | 0.568 | Hard | 5,413 |
https://leetcode.com/problems/burst-balloons/discuss/1659820/Python3-3-liner-recursive-solution | class Solution:
def maxCoins(self, nums):
nums = [1] + nums + [1]
@cache
def solve(l,r):
return max((solve(l,k-1)+nums[l-1]*nums[k]*nums[r+1]+solve(k+1,r) for k in range(l,r+1)),default=0)
return solve(1,len(nums)-2) | burst-balloons | Python3 3-liner recursive solution | pknoe3lh | 1 | 142 | burst balloons | 312 | 0.568 | Hard | 5,414 |
https://leetcode.com/problems/burst-balloons/discuss/2669841/Python-DP-Tabulation-Easy | class Solution:
def maxCoins(self, nums: List[int]) -> int:
n=len(nums)
nums.append(1)
nums.insert(0,1)
dp=[[0]*(n+2) for i in range(n+2)]
for i in range(n,0,-1):
for j in range(1,n+1):
if i>j:
continue
ma=float('-inf')
for ind in range(i,j+1):
cost=nums[i-1]*nums[ind]*nums[j+1]+dp[i][ind-1]+dp[ind+1][j]
ma=max(ma,cost)
dp[i][j]= ma
return dp[1][n] | burst-balloons | Python DP Tabulation Easy | ayush-09 | 0 | 12 | burst balloons | 312 | 0.568 | Hard | 5,415 |
https://leetcode.com/problems/burst-balloons/discuss/2591655/Python-or-Bottom-Up-DP-or-Clear-Explanation | class Solution:
def maxCoins(self, nums: List[int]) -> int:
dp = [[0 for j in range(len(nums))] for i in range(len(nums))]
# fill the (0,0), (1,1) etc
for i in range(len(nums)):
dp[i][i] = nums[i]*(nums[i-1] if i-1>=0 else 1)*(nums[i+1] if i+1<len(nums) else 1)
for offset in range(1,len(nums)):
x = 0
while x+offset<len(nums):
y = x + offset
curr = 0
for j in range(x,y+1):
left = 0 if j-1<x else dp[x][j-1]
mid = (nums[x-1] if x-1>=0 else 1)*nums[j]*(nums[y+1] if y+1<len(nums) else 1)
right = 0 if j+1>y else dp[j+1][y]
dp[x][y] = max(dp[x][y],left + mid + right)
x+=1
return dp[0][-1] | burst-balloons | Python | Bottom Up DP | Clear Explanation | vishyarjun1991 | 0 | 84 | burst balloons | 312 | 0.568 | Hard | 5,416 |
https://leetcode.com/problems/burst-balloons/discuss/2345158/Dynamic-Programming-or-Python | class Solution:
def maxCoins(self, nums: List[int]) -> int:
n = len(nums)
points = [1] * (n + 2)
for i in range(1, n + 1):
points[i] = nums[i - 1]
dp = [[0] * (n + 2) for _ in range(n + 2)]
for i in range(n + 1, -1, -1):
for j in range(i + 1, n + 2):
for k in range(i + 1, j):
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + points[i] * points[k] * points[j])
return dp[0][n + 1] | burst-balloons | Dynamic Programming | Python | Kiyomi_ | 0 | 79 | burst balloons | 312 | 0.568 | Hard | 5,417 |
https://leetcode.com/problems/burst-balloons/discuss/1747409/NEED-HELP-About-Running-Time!!! | class Solution:
def maxCoins(self, nums: List[int]) -> int:
nums = [1] + nums + [1]
N = len(nums)
"""
Recursive relation
Base case i==j: 0
max(res, dp(i,k) + dp(k + 1, j) + nums[i-1] * nums[k] * nums[j]) for k in (i,j)
"""
# return dp(1, N-1)
dp = [[0] * N for _ in range(N)]
for i in range(N-2, -1, -1):
for j in range(i + 1, N):
for k in range(i, j):
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k+1][j] + nums[i-1] * nums[k] * nums[j])
# dp[i][j] = max(dp[i][k] + dp[k+1][j] + nums[i-1] * nums[k] * nums[j] for k in range(i,j))
return dp[1][N-1] | burst-balloons | 🔴 NEED HELP About Running Time!!! | atiq1589 | 0 | 38 | burst balloons | 312 | 0.568 | Hard | 5,418 |
https://leetcode.com/problems/burst-balloons/discuss/1379272/Python-Easy-Solution-!!! | class Solution:
def maxCoins(self, nums: List[int]) -> int:
n=len(nums)
dp=[[0 for i in range(n)] for j in range(n)]
for gap in range(n):
for row in range(n-gap):
col=row+gap
prev=1 if row==0 else nums[row-1]
next=1 if col==n-1 else nums[col+1]
best=-float('inf')
for k in range(row,col+1):
tmp=prev*next*nums[k]
if row!=k:tmp+=dp[row][k-1]
if col!=k:tmp+=dp[k+1][col]
if tmp>best:best=tmp
dp[row][col]=best
return dp[0][-1] | burst-balloons | Python Easy Solution !!! | reaper_27 | 0 | 165 | burst balloons | 312 | 0.568 | Hard | 5,419 |
https://leetcode.com/problems/burst-balloons/discuss/1416741/Python-DP-(memoized-bottom-up)-solution | class Solution:
def maxCoins(self, nums: List[int]) -> int:
nums = [1] + nums + [1]
size = len(nums)
t = [[-1 for p in range(0,size+1)]
for q in range(0,size+1)]
return self.solve(nums,1,size-1,t)
def solve(self,arr,i,j,t):
if i >= j:
return 0
if t[i][j] > 0:
return t[i][j]
ans = float('-inf')
for k in range(i,j):
if t[i][k] != -1:
left = t[i][k]
else:
left = self.solve(arr,i,k,t)
t[i][k] = left
if t[k+1][j] != -1:
right = t[k+1][j]
else:
right = self.solve(arr,k+1,j,t)
t[k+1][j] = right
temp = left + right + (arr[i-1]*arr[k]*arr[j])
ans = max(ans,temp)
t[i][j] = ans
return t[i][j] | burst-balloons | Python DP (memoized, bottom up) solution | Saura_v | -2 | 453 | burst balloons | 312 | 0.568 | Hard | 5,420 |
https://leetcode.com/problems/super-ugly-number/discuss/2828266/heapq-did-the-job | class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
hp=[1]
dc={1}
i=1
while(n):
mn=heapq.heappop(hp)
if(n==1):
return mn
for p in primes:
newno=mn*p
if(newno in dc):
continue
heapq.heappush(hp,newno)
dc.add(newno)
n-=1 | super-ugly-number | heapq did the job | droj | 5 | 40 | super ugly number | 313 | 0.458 | Medium | 5,421 |
https://leetcode.com/problems/super-ugly-number/discuss/788267/Python3-k-pointers | class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
ans = [1]
ptr = [0]*len(primes) #all pointing to 0th index
for _ in range(1, n):
ans.append(min(ans[ptr[i]]*p for i, p in enumerate(primes)))
for i, p in enumerate(primes):
if ans[ptr[i]] * p == ans[-1]: ptr[i] += 1
return ans[-1] | super-ugly-number | [Python3] k pointers | ye15 | 2 | 179 | super ugly number | 313 | 0.458 | Medium | 5,422 |
https://leetcode.com/problems/super-ugly-number/discuss/788267/Python3-k-pointers | class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
ans = [1]
hp = [(p, 0) for p in primes]
for _ in range(1, n):
ans.append(hp[0][0])
while ans[-1] == hp[0][0]:
val, i = heappop(hp)
val = val//(ans[i]) * ans[i+1]
heappush(hp, (val, i+1))
return ans[-1] | super-ugly-number | [Python3] k pointers | ye15 | 2 | 179 | super ugly number | 313 | 0.458 | Medium | 5,423 |
https://leetcode.com/problems/super-ugly-number/discuss/2818384/Python3-Heap | class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
h, cnt, last, seen = [1], 0, -1, set()
max_seen = -1
while cnt < n:
c = heappop(h)
cnt += 1
seen.add(c)
for p in primes:
if c * p not in seen and (len(h) <= n - cnt or c*p < max_seen):
heappush(h, c*p)
seen.add(c*p)
max_seen = max(max_seen, c*p)
last = c
return last | super-ugly-number | Python3 - Heap | godshiva | 0 | 7 | super ugly number | 313 | 0.458 | Medium | 5,424 |
https://leetcode.com/problems/super-ugly-number/discuss/2795540/Python-(Simple-Heap) | class Solution:
def nthSuperUglyNumber(self, n, primes):
ans = [1]
while n:
val = heappop(ans)
while ans and ans[0] == val:
heappop(ans)
for p in primes:
heappush(ans,p*val)
n -= 1
return val | super-ugly-number | Python (Simple Heap) | rnotappl | 0 | 4 | super ugly number | 313 | 0.458 | Medium | 5,425 |
https://leetcode.com/problems/super-ugly-number/discuss/2753210/easy-solution-(similar-to-nth-ugly-number) | class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
dp = [0]*(n+1)
dp[1] = 1
p_ = [1]*len(primes)
for i in range(2,n+1):
mini = float('inf')
for p in range(len(primes)):
mini = min(mini,primes[p]*dp[p_[p]])
dp[i] = mini
for j in range(len(primes)):
if dp[i] == primes[j]*dp[p_[j]]:
p_[j] += 1
return dp[n] | super-ugly-number | easy solution (similar to nth ugly number) | neeshumaini55 | 0 | 4 | super ugly number | 313 | 0.458 | Medium | 5,426 |
https://leetcode.com/problems/super-ugly-number/discuss/369835/Three-Short-Solutions-in-Python-3-(Bisect-Heap-DP) | class Solution:
def nthSuperUglyNumber(self, n: int, p: List[int]) -> int:
N, I, L = [1], [0]*len(p), len(p)
for _ in range(n-1):
N.append(min([N[I[i]]*p[i] for i in range(L)]))
for i in range(L): I[i] += N[I[i]]*p[i] == N[-1]
return N[-1]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | super-ugly-number | Three Short Solutions in Python 3 (Bisect, Heap, DP) | junaidmansuri | -1 | 448 | super ugly number | 313 | 0.458 | Medium | 5,427 |
https://leetcode.com/problems/super-ugly-number/discuss/1237418/Python3-simple-solution-using-min-heap | class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
ugly = [1]
seen = set()
x = []
heapq.heapify(x)
while len(ugly) != n:
for i in primes:
if ugly[-1]*i not in seen:
seen.add(ugly[-1]*i)
heapq.heappush(x,ugly[-1]*i)
ugly.append(heapq.heappop(x))
return ugly[-1] | super-ugly-number | Python3 simple solution using min-heap | EklavyaJoshi | -3 | 155 | super ugly number | 313 | 0.458 | Medium | 5,428 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/2320000/Python3.-oror-binSearch-6-lines-w-explanation-oror-TM%3A-9784 | class Solution: # Here's the plan:
# 1) Make arr, a sorted copy of the list nums.
# 2) iterate through nums. For each element num in nums:
# 2a) use a binary search to determine the count of elements
# in the arr that are less than num.
# 2b) append that count to the answer list
# 2c) delete num from arr
# 3) return the ans list
#
# For example, suppose nums = [5,2,6,1] Then arr = [1,2,5,6].
# num = 5 => binsearch: arr = [1,2,/\5,6], i = 2 => ans = [2,_,_,_], del 5
# num = 2 => binsearch: arr = [1,/\2,6], i = 1 => ans = [2,1,_,_], del 2
# num = 6 => binsearch: arr = [1,/\6], i = 1 => ans = [2,1,1,_], del 6
# num = 1 => binsearch: arr = [/\1], i = 0 => ans = [2,1,1,0], del 1
def countSmaller(self, nums: List[int]) -> List[int]:
arr, ans = sorted(nums), [] # <-- 1)
for num in nums:
i = bisect_left(arr,num) # <-- 2a)
ans.append(i) # <-- 2b)
del arr[i] # <-- 2c)
return ans # <-- 3) | count-of-smaller-numbers-after-self | Python3. || binSearch 6 lines, w/ explanation || T/M: 97%/84% | warrenruud | 27 | 3,000 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,429 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/1045763/Merge-sort-solution | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
counts = [0] * len(nums) # to save counts
indexed_nums = [(nums[key_index], key_index) for key_index in range(len(nums))] # change the nums into (number, index) pairs
desc_nums, counts = self.mergeWithCount(indexed_nums, counts) # the helper function returns the descendingly sorted indexed_nums and the counts
return counts
def mergeWithCount(self, nums, counts):
if len(nums) == 1:
return nums, counts
cur_stack = []
left, counts = self.mergeWithCount(nums[: len(nums) // 2], counts)
right, counts = self.mergeWithCount(nums[len(nums) // 2 :], counts)
while left and right:
if left[0] > right[0]:
counts[left[0][1]] += len(right) # left[0] gives a (number, index) pair as we defined at the beginning, and left[0][1] returns the original index of the number.
cur_stack.append(left.pop(0))
else:
cur_stack.append(right.pop(0))
if left:
cur_stack.extend(left)
else:
cur_stack.extend(right)
return cur_stack, counts | count-of-smaller-numbers-after-self | Merge sort solution | greatidea | 18 | 1,500 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,430 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/1178309/Python3-Fenwick-tree | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
ans = [0]*len(nums)
nums = list(enumerate(nums))
def fn(nums, aux, lo, hi):
"""Sort nums via merge sort and populate ans."""
if lo+1 >= hi: return
mid = lo + hi >> 1
fn(aux, nums, lo, mid)
fn(aux, nums, mid, hi)
i, j = lo, mid
for k in range(lo, hi):
if j >= hi or i < mid and aux[i][1] <= aux[j][1]:
nums[k] = aux[i]
ans[nums[k][0]] += j - mid
i += 1
else:
nums[k] = aux[j]
j += 1
fn(nums, nums.copy(), 0, len(nums))
return ans | count-of-smaller-numbers-after-self | [Python3] Fenwick tree | ye15 | 4 | 244 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,431 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/2321807/python3-simple-solution-using-bisect | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
ans = []
deque = collections.deque()
for num in nums[::-1]:
index = bisect.bisect_left(deque,num)
ans.append(index)
deque.insert(index,num)
return ans[::-1] | count-of-smaller-numbers-after-self | python3, simple solution, using bisect | pjy953 | 1 | 40 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,432 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/2321289/Python-solution-with-MergeSort-and-Fenwick-tree | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
def merge(nums,start,mid,end,res):
left = start
right = mid + 1
result = []
inversion_count = 0
while left <= mid and right <= end:
if nums[left][1] <= nums[right][1]:
res[nums[left][0]] += inversion_count
result.append(nums[left])
left += 1
else:
inversion_count+=1
result.append(nums[right])
right += 1
while left <= mid:
res[nums[left][0]] += inversion_count
result.append(nums[left])
left += 1
while right <= end:
result.append(nums[right])
right += 1
j = 0
for i in range(start,end+1):
nums[i] = result[j]
j+=1
def mergesort(nums,start,end,res):
if start<end:
mid = (start + end)//2
mergesort(nums,start,mid,res)
mergesort(nums,mid+1,end,res)
merge(nums,start,mid,end,res)
n = len(nums)
nums = list(enumerate(nums))
res = [0]*n
mergesort(nums,0,n-1,res)
return res | count-of-smaller-numbers-after-self | Python solution with MergeSort and Fenwick tree | manojkumarmanusai | 1 | 119 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,433 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/2320775/Python-Simple-Python-Solution-Using-Binary-Search-(-Bisect_Left-) | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
array = sorted(nums)
result = []
for num in nums:
return_value = bisect.bisect_left(array, num)
del array[return_value]
if return_value == -1:
result.append(0)
else:
result.append(return_value)
return result | count-of-smaller-numbers-after-self | [ Python ] ✅✅ Simple Python Solution Using Binary Search ( Bisect_Left ) 🔥🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 1 | 117 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,434 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/1389517/Bisect-the-tail | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
len_nums = len(nums)
counts = [0] * len_nums
tail = [nums[len_nums - 1]]
for i in range(len_nums - 2, -1, -1):
idx = bisect_left(tail, nums[i])
counts[i] = idx
tail.insert(idx, nums[i])
return counts | count-of-smaller-numbers-after-self | Bisect the tail | EvgenySH | 1 | 121 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,435 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/2050139/Python-or-Binary-Search | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
l=len(nums)
ans=[0]*l
arr=[nums[-1]]
i=l-2
for n in nums[-2::-1]:#Starting from 2nd last el
lo,hi=0,len(arr)-1
while lo<=hi:
mid=lo+(hi-lo)//2
if arr[mid]>n:
hi=mid-1
else:
lo=mid+1
arr.insert(lo,n)
j=lo-1
while j>=0 and arr[j]==n:#In case num is duplicate like [-1,-1]
j-=1
ans[i]=j+1
i-=1
return ans | count-of-smaller-numbers-after-self | Python | Binary Search | heckt27 | 0 | 134 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,436 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/1964059/Python-easy-to-read-and-understand-or-divide-and-conquer | class Solution:
def merge(self, left, right):
#print(left, right)
m, n = len(left), len(right)
cnt = 0
i, j = 0, 0
sorted_arr = []
while i < m and j < n:
if left[i][1] > right[j][1]:
sorted_arr.append(right[j])
j += 1
cnt += 1
else:
sorted_arr.append(left[i])
self.ans[left[i][0]] += cnt
i += 1
while i < m:
sorted_arr.append(left[i])
self.ans[left[i][0]] += cnt
i += 1
while j < n:
sorted_arr.append(right[j])
j += 1
return sorted_arr
def split(self, nums):
if len(nums) == 1:
return nums
mid = len(nums) // 2
left, right = self.split(nums[:mid]), self.split(nums[mid:])
sorted_nums = self.merge(left, right)
return sorted_nums
def countSmaller(self, nums: List[int]) -> List[int]:
n = len(nums)
self.ans = [0 for _ in range(n)]
arr = []
for i, num in enumerate(nums):
arr.append((i, num))
sorted_nums = self.split(arr)
return self.ans | count-of-smaller-numbers-after-self | Python easy to read and understand | divide and conquer | sanial2001 | 0 | 306 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,437 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/1383367/Python3-BIT-and-padding-beat-%2B96 | class Solution:
def countSmaller(self, A: List[int]) -> List[int]:
n = len(A)
_min = min(A) - 1 # padding value
_max = max(A) - _min
result = [0] * n
bit = [0] * (_max+1)
def count(a):
c = 0;
while a > 0:
c += bit[a]
a -= a & -a
return c
def insert(a):
while a <= _max:
bit[a] += 1
a += a & -a
for i, a in enumerate(reversed(A)):
a = a - _min
result[n-i-1] = count(a-1)
insert(a)
return result | count-of-smaller-numbers-after-self | [Python3] BIT and padding, beat +96% | hieuvpm | 0 | 120 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,438 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/1299385/Python3-Simple-7-line-binary-search-solution | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
res = []
seq = sorted(nums)
for num in nums:
pos = bisect_left(seq, num)
res.append(pos)
seq.pop(pos)
return res | count-of-smaller-numbers-after-self | [Python3] Simple 7-line binary search solution | alsvia | 0 | 109 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,439 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/914190/Python-Intuitive-O(NlogN)-Solution-using-Merge-sort-divide-and-conquer-strategy | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
if not nums:
return []
st = 0
end = len(nums) - 1
res = [0] * len(nums)
self.merge_process(list(enumerate(nums)), st, end, res)
return res
def merge_process(self, nums, st, end, res):
if st == end:
return
mid = (st + end) // 2
self.merge_process(nums, st, mid, res)
self.merge_process(nums, mid + 1, end, res)
self.merge(nums, st, end, res)
def merge(self, nums, st, end, res):
mid = (st + end)//2
l_pt = st
r_pt = mid + 1
temp = []
while(l_pt <= mid and r_pt <= end):
if nums[r_pt][0] < nums[l_pt][0]:
temp.append(nums[r_pt])
r_pt += 1
else:
temp.append(nums[l_pt])
res[nums[l_pt][1]] += r_pt - (mid + 1)
l_pt += 1
while(l_pt <= mid):
temp.append(nums[l_pt])
res[nums[l_pt][1]] += end - mid
l_pt += 1
while(r_pt <= end):
temp.append(nums[r_pt])
r_pt += 1
for i in range(st, end + 1):
nums[i] = temp[i - st] | count-of-smaller-numbers-after-self | [Python] Intuitive O(NlogN) Solution using Merge sort divide and conquer strategy | vasu6 | 0 | 197 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,440 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/914180/Python-Intuitive-O(NlogN)-Solution-using-Merge-sort-divide-and-conquer-strategy | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
if not nums:
return []
st = 0
end = len(nums) - 1
res = [0] * len(nums)
self.merge_process(list(enumerate(nums)), st, end, res)
return res
def merge_process(self, nums, st, end, res):
if st == end:
return
mid = (st + end) // 2
self.merge_process(nums, st, mid, res)
self.merge_process(nums, mid + 1, end, res)
self.merge(nums, st, end, res)
def merge(self, nums, st, end, res):
mid = (st + end)//2
l_pt = st
r_pt = mid + 1
temp = []
while(l_pt <= mid and r_pt <= end):
if nums[r_pt][1] < nums[l_pt][1]:
temp.append(nums[r_pt])
r_pt += 1
else:
temp.append(nums[l_pt])
res[nums[l_pt][0]] += r_pt - (mid + 1)
l_pt += 1
while(l_pt <= mid):
temp.append(nums[l_pt])
res[nums[l_pt][0]] += end - mid
l_pt += 1
while(r_pt <= end):
temp.append(nums[r_pt])
r_pt += 1
for i in range(st, end + 1):
nums[i] = temp[i - st] | count-of-smaller-numbers-after-self | [Python] Intuitive O(NlogN) Solution using Merge sort divide and conquer strategy | vasu6 | 0 | 92 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,441 |
https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/2323721/Beat-95-Python3-solutions | class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
l = len(nums)
arr, ans = sorted(nums), [0] * l
if l > 99:
for i in range(l-1):
ans[i] = bisect_left(arr, nums[i]) # binary search index
del arr[ans[i]]
else:
for i in range(l):
ans[i] = arr.index(nums[i]) # linear search index
del arr[ans[i]]
return ans | count-of-smaller-numbers-after-self | Beat 95% Python3 solutions | AgentIvan | -1 | 30 | count of smaller numbers after self | 315 | 0.428 | Hard | 5,442 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1687144/Python-3-Simple-solution-using-a-stack-and-greedy-approach-(32ms-14.4MB) | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
stack = []
for idx, character in enumerate(s):
if not stack:
stack.append(character)
elif character in stack:
continue
else:
while stack and (character < stack[-1]):
if stack[-1] in s[idx + 1:]:
_ = stack.pop()
else:
break
stack.append(character)
return ''.join(stack) | remove-duplicate-letters | [Python 3] Simple solution using a stack and greedy approach (32ms, 14.4MB) | seankala | 5 | 498 | remove duplicate letters | 316 | 0.446 | Medium | 5,443 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/2050746/Python3-Runtime%3A-51ms-54.58-Memory%3A-13.9mb-82.79 | class Solution:
def removeDuplicateLetters(self, string: str) -> str:
lastIndex = [0] * 26
self.getLastIndexOfChar(string, lastIndex)
stack = self.maintainLexoOrder(string, lastIndex)
return ''.join(chr(ord('a') + char) for char in stack)
def getLastIndexOfChar(self, string, lastIndex):
for idx, char in enumerate(string):
lastIndex[ord(char)-ord('a')] = idx
def maintainLexoOrder(self, string, lastIndex):
seen = [False] * 26
stack = []
for idx, char in enumerate(string):
currentCharVal = (ord(char) - ord('a'))
if seen[currentCharVal]:
continue
while (len(stack) > 0 and
stack[len(stack)-1] > currentCharVal and
idx < lastIndex[stack[len(stack)-1]]):
seen[stack.pop()] = False
stack.append(currentCharVal)
seen[currentCharVal] = True
return stack | remove-duplicate-letters | Python3 Runtime: 51ms 54.58% Memory: 13.9mb 82.79% | arshergon | 1 | 104 | remove duplicate letters | 316 | 0.446 | Medium | 5,444 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1860601/Python-Solution | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
n, lastIdx, insideStack, stack = len(s), [0] * 26, [0] * 26, [] # insideStack: it will show the current status of the stack, which character is present inside the stack at any particular instance of the loop.
getIdx = lambda c: ord(c) - ord('a') # it will return the index
for i in range(n): lastIdx[getIdx(s[i])] = i # store the last index of the each character
for i in range(n):
currChar = s[i] # curr Char acter
if insideStack[getIdx(currChar)]: continue # if current character inside our stack, skkiiip it..
while stack and stack[-1] > currChar and lastIdx[getIdx(stack[-1])] > i: # we got a smaller character, pop the greater ones out only if its instance is present at the right part of the array from i
insideStack[getIdx(stack.pop())] = 0 # we popped So, its no more inside stack, mark it in insideStack that its no more inside stack
stack.append(currChar) # add the currChar
insideStack[getIdx(currChar)] = 1 # mark that currChar is inside our stack
return ''.join(stack) # return the stack as a string | remove-duplicate-letters | ✅ Python Solution | dhananjay79 | 1 | 289 | remove duplicate letters | 316 | 0.446 | Medium | 5,445 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1860601/Python-Solution | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
n, stack, dic = len(s), [], {}
for i in range(n): dic[s[i]] = [0,i]
for i in range(n):
currChar = s[i]
if dic[currChar][0]: continue
while stack and stack[-1] > currChar and dic[stack[-1]][1] > i: dic[stack.pop()][0] = 0
stack.append(currChar)
dic[currChar][0] = 1
return ''.join(stack) | remove-duplicate-letters | ✅ Python Solution | dhananjay79 | 1 | 289 | remove duplicate letters | 316 | 0.446 | Medium | 5,446 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1860300/93-Faster-oror-Python-Simple-Python-Solution-Using-Stack-and-Iterative-Approach | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
LastIndex = {}
for i in range(len(s)):
LastIndex[s[i]] = i
stack = []
AlreadySeen = set()
for i in range(len(s)):
if s[i] in AlreadySeen:
continue
else:
while stack and stack[-1] > s[i] and LastIndex[stack[-1]] > i:
AlreadySeen.remove(stack[-1])
stack.pop()
stack.append(s[i])
AlreadySeen.add(s[i])
return ''.join(stack) | remove-duplicate-letters | 93% Faster || [ Python ] ✔✔ Simple Python Solution Using Stack and Iterative Approach 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 1 | 272 | remove duplicate letters | 316 | 0.446 | Medium | 5,447 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/890287/my-python-Solution-using-counter-dict | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
myC=collections.Counter(s)
res=[]
seen=set()
for c in s:
while res and c<res[-1] and myC[res[-1]]>0 and c not in seen:
x=res.pop()
seen.discard(x)
if c not in seen:
res.append(c)
seen.add(c)
myC[c]-=1
return ''.join(res) | remove-duplicate-letters | my python 🐍 Solution using counter dict | InjySarhan | 1 | 446 | remove duplicate letters | 316 | 0.446 | Medium | 5,448 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/2821524/Python-oror-STACK-SOLUTION-oror-EASY | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
d = defaultdict(lambda:0)
for i in s : d[i]+=1
st,i = [] , 0
while i < len(s):
if st == []:
st.append([s[i],ord(s[i])])
d[s[i]] -= 1
elif [s[i],ord(s[i])] in st:
d[s[i]] -= 1
else:
if st!=[] and st[-1][1] > ord(s[i]) and d[st[-1][0]] !=0:
while st!=[] and st[-1][1] > ord(s[i]) and d[st[-1][0]] !=0:
st.pop()
st.append([s[i],ord(s[i])])
d[s[i]] -= 1
elif st!=[] and st[-1][1] < ord(s[i]):
st.append([s[i],ord(s[i])])
d[s[i]] -= 1
else:
st.append([s[i],ord(s[i])])
d[s[i]] -= 1
i+=1
op = ""
for i in st:
op += i[0]
return op; | remove-duplicate-letters | Python || STACK SOLUTION || EASY | cheems_ds_side | 0 | 5 | remove duplicate letters | 316 | 0.446 | Medium | 5,449 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/2692696/Greedy-Approach-or-O(n)-time-or-O(n)-space-due-26-alphabets | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
charMaxIndex = {}
for i in range(len(s)):
charMaxIndex[s[i]] = i
visited = set()
stack = []
for i in range(len(s)):
if s[i] in visited:
continue
while stack and stack[-1] > s[i] and charMaxIndex[stack[-1]] > i:
visited.remove(stack[-1])
stack.pop()
visited.add(s[i])
stack.append(s[i])
return ''.join(stack) | remove-duplicate-letters | Greedy Approach | O(n) time | O(n) space due 26 alphabets | wakadoodle | 0 | 7 | remove duplicate letters | 316 | 0.446 | Medium | 5,450 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/2666355/Python-easy-Stack-O(n) | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
count = Counter(s)
stack = deque()
result = set()
for i in s:
if i in result:
count[i] -= 1
continue
while(stack and stack[-1] > i and count[stack[-1]] > 1):
count[stack[-1]] -= 1
result.remove(stack[-1])
stack.pop()
stack.append(i)
result.add(i)
return "".join(stack) | remove-duplicate-letters | Python easy Stack O(n) | anu1rag | 0 | 7 | remove duplicate letters | 316 | 0.446 | Medium | 5,451 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/2663022/Remove-Duplicate-Letters-oror-Python3-oror-Stack | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
d={}
for i in range(len(s)):
d[s[i]]=i
stack=[]
st=set()
for i in range(len(s)):
curr=s[i]
if curr in st:
continue
if len(stack)!=0 and stack[-1]<curr:
st.add(curr)
stack.append(curr)
else:
while len(stack)!=0 and stack[-1]>curr and d[stack[-1]]>i:
a=stack.pop()
st.remove(a)
if curr not in st:
st.add(curr)
stack.append(curr)
return ''.join(stack) | remove-duplicate-letters | Remove Duplicate Letters || Python3 || Stack | shagun_pandey | 0 | 4 | remove duplicate letters | 316 | 0.446 | Medium | 5,452 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/2557646/Simple-python-solution | class Solution:
def smallestSubsequence(self, s: str) -> str:
new = {}
for i in range(len(s)):
new[s[i]]=i
stak,seen=[],set()
for i in range(len(s)):
if s[i] not in seen:
while stak and new[stak[-1]]>i and stak[-1]>s[i]:
seen.remove(stak[-1])
stak.pop()
stak.append(s[i])
seen.add(s[i])
return "".join(stak) | remove-duplicate-letters | Simple python solution | SaiManoj1234 | 0 | 40 | remove duplicate letters | 316 | 0.446 | Medium | 5,453 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/2271058/Python-Stack-Solution | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
max_index = {}
for i in range(len(s)):
max_index[s[i]] = i
seen = set()
stack = []
for i in range(len(s)):
if s[i] in seen:continue
while stack and stack[-1]>s[i] and max_index[stack[-1]]>(i):
seen.remove(stack[-1])
stack.pop()
stack.append(s[i])
seen.add(s[i])
return ''.join(stack) | remove-duplicate-letters | Python Stack Solution | Abhi_009 | 0 | 51 | remove duplicate letters | 316 | 0.446 | Medium | 5,454 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1892465/Sliding-window-in-Python-no-stack-employed. | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
lower_bound, upper_bound = -1, len(s) - 1
alphabet, result = set(s), {}
while alphabet:
seen, indices = set(), {}
for i in range(upper_bound, lower_bound, -1):
seen.add(char := s[i])
if char not in result and seen >= alphabet:
indices[char] = i
char, lower_bound = min(indices.items())
result[char] = None
alphabet.remove(char)
return r''.join(result) | remove-duplicate-letters | Sliding window in Python; no stack employed. | kmierzej | 0 | 52 | remove duplicate letters | 316 | 0.446 | Medium | 5,455 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1860666/python-stack-fast-easy-code | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
s = list(s)
last_index = {}
for i in range(len(s)):
last_index[s[i]] = i
stack =[]
visited = [False]*26
for i in range(0,len(s)):
if not visited[(ord(s[i])-97)]:
while len(stack)!=0 and ord(stack[-1])>=ord(s[i]):
if last_index[stack[-1]]>=i:
visited[ord(stack[-1])-97] = False
stack.pop()
else:
break
stack.append(s[i])
visited[(ord(s[i])-97)] = True
return ''.join(stack) | remove-duplicate-letters | python stack fast easy code | Brillianttyagi | 0 | 63 | remove duplicate letters | 316 | 0.446 | Medium | 5,456 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1860336/python-oror-Simple-Solution-with-explanation | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
counter = Counter(s)
not_used = {c: True for c in s}
ans = ""
for c in s:
counter[c] -= 1
if not_used[c]:
while ans and ord(ans[-1]) >= ord(c) and counter[ans[-1]]>0:
not_used[ans[-1]] = True
ans = ans[:-1]
ans += c
not_used[c] = False
return ans | remove-duplicate-letters | python || Simple Solution with explanation | zouhair11elhadi | 0 | 53 | remove duplicate letters | 316 | 0.446 | Medium | 5,457 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1859915/Python-or-TC-O(N)SC-O(N)-or-Easy-to-understand-with-comments-or | class Solution(object):
def removeDuplicateLetters(self, s):
count = Counter(s)
stack = []
for char in s:
# this condition is for removing duplicates
if char in stack:
count[char] -= 1
continue
# this condition is for maintain Lexicographical order
while stack and stack[-1]>char and count[stack[-1]] > 0:
stack.pop()
# after every condition just decrement the count for that char and push to stack
count[char] -= 1
stack.append(char)
return "".join(stack) | remove-duplicate-letters | Python | TC-O(N)/SC-O(N) | Easy to understand with comments | | Patil_Pratik | 0 | 34 | remove duplicate letters | 316 | 0.446 | Medium | 5,458 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1634652/Pythonic-solution(with-speedy-improvement) | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
seen = {el: index for index, el in enumerate(s)} # write down last indexes for the values
result = [s[0]] # variable for future result
for i in range(1, len(s)): # start from index 1 as the first value has already been added
if s[i] in set(result): # remember: looking for a value in a set takes O(1) instead of O(n) in array, that's why it's much better to transform your list to a hash table
continue
while result[-1] > s[i] and seen[result[-1]] > i:
result.pop()
if len(result) == 0:
break
result.append(s[i])
return ''.join(result) | remove-duplicate-letters | Pythonic solution(with speedy improvement) | Dany_Sulimov | 0 | 249 | remove duplicate letters | 316 | 0.446 | Medium | 5,459 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1449546/Python3-Solution-using-stack | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
d = {c: i for i, c in enumerate(s)}
stack = ['#']
visited = set()
for idx, symb in enumerate(s):
if symb in visited:
continue
while symb < stack[-1] and d[stack[-1]] > idx:
visited.remove(stack.pop())
stack.append(symb)
visited.add(symb)
return ''.join(stack[1:]) | remove-duplicate-letters | [Python3] Solution using stack | maosipov11 | 0 | 166 | remove duplicate letters | 316 | 0.446 | Medium | 5,460 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/1449546/Python3-Solution-using-stack | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
stack = []
c2c = collections.Counter(s) # char to count
visited = set()
for c in s:
if c not in visited:
while stack and c2c[stack[-1]] > 0 and stack[-1] > c:
elem = stack.pop()
visited.remove(elem)
visited.add(c)
stack.append(c)
c2c[c] -= 1
return ''.join(stack) | remove-duplicate-letters | [Python3] Solution using stack | maosipov11 | 0 | 166 | remove duplicate letters | 316 | 0.446 | Medium | 5,461 |
https://leetcode.com/problems/remove-duplicate-letters/discuss/894596/Python3-stack-O(N)-time-O(N)-space | class Solution:
def removeDuplicateLetters(self, s: str) -> str:
mp = {c: i for i, c in enumerate(s)}
stack = []
for i, c in enumerate(s):
if c not in stack:
while stack and c < stack[-1] and i < mp[stack[-1]]: stack.pop()
stack.append(c)
return "".join(map(str, stack)) | remove-duplicate-letters | [Python3] stack O(N) time O(N) space | ye15 | 0 | 157 | remove duplicate letters | 316 | 0.446 | Medium | 5,462 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085316/Python-or-or-Easy-3-Approaches-explained | class Solution:
def maxProduct(self, words: List[str]) -> int:
n=len(words)
char_set = [set(words[i]) for i in range(n)] # precompute hashset for each word
max_val = 0
for i in range(n):
for j in range(i+1, n):
if not (char_set[i] & char_set[j]): # if nothing common
max_val=max(max_val, len(words[i]) * len(words[j]))
return max_val | maximum-product-of-word-lengths | ✅ Python | | Easy 3 Approaches explained | constantine786 | 57 | 3,700 | maximum product of word lengths | 318 | 0.601 | Medium | 5,463 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085316/Python-or-or-Easy-3-Approaches-explained | class Solution:
def maxProduct(self, words: List[str]) -> int:
return max([len(s1) * len(s2) for s1, s2 in combinations(words, 2) if not (set(s1) & set(s2))], default=0) | maximum-product-of-word-lengths | ✅ Python | | Easy 3 Approaches explained | constantine786 | 57 | 3,700 | maximum product of word lengths | 318 | 0.601 | Medium | 5,464 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085316/Python-or-or-Easy-3-Approaches-explained | class Solution:
def maxProduct(self, words: List[str]) -> int:
n=len(words)
bit_masks = [0] * n
lengths = [0] * n
for i in range(n):
for c in words[i]:
bit_masks[i]|=1<<(ord(c) - ord('a')) # set the character bit
lengths[i]=len(words[i])
max_val = 0
for i in range(n):
for j in range(i+1, n):
if not (bit_masks[i] & bit_masks[j]):
max_val=max(max_val, lengths[i] * lengths[j])
return max_val | maximum-product-of-word-lengths | ✅ Python | | Easy 3 Approaches explained | constantine786 | 57 | 3,700 | maximum product of word lengths | 318 | 0.601 | Medium | 5,465 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2086001/Python-Simple-Solution-oror-Brute-force-to-Optimized-code | class Solution:
def maxProduct(self, words: List[str]) -> int:
l = []
for i in words:
for j in words:
# creating a string with common letters
com_str = ''.join(set(i).intersection(j))
# if there are no common letters
if len(com_str) == 0:
l.append(len(i)*len(j))
# if the list is not empty
if len(l) != 0:
return max(l)
# return 0 otherwise
return 0 | maximum-product-of-word-lengths | Python Simple Solution || Brute force to Optimized code | Shivam_Raj_Sharma | 5 | 262 | maximum product of word lengths | 318 | 0.601 | Medium | 5,466 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2088561/What-about-a-trie | class Solution:
def maxProduct(self, words: List[str]) -> int:
n = len(words)
best = 0
trie = {}
# Build a trie
# O(N * U * logU) where U is the number of unique letters (at most 26), simplified to O(N)
for word in words:
node = trie
letters = sorted(set(word))
for char in letters:
if char not in node:
node[char] = {}
node = node[char]
# The "None" node will store the length of the word
node[None] = max(node.get(None, 0), len(word))
# Loop through each word
# O(N)
for word in words:
letters = set(word)
word_len = len(word)
# With BFS find the longest word inside the trie that does not have any common letters with current word
# O(2^26 - 1) => O(1)
queue = collections.deque([trie])
while queue:
node = queue.popleft()
if None in node:
best = max(best, node[None] * word_len)
# Explore the neighbors
for char in node.keys():
if char is not None and char not in letters:
queue.append(node[char])
return best | maximum-product-of-word-lengths | What about a trie? | corcoja | 3 | 70 | maximum product of word lengths | 318 | 0.601 | Medium | 5,467 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/788487/Python3-%22brute-force%22ish | class Solution:
def maxProduct(self, words: List[str]) -> int:
mp = dict()
for word in words:
for c in word:
mp.setdefault(c, set()).add(word)
s = set(words)
ans = 0
for word in words:
comp = set().union(*(mp[c] for c in word))
ans = max(ans, len(word) * max((len(x) for x in s - comp), default=0))
return ans | maximum-product-of-word-lengths | [Python3] "brute-force"ish | ye15 | 2 | 127 | maximum product of word lengths | 318 | 0.601 | Medium | 5,468 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/788487/Python3-%22brute-force%22ish | class Solution:
def maxProduct(self, words: List[str]) -> int:
mp = defaultdict(int)
for word in words:
mask = 0
for ch in word: mask |= 1 << ord(ch)-97
mp[mask] = max(mp[mask], len(word))
return max((mp[x]*mp[y] for x in mp for y in mp if not x & y), default=0) | maximum-product-of-word-lengths | [Python3] "brute-force"ish | ye15 | 2 | 127 | maximum product of word lengths | 318 | 0.601 | Medium | 5,469 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/788487/Python3-%22brute-force%22ish | class Solution:
def maxProduct(self, words: List[str]) -> int:
mp = {} #mapping from mask to length
for word in words:
mask = reduce(or_, (1 << ord(c)-97 for c in word), 0)
mp[mask] = max(len(word), mp.get(mask, 0))
return max((mp[x] * mp[y] for x in mp for y in mp if not x&y), default=0) | maximum-product-of-word-lengths | [Python3] "brute-force"ish | ye15 | 2 | 127 | maximum product of word lengths | 318 | 0.601 | Medium | 5,470 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2087664/simple-and-clean-code-in-python | class Solution:
def maxProduct(self, words: List[str]) -> int:
maxVal = 0
for comb in combinations(words,2):
for char in comb[0]:
if char in comb[1]:
break
else:
maxVal = max(len(comb[0])*len(comb[1]),maxVal)
return maxVal | maximum-product-of-word-lengths | simple and clean code in python | thunder-007 | 1 | 86 | maximum product of word lengths | 318 | 0.601 | Medium | 5,471 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085362/Python-brute-force-O(N2)-using-sets-and-bitmasks | class Solution:
def maxProduct(self, words: List[str]) -> int:
result = 0
words_set = [set(word) for word in words]
for i in range(len(words)-1):
for j in range(i + 1, len(words)):
if (len(words[i]) * len(words[j]) > result and
not (words_set[i] & words_set[j])):
result = len(words[i]) * len(words[j])
return result | maximum-product-of-word-lengths | Python, brute force O(N^2) using sets and bitmasks | blue_sky5 | 1 | 97 | maximum product of word lengths | 318 | 0.601 | Medium | 5,472 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085362/Python-brute-force-O(N2)-using-sets-and-bitmasks | class Solution:
def maxProduct(self, words: List[str]) -> int:
def bitmask(word):
mask = 0
for c in word:
mask |= 1 << ord(c) - ord('a')
return mask
result = 0
bitmasks = [bitmask(word) for word in words]
for i in range(len(words)-1):
for j in range(i + 1, len(words)):
if (len(words[i]) * len(words[j]) > result and
bitmasks[i] & bitmasks[j] == 0):
result = len(words[i]) * len(words[j])
return result | maximum-product-of-word-lengths | Python, brute force O(N^2) using sets and bitmasks | blue_sky5 | 1 | 97 | maximum product of word lengths | 318 | 0.601 | Medium | 5,473 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1724311/Python3-Basic-Solution | class Solution:
def maxProduct(self, words: List[str]) -> int:
m = 0
word = sorted(words,key = len)[::-1]
for i in range(len(words)):
for j in range(i,len(words)):
if(i==j):
continue
if(set(words[i]).intersection(set(words[j])) == set()):
m = max(m,len(words[i])*len(words[j]))
return m | maximum-product-of-word-lengths | Python3 Basic Solution | priyanshi23 | 1 | 110 | maximum product of word lengths | 318 | 0.601 | Medium | 5,474 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1492634/python3-O(n2)-Elegant-solution | class Solution:
def maxProduct(self, words: List[str]) -> int:
def check(a,b):
for char in a:
if char in b:
return False
return True
max_ln = 0
for indx,word in enumerate(words):
for nxt_word in words[indx:]:
prdct = len(word)*len(nxt_word)
if check(word,nxt_word) and max_ln<prdct:
max_ln=prdct
return max_ln | maximum-product-of-word-lengths | [python3] O(n^2) Elegant solution | _jorjis | 1 | 109 | maximum product of word lengths | 318 | 0.601 | Medium | 5,475 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/1235015/Python-3-Solution-using-set | class Solution:
def maxProduct(self, words: List[str]) -> int:
m = 0
for x in words:
for i in words:
if not set(x)&set(i):
k =len(x) * len(i)
if k > m:
m = k
return(m) | maximum-product-of-word-lengths | [Python 3] Solution using set | SushilG96 | 1 | 102 | maximum product of word lengths | 318 | 0.601 | Medium | 5,476 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2662717/Python-solution | class Solution:
def maxProduct(self, words: List[str]) -> int:
sets = [set()] * len(words)
ans = 0
for i in range(len(words)):
sets[i] = set(list(words[i]))
for i in range(len(words)):
for j in range(i+1,len(words)):
if len(sets[i] & sets[j]) == 0:
ans = max(ans, len(words[i]) * len(words[j]))
return ans | maximum-product-of-word-lengths | Python solution | maomao1010 | 0 | 15 | maximum product of word lengths | 318 | 0.601 | Medium | 5,477 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2562189/Python-simple-solution | class Solution:
def maxProduct(self, words: list[str]) -> int:
ans, d = 0, {k: set(k) for k in words}
for i in range(len(words) - 1):
for j in range(i + 1, len(words)):
w1, w2 = words[i], words[j]
if not d[w1] & d[w2]:
ans = max(ans, len(w1) * len(w2))
return ans | maximum-product-of-word-lengths | Python simple solution | Mark_computer | 0 | 95 | maximum product of word lengths | 318 | 0.601 | Medium | 5,478 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2503130/easy-python-solution | class Solution:
def maxProduct(self, words: List[str]) -> int:
letter_dict = {}
for word in words :
letter_dict[word] = set([i for i in word])
max_num = 0
for i in range(len(words)) :
for j in range(i+1, len(words)) :
if len(words[i]) * len(words[j]) > max_num :
if len(letter_dict[words[i]].intersection(letter_dict[words[j]])) == 0 :
max_num = len(words[i]) * len(words[j])
return max_num | maximum-product-of-word-lengths | easy python solution | sghorai | 0 | 57 | maximum product of word lengths | 318 | 0.601 | Medium | 5,479 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2439854/460ms-faster-than-88-easy-python-code | class Solution:
def maxProduct(self, words: List[str]) -> int:
n=len(words)
wordset=[set(i) for i in words]
product=[len(words[i])*len(words[j]) for i in range(n) for j in range(i,n) if wordset[i].isdisjoint(wordset[j])]
if len(product)==0:
return 0
return max(product) | maximum-product-of-word-lengths | 460ms, faster than 88%, easy python code | ayushigupta2409 | 0 | 79 | maximum product of word lengths | 318 | 0.601 | Medium | 5,480 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2092136/Python3-or-using-sets-or-faster-than-73.61-of-Python3-online-submissions-for-Maximum-Product-of-Word | class Solution:
def maxProduct(self, words: List[str]) -> int:
stateLst = []
maxi = 0
n = len(words)
for i in range(n):
stateLst.append(self.findStateOfStr(words[i]))
for i in range(n):
for j in range(i+1, n):
if stateLst[i] & stateLst[j] == 0:
strProduct = len(words[i])*len(words[j])
maxi = max(maxi, strProduct)
return maxi
def findStateOfStr(self, word):
n = len(word)
state = 0
for i in range(n):
index = ord(word[i]) - ord("a")
state |= 1<< (index)
return state | maximum-product-of-word-lengths | ✅Python3 | using sets | faster than 73.61% of Python3 online submissions for Maximum Product of Word | prankurgupta18 | 0 | 79 | maximum product of word lengths | 318 | 0.601 | Medium | 5,481 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2092130/571-ms-faster-than-73.61-of-Python3-online-submissions-for-Maximum-Product-of-Word-Lengths. | class Solution:
def maxProduct(self, words: List[str]) -> int:
stateLst = []
maxi = 0
n = len(words)
for i in range(n):
stateLst.append(self.findStateOfStr(words[i]))
for i in range(n):
for j in range(i+1, n):
if stateLst[i] & stateLst[j] == 0:
strProduct = len(words[i])*len(words[j])
maxi = max(maxi, strProduct)
return maxi
def findStateOfStr(self, word):
n = len(word)
state = 0
for i in range(n):
index = ord(word[i]) - ord("a")
state |= 1<< (index)
return state | maximum-product-of-word-lengths | 571 ms, faster than 73.61% of Python3 online submissions for Maximum Product of Word Lengths. | prankurgupta18 | 0 | 36 | maximum product of word lengths | 318 | 0.601 | Medium | 5,482 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2089303/Python3-Easy-Approaches-Using-For-Loop-and-Break-(Explained) | class Solution:
def maxProduct(self, words: List[str]) -> int:
max_val = 0
status = False
newWords = []
for word in words:
newWords.append("".join(set(word)))
for i in range (len(words)):
for j in range (i+1, len(words)):
for letter1 in newWords[i]:
for letter2 in newWords[j]:
if letter1 == letter2:
status = True
break
else:
status = False
if status == True:
break
if status == False:
max_val = max(max_val, len(words[i]) * len(words[j]))
return max_val | maximum-product-of-word-lengths | [Python3] Easy Approaches Using For Loop and Break (Explained) | hjpdy | 0 | 14 | maximum product of word lengths | 318 | 0.601 | Medium | 5,483 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2088641/Python-using-set()-and-hashmap | class Solution:
def maxProduct(self, words: List[str]) -> int:
words_set = [set(w) for w in words]
res = 0
dic = {i: v for i, v in enumerate(words_set)}
for i in range(len(words) - 1):
for j in range(i + 1, len(words)):
if len(dic[i].intersection(dic[j])) == 0:
res = max(res, len(words[i]) * len(words[j]))
return res | maximum-product-of-word-lengths | Python using set() and hashmap | Kennyyhhu | 0 | 38 | maximum product of word lengths | 318 | 0.601 | Medium | 5,484 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2087649/Python-O(N2)-optimized-with-unique-bitmasks | class Solution:
def maxProduct(self, words: List[str]) -> int:
def bitmask(word):
mask = 0
for c in word:
mask |= 1 << ord(c) - 97 # 97 == ord('a')
return mask
bm2len = {}
for word in words:
bm = bitmask(word)
if bm2len.get(bm, 0) < len(word):
bm2len[bm] = len(word)
words = list(bm2len.items())
result = 0
for i in range(len(words)-1):
for j in range(i + 1, len(words)):
if (words[i][1] * words[j][1] > result and
words[i][0] & words[j][0] == 0):
result = words[i][1] * words[j][1]
return result | maximum-product-of-word-lengths | Python, O(N^2) optimized with unique bitmasks | blue_sky5 | 0 | 13 | maximum product of word lengths | 318 | 0.601 | Medium | 5,485 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2087320/Python3-solution-or-Made-using-for-while-loops-and-if-else | class Solution:
def maxProduct(self, words: List[str]) -> int:
alph = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
prods = []
for i in range(len(words)):
k=i
while k<len(words)-1:
k+=1
common = 0
for j in alph :
if j in words[i] and j in words[k]:
common+=1
if common == 0:
prods.append(len(words[i])*len(words[k]))
return max(prods,default = 0) | maximum-product-of-word-lengths | Python3 solution | Made using for, while loops and if else | rogan35 | 0 | 34 | maximum product of word lengths | 318 | 0.601 | Medium | 5,486 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2086863/Python3-Solution-with-using-bit-manipulation | class Solution:
def maxProduct(self, words: List[str]) -> int:
d = {}
for word in words:
mask = 0
for c in word:
mask |= 1 << (ord(c) - ord('a'))
d[word] = mask
res = 0
for i in range(len(words) - 1):
for j in range(i + 1, len(words)):
if d[words[i]] & d[words[j]] == 0:
res = max(res, len(words[i]) * len(words[j]))
return res | maximum-product-of-word-lengths | [Python3] Solution with using bit-manipulation | maosipov11 | 0 | 10 | maximum product of word lengths | 318 | 0.601 | Medium | 5,487 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2086617/java-python-bit-manipulation | class Solution:
def maxProduct(self, words: List[str]) -> int:
table = [0]*len(words)
ans = 0
for i in range(len(words)) :
for j in range(len(words[i])) :
table[i] |= 1<<(ord(words[i][j]) - 97)
for i in range(len(words)) :
for j in range(i, len(words)) :
if (table[i] & table[j]) == 0 :
ans = max(ans, len(words[i]) * len(words[j]))
return ans | maximum-product-of-word-lengths | java, python - bit manipulation | ZX007java | 0 | 18 | maximum product of word lengths | 318 | 0.601 | Medium | 5,488 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2086536/Python | class Solution:
def maxProduct(self, ws: List[str]) -> int:
d = [set() for j in range(len(ws))]
for i in range(len(ws)):
for val in ws[i]:
d[i].add(val)
ws[i] = len(ws[i])
ans = 0
for i in range(len(ws)):
for j in range(i+1,len(ws)):
t = False
for val in d[i]:
if val in d[j]:
t = True
break
if not t:
ans = max(ans,ws[i]*ws[j])
return ans | maximum-product-of-word-lengths | Python | Shivamk09 | 0 | 25 | maximum product of word lengths | 318 | 0.601 | Medium | 5,489 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2086446/Simple-brute-force-approach | class Solution:
def maxProduct(self, words: List[str]) -> int:
def check(a, b):
for i in a:
if i in b:
return False
return True
res = 0
for i in range(len(words)):
for j in range(len(words)):
if check(words[i], words[j]):
res = max(res, len(words[i]) * len(words[j]))
return res | maximum-product-of-word-lengths | Simple brute force approach | ankurbhambri | 0 | 22 | maximum product of word lengths | 318 | 0.601 | Medium | 5,490 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2086230/Python-Simple-Solution | class Solution:
def maxProduct(self, words: List[str]) -> int:
# initialize the variable's
max_ans, n = 0, len(words)
# generate all possible pairs via 2 for loop's
for i in range(n):
for j in range(i):
# check the set intersection. If there's no match then try to update the max_ans.
if len(set(words[i]).intersection(words[j])) == 0:
max_ans = max(max_ans, len(words[i]) * len(words[j]))
# return max_ans
return max_ans | maximum-product-of-word-lengths | Python Simple Solution | Nk0311 | 0 | 12 | maximum product of word lengths | 318 | 0.601 | Medium | 5,491 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2086143/Easiest-Approach-Python | class Solution:
def maxProduct(self, words: List[str]) -> int:
def checker(s1, s2):
flag = True
for i in s1:
if i in s2:
flag = False
return flag
max_prod = 0
for i in range(len(words)):
for j in range(i+1, len(words)):
if checker(words[i], words[j]):
max_prod = max(max_prod , len(words[i])*len(words[j]) )
return max_prod | maximum-product-of-word-lengths | Easiest Approach Python | Abhi-Jit | 0 | 24 | maximum product of word lengths | 318 | 0.601 | Medium | 5,492 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085838/Python-Python-Solution-Using-Brute-Force-Approach-or-O(n*n) | class Solution:
def maxProduct(self, words: List[str]) -> int:
def check(s1,s2):
for i in s1:
if i in s2:
return False
return True
result = 0
for i in range(len(words)-1):
for j in range(i+1,len(words)):
if check(words[i],words[j]) == True:
result = max(result,len(words[i])*len(words[j]))
return result | maximum-product-of-word-lengths | [ Python ] ✅✅ Python Solution Using Brute Force Approach | O(n*n) ✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 29 | maximum product of word lengths | 318 | 0.601 | Medium | 5,493 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085503/Python-Easy-Solution-(4-Lines) | class Solution:
def maxProduct(self, words: List[str]) -> int:
res = [0]
for i, word in enumerate(words):
for j in range(i+1, len(words)):
if all(char not in set(words[j]) for char in set(word)):
res.append(len(word)*len(words[j]))
return max(res) | maximum-product-of-word-lengths | Python Easy Solution (4 Lines) | pe-mn | 0 | 24 | maximum product of word lengths | 318 | 0.601 | Medium | 5,494 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085503/Python-Easy-Solution-(4-Lines) | class Solution:
def maxProduct(self, words: List[str]) -> int:
res = [0]
for i, word in enumerate(words):
for j in range(i+1, len(words)):
check = True
for char in set(word):
if char in set(words[j]):
check = False
break
if check:
res.append(len(word)*len(words[j]))
return max(res) | maximum-product-of-word-lengths | Python Easy Solution (4 Lines) | pe-mn | 0 | 24 | maximum product of word lengths | 318 | 0.601 | Medium | 5,495 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085498/Python-O(n2)-oror-Two-easy-approaches | class Solution:
def maxProduct(self, words: List[str]) -> int:
d=defaultdict(int)
for w in words:
bitw=0
for c in w:
bitw |=(1<<ord(c)-97)
d[w]=bitw
def common(s,t):
if d[s]&d[t]:return True
return False
mx=0
for i in words:
for j in words:
if not common(i,j):
mx=max(mx,len(i)*len(j))
return mx | maximum-product-of-word-lengths | Python O(n2) || Two easy approaches | aditya1292 | 0 | 29 | maximum product of word lengths | 318 | 0.601 | Medium | 5,496 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085498/Python-O(n2)-oror-Two-easy-approaches | class Solution:
def maxProduct(self, words: List[str]) -> int:
d=defaultdict(set)
for w in words:
d[w]=set(w)
def common(s,t):
if d[s]&d[t]:return True
return False
mx=0
for i in words:
for j in words:
if not common(i,j):
mx=max(mx,len(i)*len(j))
return mx | maximum-product-of-word-lengths | Python O(n2) || Two easy approaches | aditya1292 | 0 | 29 | maximum product of word lengths | 318 | 0.601 | Medium | 5,497 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085359/Easy-to-Understand-Solution-with-no-bit-manipulation | class Solution:
def maxProduct(self, words: List[str]) -> int:
def inter(s1,s2):
set1 = set(s1)
set2 = set(s2)
z = set1.intersection(set2)
if not z:
return True
return False
counter = 0
for i in range(0,len(words)):
for j in range(0,len(words)):
if i == j:
continue
elif inter(words[i],words[j]) == True:
temp = len(words[i]) * len(words[j])
counter = max(counter,temp)
return counter | maximum-product-of-word-lengths | Easy to Understand Solution with no bit manipulation | masamune-prog | 0 | 16 | maximum product of word lengths | 318 | 0.601 | Medium | 5,498 |
https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2071456/Python-Solution | class Solution:
def maxProduct(self, words: List[str]) -> int:
m = 0
wLen = len(words)
for i in range(wLen):
for j in range(wLen):
if all (k not in words[j] for k in words[i]):
m = max(m, len(words[i])*len(words[j]))
return m | maximum-product-of-word-lengths | Python Solution | vgholami | 0 | 21 | maximum product of word lengths | 318 | 0.601 | Medium | 5,499 |
Subsets and Splits