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/all-paths-from-source-to-target/discuss/2225609/Python-3%3A-DFS-and-BFS
class Solution: def allPathsSourceTarget(self, graph): stack = [] for ii in range(len(graph[0])): stack.append((graph[0][ii],[0,graph[0][ii]])) final = [] while stack: end, road = stack.pop() if end == len(graph)-1: final.append(road) if end < len(graph): if graph[end]: for ii in range(len(graph[end])): stack.append((graph[end][ii], road + [graph[end][ii]])) return final
all-paths-from-source-to-target
Python 3: DFS & BFS
SetsunaOgiso
0
23
all paths from source to target
797
0.815
Medium
13,000
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/2022607/Fast-DFS-Solution
class Solution: def solve(self, current,output,n, graph): if current==n: self.ans.append(list(output)) return for i in range(len(graph[current])): output.append(graph[current][i]) self.solve(graph[current][i],output,n, graph) output.pop() def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: n = len(graph)-1 self.ans = [] self.solve(0,[0],n, graph) return self.ans
all-paths-from-source-to-target
Fast DFS Solution
dbansal18
0
28
all paths from source to target
797
0.815
Medium
13,001
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1872285/Python3-Traversal-with-2D-linked-list
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: self.res = [] # Keep track of all the paths during recursion path = [] self.traverse(graph, 0, path) return self.res def traverse(self, graph, s, path): path.append(s) n = len(graph) # Stops when the current path hits all the nodes if (s == n - 1): self.res.append(path.copy()); path.pop(-1) return # Run traversal for all neighboring nodes of s for v in graph[s]: self.traverse(graph, v, path) path.pop(-1)
all-paths-from-source-to-target
[Python3] Traversal with 2D linked-list
leqinancy
0
12
all paths from source to target
797
0.815
Medium
13,002
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1858003/Python-Solution-oror-Backtracking
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: def pathtrack(node,path,ans,graph,l): if node == [] or path[-1] == l-1: if path[-1] != l-1: path.pop(-1) return ans.append(path) path = [0] return for i in node: nextnode = i pathtrack(graph[i],path+[i],ans,graph,l) ans = [] path = [0] l = len(graph) pathtrack(graph[0],path,ans,graph,l) return ans
all-paths-from-source-to-target
Python Solution || Backtracking
MS1301
0
49
all paths from source to target
797
0.815
Medium
13,003
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1815375/Python-Backtracking
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: n = len(graph) def backtrack(result, curr=0, nodesInPath=[0]): if curr == n - 1: result.append(nodesInPath[:]) if not graph[curr]: return for neigh in graph[curr]: nodesInPath.append(neigh) backtrack(result, neigh, nodesInPath) nodesInPath.pop() result = [] backtrack(result) return result
all-paths-from-source-to-target
Python Backtracking
Rush_P
0
41
all paths from source to target
797
0.815
Medium
13,004
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1805112/Python-or-why-use-deque-instead-of-List-in-Backtracking
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: def backtrack(graph, s, p): # the path should be a nonlocal variable nonlocal path if not graph: return n = len(graph) # if reach the target, no need to explore more. if s == n-1: res.append(list(path)) return # Explore the neighbor nodes for v in graph[s]: path.append(v) backtrack(graph, v, path) path = path[:-1] res = [] path = [0] backtrack(graph, 0, path) return res
all-paths-from-source-to-target
Python | why use deque instead of List in Backtracking?
Fayeyf
0
34
all paths from source to target
797
0.815
Medium
13,005
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1746645/108-ms-faster-than-61.22-Memory-Usage%3A-15.7-MB-less-than-51.25-using-python3-and-backtracking
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: self.res = [] self.n = len(graph) self.vis = [False for i in range(self.n)] def solve(path,index): if(path[-1] == self.n-1): self.res.append(path) return if(not graph[index]): if(path[-1] ==self.n - 1): self.res.append(path) return for i in graph[index]: if(not self.vis[i]): self.vis[i] = True solve(path + [i],i) self.vis[i] = False solve([0],0) return self.res
all-paths-from-source-to-target
108 ms, faster than 61.22% Memory Usage: 15.7 MB, less than 51.25% using python3 and backtracking
jagdishpawar8105
0
60
all paths from source to target
797
0.815
Medium
13,006
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1699730/Python-Easy-Solution
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: out = [] def findPath(i=0, l=[]): l.append(i) if i == len(graph)-1: out.append(l) for ele in graph[i]: findPath(ele, l.copy()) findPath() return out
all-paths-from-source-to-target
Python Easy Solution
dhnam2234
0
66
all paths from source to target
797
0.815
Medium
13,007
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1692734/797-All-paths-From-Source-to-Target-via-Backtracking
class Solution: def allPathsSourceTarget(self, graph): result = []; path = [0] self.dfs(graph, result, path, 0) return result def dfs(self, graph, result, path, start): if start == len(graph) - 1: result.append(path[:]) return for node in graph[start]: ### search space path.append(node) self.dfs(graph, result, path, node) path.pop() ### backtracking
all-paths-from-source-to-target
797 All paths From Source to Target via Backtracking
zwang198
0
267
all paths from source to target
797
0.815
Medium
13,008
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1692734/797-All-paths-From-Source-to-Target-via-Backtracking
class Solution: def allPathsSourceTarget(self, graph): result = []; path = [] self.dfs(graph, result, path, 0) return result def dfs(self, graph, result, path, start): path.append(start) if start == len(graph) - 1: result.append(path[:]) path.pop() return for node in graph[start]: ### search space self.dfs(graph, result, path, node) path.pop() ### backtracking
all-paths-from-source-to-target
797 All paths From Source to Target via Backtracking
zwang198
0
267
all paths from source to target
797
0.815
Medium
13,009
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/1684571/python3-slow-but-easy-BFS-solution-w-explanation
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: total = [[0]] ans = [] target = len(graph) - 1 while total: # start BFS itr = total.pop(0) last = itr[-1] possible = graph[last] if not possible: #not possible means no valid edge stars with the end of this path continue for i in possible: if i == target: #find valid path, concact the target, and append it to answer ans.append(itr + [target]) continue total.append(itr + [i]) #add all pending path to the end of the queue return ans
all-paths-from-source-to-target
python3 slow but easy BFS solution w explanation
752937603
0
48
all paths from source to target
797
0.815
Medium
13,010
https://leetcode.com/problems/smallest-rotation-with-highest-score/discuss/1307760/Python3-difference-array
class Solution: def bestRotation(self, nums: List[int]) -> int: diff = [0]*(len(nums) + 1) for i, x in enumerate(nums): diff[i+1] += 1 if x <= i: diff[0] += 1 diff[(i-x)%len(nums) + 1] -= 1 ans = prefix = 0 mx = -inf for i, x in enumerate(diff): prefix += x if prefix > mx: mx, ans = prefix, i return ans
smallest-rotation-with-highest-score
[Python3] difference array
ye15
0
137
smallest rotation with highest score
798
0.498
Hard
13,011
https://leetcode.com/problems/smallest-rotation-with-highest-score/discuss/1307760/Python3-difference-array
class Solution: def bestRotation(self, nums: List[int]) -> int: diff = [1] * len(nums) for i, x in enumerate(nums): diff[(i-x+1) % len(nums)] -= 1 prefix = list(accumulate(diff)) return prefix.index(max(prefix))
smallest-rotation-with-highest-score
[Python3] difference array
ye15
0
137
smallest rotation with highest score
798
0.498
Hard
13,012
https://leetcode.com/problems/champagne-tower/discuss/1818232/Python-Easy-Solution-or-95-Faster-or-Dynamic-Programming
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: dp = [[0 for _ in range(x)] for x in range(1, query_row + 2)] dp[0][0] = poured for i in range(query_row): for j in range(len(dp[i])): temp = (dp[i][j] - 1) / 2.0 if temp>0: dp[i+1][j] += temp dp[i+1][j+1] += temp return dp[query_row][query_glass] if dp[query_row][query_glass] <= 1 else 1
champagne-tower
✔️ Python Easy Solution | 95% Faster | Dynamic Programming
pniraj657
24
1,300
champagne tower
799
0.513
Medium
13,013
https://leetcode.com/problems/champagne-tower/discuss/1819005/Python-Detailed-explanation-or-faster-than-92.23-or-Memory-less-than-95.15
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: pyramid = {k-1:[0] * k for k in range(1, 101)} pyramid[0][0] = poured for row in range(1, query_row+1): T = True for c in range(row): val = (pyramid[row-1][c] - 1.0) / 2.0 if val>0: T = False pyramid[row][c] += val pyramid[row][c+1] += val if T: return min(1, pyramid[query_row][query_glass]) return min(1, pyramid[query_row][query_glass])
champagne-tower
[Python] Detailed explanation | faster than 92.23% | Memory less than 95.15%
zouhair11elhadi
4
123
champagne tower
799
0.513
Medium
13,014
https://leetcode.com/problems/champagne-tower/discuss/1817816/Python-Simple-Python-Solution-Using-Dynamic-Programming
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: dp = [[0]*x for x in range(1,102)] dp[0][0] = poured for row in range(query_row + 1): for col in range(row + 1): mid_pour = (dp[row][col] - 1.0) / 2.0 if mid_pour > 0: dp[row+1][col] = dp[row+1][col] + mid_pour dp[row+1][col+1] = dp[row+1][col+1] + mid_pour result = min(1, dp[query_row][query_glass]) return result
champagne-tower
[ Python ] ✔✔ Simple Python Solution Using Dynamic Programming 🔥✌
ASHOK_KUMAR_MEGHVANSHI
3
375
champagne tower
799
0.513
Medium
13,015
https://leetcode.com/problems/champagne-tower/discuss/1817737/Simulation-with-flag
class Solution: def champagneTower(self, poured: int, r: int, c: int) -> float: dp = [[0] * i for i in range(1, 102)] dp[0][0] = poured for i in range(100): go_to_next_level = False #set a flag to judge if you go to next level or not for j in range(i + 1): if dp[i][j] > 1: go_to_next_level = True drip = dp[i][j] - 1 dp[i + 1][j] += drip / 2 dp[i + 1][j + 1] += drip / 2 if not go_to_next_level: break return min(1, dp[r][c])
champagne-tower
Simulation with flag
kryuki
2
32
champagne tower
799
0.513
Medium
13,016
https://leetcode.com/problems/champagne-tower/discuss/986513/Python3-dp-(top-down-and-bottom-up)
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: @lru_cache(None) def fn(i, j): """Return wine poured into glass (i, j).""" if i == j == 0: return poured # boundary condition if j < 0 or j > i: return 0 # boundary condition return max(0, fn(i-1, j-1)-1)/2 + max(0, fn(i-1, j)-1)/2 return min(1, fn(query_row, query_glass))
champagne-tower
[Python3] dp (top-down & bottom-up)
ye15
2
162
champagne tower
799
0.513
Medium
13,017
https://leetcode.com/problems/champagne-tower/discuss/986513/Python3-dp-(top-down-and-bottom-up)
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: dp = [poured] + query_row*[0] for i in range(1, query_row+1): for j in reversed(range(i+1)): dp[j] = max(0, dp[j]-1)/2 + (j>0)*max(0, dp[j-1]-1)/2 return min(1, dp[query_glass])
champagne-tower
[Python3] dp (top-down & bottom-up)
ye15
2
162
champagne tower
799
0.513
Medium
13,018
https://leetcode.com/problems/champagne-tower/discuss/1819960/Python-Easy-To-Understand-With-Explanation.
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: # Create the levels with exact number of elements in each level # 1,2,3,4,5,----- levels = [[0]*i for i in range(1,query_row+2)] # Update the first level with the poured wine. levels[0] = [poured] # Iterate for all the levels from 0 to end-1 and based on the cup update the next 2 below cups # For cup at index i,j the next level cups will be [i+1,j] and [i+1,j+1]. # Important : Skip the cups that has less than 1 level of water as they won't flow over and in calculation # they will add -ve number and mess up the final value. for i in range(len(levels)-1): for j in range(len(levels[i])): if levels[i][j]-1 <= 0: continue temp = (levels[i][j]-1)/2.0 levels[i+1][j] = levels[i+1][j]+temp levels[i+1][j+1] = levels[i+1][j+1]+temp # Return the calculated response. return min(1,levels[query_row][query_glass]) # TC : N*M where N = no of levels-1 and M = number of cups-queryglass+1 # Sc = N*M as we are storing the data. We can remove this part by deleting the used values.
champagne-tower
Python Easy To Understand With Explanation.
H1ccup
1
31
champagne tower
799
0.513
Medium
13,019
https://leetcode.com/problems/champagne-tower/discuss/1818236/Recursion-with-memoization-Simple-approach-Easy-to-Understand-Dynamic-programming-Python
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: def solve(val, r, g,dp): if r==0 and g==0: return val if g<0 or g>r: return 0 if (r,g) in dp: return dp[(r,g)] left = max((solve(val,r-1,g-1,dp)-1)/2,float(0)) right = max((solve(val,r-1,g,dp)-1)/2,float(0)) dp[(r,g)] = left+right return dp[(r,g)] return min(solve(poured,query_row,query_glass,{}),float(1))
champagne-tower
Recursion with memoization , Simple approach , Easy to Understand , Dynamic programming , Python
user8744WJ
1
102
champagne tower
799
0.513
Medium
13,020
https://leetcode.com/problems/champagne-tower/discuss/2804556/Python-recursion
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: @cache def helper(i, j): if i == 0 and j == 0: return poured left, right = 0, 0 if j > 0: left = helper(i - 1, j - 1) if j < i: right = helper(i - 1, j) if left > 1: left -= 1 left /= 2 else: left = 0 if right > 1: right -= 1 right /= 2 else: right = 0 return left + right ans = helper(query_row, query_glass) return min(ans, 1)
champagne-tower
Python, recursion
yiming999
0
1
champagne tower
799
0.513
Medium
13,021
https://leetcode.com/problems/champagne-tower/discuss/1820912/Python-Solution
class Solution: def champagneTower(self, poured, query_row, query_glass): glasses = [poured] for _ in range(query_row): temp = [0] * (len(glasses) + 1) for i in range(len(glasses)): pour = (glasses[i] - 1) / 2 if pour > 0: temp[i] += pour temp[i + 1] += pour glasses = temp return min(1, glasses[query_glass])
champagne-tower
Python Solution
pradeep288
0
20
champagne tower
799
0.513
Medium
13,022
https://leetcode.com/problems/champagne-tower/discuss/1820120/Python-DP-97.5
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: row, row_count = [poured], 0 while row_count < query_row: prev = 0 for i in range(len(row)): if row[i] > 1: prev, row[i] = row[i], ((row[i] - 1) / 2) if prev <= 1 else ((row[i] - 1) / 2) + ((prev - 1) / 2) else: prev, row[i] = row[i], 0 if prev <= 1 else ((prev - 1) / 2) if prev > 1: row.append((prev - 1) / 2) else: row.append(0) row_count += 1 return row[query_glass] if row[query_glass] < 1 else 1
champagne-tower
Python DP 97.5%
Rush_P
0
17
champagne tower
799
0.513
Medium
13,023
https://leetcode.com/problems/champagne-tower/discuss/1818956/Help-needed-I-don't-know-where-went-wrong-when-submiting-the-code
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: return min(self.getAmountPouredIntoThisGlass(poured, query_row, query_glass), 1) def getAmountPouredIntoThisGlass(self, poured, query_row, query_glass, d=dict())-> float: if query_row == 0: d[(0,0)] = poured return d[(0,0)] elif query_glass == 0 or query_glass == query_row: if (query_row, query_glass) in d: return d[(query_row, query_glass)] d[(query_row, query_glass)] = max((poured+1)/2**query_row - 1, 0) return d[(query_row, query_glass)] else: if (query_row, query_glass) in d: return d[(query_row, query_glass)] else: l_p = max(self.getAmountPouredIntoThisGlass(poured, query_row-1, query_glass - 1, d) - 1, 0) r_p = max(self.getAmountPouredIntoThisGlass(poured, query_row-1, query_glass, d) - 1, 0) d[(query_row, query_glass)] = 0.5*(l_p + r_p) return d[(query_row, query_glass)]
champagne-tower
Help needed, I don't know where went wrong when submiting the code
hclbeatyou
0
14
champagne tower
799
0.513
Medium
13,024
https://leetcode.com/problems/champagne-tower/discuss/1818714/Python-or-DP-2D-or-Clean-and-easy
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: dp = [[0 for _ in range(x)] for x in range(1, query_row + 2)] dp[0][0] = poured for i in range(query_row): for j in range(len(dp[i])): temp = (dp[i][j] - 1) / 2.0 if temp>0: dp[i+1][j] += temp dp[i+1][j+1] += temp return dp[query_row][query_glass] if dp[query_row][query_glass] <= 1 else 1
champagne-tower
Python | DP-2D | Clean and easy
sravyan
0
39
champagne tower
799
0.513
Medium
13,025
https://leetcode.com/problems/champagne-tower/discuss/1818510/Python3-Easy
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: arr = [[0 for i in range(101)] for j in range(101)] arr[0][0] = poured for i in range(100): for j in range(i+1): if arr[i][j] > 1: arr[i+1][j] += (arr[i][j]-1)*0.5 arr[i+1][j+1] += (arr[i][j]-1)*0.5 arr[i][j] = 1 return arr[query_row][query_glass]
champagne-tower
Python3 Easy
rishabhmanu
0
22
champagne tower
799
0.513
Medium
13,026
https://leetcode.com/problems/champagne-tower/discuss/1818463/Simple-Python3-Solution
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: dp = [[0 for _ in range(x)] for x in range(1, query_row + 2)] dp[0][0] = poured for i in range(query_row): for j in range(len(dp[i])): temp = (dp[i][j] - 1) / 2.0 if temp > 0: dp[i + 1][j] += temp dp[i + 1][j + 1] += temp return dp[query_row][query_glass] if dp[query_row][query_glass] <= 1 else 1
champagne-tower
Simple Python3 Solution
user6774u
0
22
champagne tower
799
0.513
Medium
13,027
https://leetcode.com/problems/champagne-tower/discuss/1817671/Fast-PHP-solution-(also-Python3-and-JS)-w-explanation
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: # Start out with 1 glass containing all the champagne. row = 0 rows = [[poured], 1] prev = 0 while(True): spilled = False for i,glass in enumerate(rows[prev]): if glass > 1: # Spill over to the next row. overflow = glass - 1 rows[prev][i] = 1 if not spilled: # Create the next row of glasses to collect the spillage. spilled = True rows[1-prev] = [0]*(row+2) rows[1-prev][i] += overflow/2 rows[1-prev][i+1] += overflow/2 if row == query_row: return rows[prev][query_glass] if not spilled: break prev = 1 - prev row += 1 return 0
champagne-tower
Fast PHP solution (also Python3 and JS) w/ explanation
crankyinmv
0
36
champagne tower
799
0.513
Medium
13,028
https://leetcode.com/problems/champagne-tower/discuss/1275558/python-solution-or
class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: dp =[ [0]*row for row in range(1,100+2) ] dp[0][0] = poured for i in range(query_row+1): for j in range(i+1):# calculating the amount of liquid which will left after completely filling this cup left = (dp[i][j] -1)/2 if left >0: dp[i+1][j]+=left dp[i+1][j+1]+=left return min(1, dp[query_row][query_glass])
champagne-tower
python solution |
chikushen99
0
113
champagne tower
799
0.513
Medium
13,029
https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/discuss/932390/Python3-two-counters
class Solution: def minSwap(self, A: List[int], B: List[int]) -> int: ans = sm = lg = mx = 0 for x, y in zip(A, B): if mx < min(x, y): # prev max < current min ans += min(sm, lg) # update answer &amp; reset sm = lg = 0 mx = max(x, y) if x < y: sm += 1 # count "x < y" elif x > y: lg += 1 # count "x > y" return ans + min(sm, lg)
minimum-swaps-to-make-sequences-increasing
[Python3] two counters
ye15
8
237
minimum swaps to make sequences increasing
801
0.393
Hard
13,030
https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/discuss/2675067/Python3-DP-Solution-O(n)-Time
class Solution: def minSwap(self, nums1: List[int], nums2: List[int]) -> int: dp = [[-1]*2 for i in range(len(nums1))] def solve(prev1, prev2, i, swaped): if i >= len(nums1): return 0 if dp[i][swaped] != -1: return dp[i][swaped] ans = 2**31 # No Swap if nums1[i] > prev1 and nums2[i] > prev2: ans = solve(nums1[i], nums2[i], i+1, 0) # Swap if nums1[i] > prev2 and nums2[i] > prev1: ans = min(ans, 1 + solve(nums2[i], nums1[i], i+1, 1)) dp[i][swaped] = ans return ans return solve(-1, -1, 0, 0)
minimum-swaps-to-make-sequences-increasing
✅ [Python3] DP Solution O(n) Time
samirpaul1
2
198
minimum swaps to make sequences increasing
801
0.393
Hard
13,031
https://leetcode.com/problems/find-eventual-safe-states/discuss/1317749/Python-DFS-Easy
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: n=len(graph) status=[0]*(n) res=[] def dfs(i):# this function will check is there any loop, cycle and i is a part of that loop,cycle if status[i]=="visited": #if this node is already visited, loop detected return true return True if status[i]=="safe": #if this node is previously visited and marked safe no need to repeat it ,return False no loop possible from it return False status[i]="visited" # so we have visited this node for j in graph[i]: if dfs(j):# if loop detected return True return True status[i]="safe" # if we reached till here means no loop detected from node i so this node is safe return False # no loop possible return false for i in range(n): if not dfs(i): #if no loop detected this node is safe res.append(i) return res
find-eventual-safe-states
Python-DFS-Easy
manmohan1105
9
575
find eventual safe states
802
0.553
Medium
13,032
https://leetcode.com/problems/find-eventual-safe-states/discuss/2548451/Python-Elegant-and-Short-or-O(V-%2B-E)-or-Three-color-DFS
class Solution: """ Time: O(V + E) Memory: O(V) """ WHITE = 0 GRAY = 1 BLACK = 2 def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: def dfs(u: int) -> bool: if color[u] == self.GRAY: return True if color[u] == self.BLACK: return False color[u] = self.GRAY for v in graph[u]: if dfs(v): return True color[u] = self.BLACK return False color = [self.WHITE] * len(graph) return [node for node in range(len(graph)) if not dfs(node)]
find-eventual-safe-states
Python Elegant & Short | O(V + E) | Three-color DFS
Kyrylo-Ktl
3
160
find eventual safe states
802
0.553
Medium
13,033
https://leetcode.com/problems/find-eventual-safe-states/discuss/2829279/Python3-Solution-or-DFS-or-O(n)
class Solution: def eventualSafeNodes(self, graph): N = len(graph) dp = [-1] * N def dfs(x): if dp[x] != -1: return dp[x] dp[x] = 0 for i in graph[x]: if dfs(i) == 0: return 0 dp[x] = 1 return 1 return [i for i in range(N) if dfs(i)]
find-eventual-safe-states
✔ Python3 Solution | DFS | O(n)
satyam2001
2
21
find eventual safe states
802
0.553
Medium
13,034
https://leetcode.com/problems/find-eventual-safe-states/discuss/1653036/Python3-Solution-with-using-topological-sorting
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: g = collections.defaultdict(list) indegree = collections.defaultdict(int) for v, neigbs in enumerate(graph): for neigb in neigbs: g[neigb].append(v) indegree[v] += 1 q = collections.deque() for v in range(len(graph)): if v not in indegree: q.append(v) res = [False] * len(graph) while q: node = q.popleft() res[node] = True for neigb in g[node]: indegree[neigb] -= 1 if indegree[neigb] == 0: q.append(neigb) return [idx for idx in range(len(res)) if res[idx]]
find-eventual-safe-states
[Python3] Solution with using topological sorting
maosipov11
2
95
find eventual safe states
802
0.553
Medium
13,035
https://leetcode.com/problems/find-eventual-safe-states/discuss/1604866/Python3-Kahn's-Algorithm-(count-number-of-reach-times)-with-BFS
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: """ 1. find all nodes that do not have outgoing edges -> terminal node 2. reverse all edges 3. from each terminal node, do BFS/DFS, the node we are reaching at the end are safe nodes """ q = deque() visited = set() # counts how many times a node is left to reach cnt = Counter() n_table = defaultdict(list) for i, neighbors in enumerate(graph): # count how many outgoing edges, -1 when reached cnt[i] = len(neighbors) # record reverse edge for n in neighbors: n_table[n].append(i) if len(neighbors) == 0: # no outgoing edges, set as start q.append(i) visited.add(i) res = [] while q: curr = q.popleft() res.append(curr) for neighbor in n_table[curr]: cnt[neighbor] -= 1 if neighbor not in visited and cnt[neighbor] == 0: q.append(neighbor) visited.add(neighbor) return sorted(res)
find-eventual-safe-states
[Python3] Kahn's Algorithm (count number of reach times) with BFS
nick19981122
2
164
find eventual safe states
802
0.553
Medium
13,036
https://leetcode.com/problems/find-eventual-safe-states/discuss/2705693/DFS-solution-using-cycle-detection-in-python
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: def check_cycle(node,graph,visited): if visited[node]==2: return True visited[node]=2 for neighbour in graph[node]: if visited[neighbour]!=1: if check_cycle(neighbour,graph,visited): return True visited[node]=1 return False n=len(graph) visited=[0]*(n) for i in range(n): if visited[i]==0: if check_cycle(i,graph,visited): continue answer=[] for i in range(n): if visited[i]==1: answer.append(i) return answer
find-eventual-safe-states
DFS solution using cycle detection in python
shashank_2000
1
10
find eventual safe states
802
0.553
Medium
13,037
https://leetcode.com/problems/find-eventual-safe-states/discuss/2024860/Python-easy-to-read-and-understand-or-dfs-(cycle-detection)
class Solution: def isCycle(self, graph, node, visit): if visit[node] == 2: return True visit[node] = 2 for nei in graph[node]: if visit[nei] != 1: if self.isCycle(graph, nei, visit): return True visit[node] = 1 return False def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: n = len(graph) visit = [0 for _ in range(n)] for i in range(n): if visit[i] == 0: if self.isCycle(graph, i, visit): continue ans = [] for i in range(n): if visit[i] == 1: ans.append(i) return ans
find-eventual-safe-states
Python easy to read and understand | dfs (cycle detection)
sanial2001
1
116
find eventual safe states
802
0.553
Medium
13,038
https://leetcode.com/problems/find-eventual-safe-states/discuss/932606/Python3-repeatedly-removing-terminals
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: ans, out, inn = [], [], [[] for _ in graph] # reversed graph for i, x in enumerate(graph): if not x: ans.append(i) # safe states out.append(len(x)) # out degree for xx in x: inn[xx].append(i) # in-nodes of xx for n in ans: for nn in inn[n]: out[nn] -= 1 if not out[nn]: ans.append(nn) return sorted(ans)
find-eventual-safe-states
[Python3] repeatedly removing terminals
ye15
1
67
find eventual safe states
802
0.553
Medium
13,039
https://leetcode.com/problems/find-eventual-safe-states/discuss/424804/simple-DFS-python-solution-with-explanation-faster-than-93
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: N = len(graph) T = set([n for n in range(N) if not graph[n]]) V = set() def dfs(node,visited): if node in T: return True if node in V or node in visited: return False visited.append(node) for n in graph[node]: if not dfs(n,visited): V.add(node) V.add(n) return False else: T.add(n) T.add(node) return True res = [n for n in range(N) if dfs(n,[])] return res
find-eventual-safe-states
simple DFS python solution with explanation faster than 93%
Maple177
1
185
find eventual safe states
802
0.553
Medium
13,040
https://leetcode.com/problems/find-eventual-safe-states/discuss/2824574/Python
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: n = len(graph) safe ={} res =[] def dfs(i): if i in safe: return safe[i] safe[i] = False for nei in graph[i]: if not dfs(nei): return safe[i] safe[i] = True return safe[i] for i in range(n): if dfs(i): res.append(i) return res
find-eventual-safe-states
Python
Sangeeth_psk
0
2
find eventual safe states
802
0.553
Medium
13,041
https://leetcode.com/problems/find-eventual-safe-states/discuss/2713370/python-solution-using-topological-sort
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: n=len(graph) indegree=[0]*(n) adj=[[]for _ in range(n)] for u in range(n): for v in graph[u]: adj[v].append(u) indegree[u]+=1 queue=deque() for v in range(n): if indegree[v]==0: queue.append(v) ans=[] while queue: u=queue.popleft() ans.append(u) for v in adj[u]: indegree[v]-=1 if indegree[v]==0: queue.append(v) return sorted(ans)
find-eventual-safe-states
python solution using topological sort
shashank_2000
0
12
find eventual safe states
802
0.553
Medium
13,042
https://leetcode.com/problems/find-eventual-safe-states/discuss/2417353/Simple-oror-Easy-to-understand-or-Python
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: cache = {} graph = {idx : graph[idx] for idx in range(len(graph))} def dfs(currentIdx, visited): if len(graph[currentIdx]) == 0: return True if currentIdx in visited: return False if currentIdx in cache: return cache[currentIdx] temp = True visited.add(currentIdx) for i in graph[currentIdx]: temp = temp and dfs(i, visited) if not temp: break visited.remove(currentIdx) cache[currentIdx] = temp return temp res = [] for idx in range(len(graph)): if dfs(idx, set()): res.append(idx) return res
find-eventual-safe-states
Simple || Easy to understand | Python
tvishnu
0
48
find eventual safe states
802
0.553
Medium
13,043
https://leetcode.com/problems/find-eventual-safe-states/discuss/1873116/fast-DFS-with-memo-cache-or-96%2B
class Solution: def eventualSafeNodes(self, graph): return self.dfs(graph) def dfs(self, graph): ''' cache safe statue in dfs ''' safe_status = [None] * len(graph) def check_safe(node) -> bool: if safe_status[node] is None: safe_status[node] = False # mark safe status first, incase dfs went into a loop for next_node in graph[node]: if not check_safe(next_node): break else: safe_status[node] = True return safe_status[node] # check safe for node in range(len(graph)): check_safe(node) return [idx for idx, safe in enumerate(safe_status) if safe]
find-eventual-safe-states
fast DFS with memo cache | 96+%
steve-jokes
0
64
find eventual safe states
802
0.553
Medium
13,044
https://leetcode.com/problems/find-eventual-safe-states/discuss/1823000/Python-DFS-74
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: def dfs(node, result, visited): if node in visited: return visited[node] == [] visited[node] for n in graph[node]: visited[node].append(n) if not dfs(n, result, visited): return False result.append(node) visited[node] = [] return True result, visited = [], defaultdict(list) for i in range(len(graph)): dfs(i, result, visited) result.sort() return result
find-eventual-safe-states
Python DFS 74%
Rush_P
0
95
find eventual safe states
802
0.553
Medium
13,045
https://leetcode.com/problems/find-eventual-safe-states/discuss/1736940/Python-Easy-to-understand-or-cycle-detection
class Solution: def dfs(self, graph, node, visited): if visited[node] == 2: return True visited[node] = 2 for nei in graph[node]: if visited[nei] != 1: if self.dfs(graph, nei, visited) == True: return True visited[node] = 1 return False def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: n = len(graph) visited = [0 for _ in range(n)] for i in range(n): if visited[i] == 0: if self.dfs(graph, i, visited): continue ans = [] for i in range(n): if visited[i] == 1: ans.append(i) return ans
find-eventual-safe-states
[Python] Easy to understand | cycle detection
sanial2001
0
80
find eventual safe states
802
0.553
Medium
13,046
https://leetcode.com/problems/find-eventual-safe-states/discuss/1420421/Python3-Detect-cycle-using-DFS.-Simple-readable-solution-with-comments.
class Solution: def is_cycle(self, graph: List[List[int]], node: int, is_visited: Set, is_safe: Set) -> bool: # IF node is already visited, return cycle detected true if node in is_visited: return True # IF node is already explored, and no cycle detected, return False if node in is_safe: return False # Add node to is_visited set is_visited.add(node) # Try to detect cycle in path of adjacent nodes for adj_node in graph[node]: if self.is_cycle(graph, adj_node, is_visited, is_safe): return True # Backtrack: Very important, as there can be many paths going through the same node. # And we might not have explored all of them. So remove the node from the visited set # and mark it as safe is_visited.remove(node) # Mark node as safe, as no cycle detected in its path is_safe.add(node) return False def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: # Init is_safe = set() is_visited = set() # Try to detect cycle for all the nodes for node in range(len(graph)): if node not in is_visited: self.is_cycle(graph, node, is_visited, is_safe) # Make sorted array of is_safe set is_safe = sorted(list(is_safe)) return is_safe
find-eventual-safe-states
[Python3] Detect cycle using DFS. Simple readable solution with comments.
ssshukla26
0
78
find eventual safe states
802
0.553
Medium
13,047
https://leetcode.com/problems/unique-morse-code-words/discuss/2438206/Python-Elegant-and-Short-or-Two-lines-or-No-loops
class Solution: """ Time: O(n) Memory: O(n) """ MORSE = { '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': '--..', } def uniqueMorseRepresentations(self, words: List[str]) -> int: return len(set(map(self.encode, words))) @classmethod def encode(cls, word: str) -> str: return ''.join(map(cls.MORSE.get, word))
unique-morse-code-words
Python Elegant & Short | Two lines | No loops
Kyrylo-Ktl
5
395
unique morse code words
804
0.827
Easy
13,048
https://leetcode.com/problems/unique-morse-code-words/discuss/362150/Solution-in-Python-3-(beats-~100)-(two-lines)
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: M = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..'] return len(set([''.join(map(lambda x: M[ord(x)-97], w)) for w in words])) - Junaid Mansuri (LeetCode ID)@hotmail.com
unique-morse-code-words
Solution in Python 3 (beats ~100%) (two lines)
junaidmansuri
4
584
unique morse code words
804
0.827
Easy
13,049
https://leetcode.com/problems/unique-morse-code-words/discuss/2436772/Python-easy-understanding-solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: s = set() mos = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] for w in words: # Iterate through every word. m = '' for l in w: # Iterate through every letter in current word. m += mos[ord(l) - ord('a')] # Change the letter into morse code. s.add(m) # Use set to avoid replicate answer. return len(s)
unique-morse-code-words
Python easy-understanding solution
byroncharly3
2
246
unique morse code words
804
0.827
Easy
13,050
https://leetcode.com/problems/unique-morse-code-words/discuss/2166577/Python3-O(n*m)-oror-O(n)
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: # O(n*m) || O(n) hashMap = {'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': '--..'} seen = set() for word in words: newList = [] for code in word: newList.append(hashMap[code]) seen.add(''.join(newList)) return len(seen)
unique-morse-code-words
Python3 O(n*m) || O(n)
arshergon
2
64
unique morse code words
804
0.827
Easy
13,051
https://leetcode.com/problems/unique-morse-code-words/discuss/2621809/Python3-oror-Best-Solution-O(N*K)-where-k-is-a-max-length-of-string
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: arr = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] s =set() for word in words: string = "" for ele in word: string+=arr[ord(ele)-97] s.add(string) return len(s)
unique-morse-code-words
Python3 || Best Solution O(N*K) , where k is a max length of string
shacid
1
31
unique morse code words
804
0.827
Easy
13,052
https://leetcode.com/problems/unique-morse-code-words/discuss/2441478/Simple-python-solution-85-speed
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: conversion = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] alphabet = 'abcdefghijklmnopqrstuvwxyz' d = {} for i in range(len(alphabet)): d[alphabet[i]] = conversion[i] transformations = [] for word in words: trans = '' for char in word: trans += d[char] if trans not in transformations: transformations.append(trans) return len(transformations)
unique-morse-code-words
Simple python solution 85% speed
yusefgharib
1
23
unique morse code words
804
0.827
Easy
13,053
https://leetcode.com/problems/unique-morse-code-words/discuss/1862059/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: arr = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] output = set() alpha = "abcdefghijklmnopqrstuvwxyz" for i in words: abc = "" for j in i: index = alpha.index(j) abc+=arr[index] output.add(abc) return len(output)
unique-morse-code-words
Python (Simple Approach and Beginner-Friendly)
vishvavariya
1
101
unique morse code words
804
0.827
Easy
13,054
https://leetcode.com/problems/unique-morse-code-words/discuss/1316260/Python3-oror-Memory-less-than-99.5oror-Faster-than-84
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] #update dictionary with key temp(the morse string) formed and just len(dictionary) di = {} for word in words: temp = "" for letter in word: temp+=morse[ord(letter)-97] #ord finds the ascii of letter #ascii of a is 97 di[temp]=1 return len(di)
unique-morse-code-words
Python3 || Memory less than 99.5%|| Faster than 84%
ana_2kacer
1
147
unique morse code words
804
0.827
Easy
13,055
https://leetcode.com/problems/unique-morse-code-words/discuss/1276632/Easy-Python-Solution(96.07)
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: d=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] x=[] c=0 for j in words: w=j s="" for i in w: s+=d[ord(i)-97] if(s not in x): x.append(s) c+=1 return c
unique-morse-code-words
Easy Python Solution(96.07%)
Sneh17029
1
273
unique morse code words
804
0.827
Easy
13,056
https://leetcode.com/problems/unique-morse-code-words/discuss/1216673/Python-dictionary-solution-93-faster
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: dict = {} morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] diff = ord('a') for i in words: ans = "" for j in range(len(i)): ans+=morse[ord(i[j])-diff] dict[ans] = 1 return len(dict)
unique-morse-code-words
Python dictionary solution 93% faster
bagdaulet881
1
146
unique morse code words
804
0.827
Easy
13,057
https://leetcode.com/problems/unique-morse-code-words/discuss/780193/Python3%3A-One-liner-(minus-the-line-to-define-the-alphabet)
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: ALPHABET = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] return len({"".join([ALPHABET[ord(char) - ord('a')] for char in word]) for word in words})
unique-morse-code-words
Python3: One-liner (minus the line to define the alphabet)
merdenberger31
1
54
unique morse code words
804
0.827
Easy
13,058
https://leetcode.com/problems/unique-morse-code-words/discuss/2841567/Python3-solution-Runtime-37-ms-Beats-92.72-Memory-13.8-MB-Beats-74.47
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: val = {'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' : "--.."} transformations = [] for word in words: transformation = "" for ch in word: transformation += val[ch] if transformation not in transformations: transformations.append(transformation) return len(transformations)
unique-morse-code-words
Python3 solution Runtime 37 ms Beats 92.72% Memory 13.8 MB Beats 74.47%
SupriyaArali
0
1
unique morse code words
804
0.827
Easy
13,059
https://leetcode.com/problems/unique-morse-code-words/discuss/2827841/PYTHON3-Solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: dic = [".-","-...","-.-.","-..",".","..-.","--.","....",".." \ ,".---","-.-",".-..","--","-.","---",".--.","--.-" \ ,".-.","...","-","..-","...-",".--","-..-","-.--","--.."] A = dict( zip( string.ascii_lowercase,dic) ) s = set() for word in words: s.add("".join( [ A[letter] for letter in word ] ) ) return len(s)
unique-morse-code-words
PYTHON3 Solution
Gurugubelli_Anil
0
4
unique morse code words
804
0.827
Easy
13,060
https://leetcode.com/problems/unique-morse-code-words/discuss/2816341/Fast-and-Simple-Solution-Python
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: values = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] checked = set() for i in range(0, len(words)): value = "" for char in words[i]: value += values[ord(char) - 97] if value not in checked: checked.add(value) return len(checked)
unique-morse-code-words
Fast and Simple Solution - Python
PranavBhatt
0
3
unique morse code words
804
0.827
Easy
13,061
https://leetcode.com/problems/unique-morse-code-words/discuss/2799108/(-)-Easy-Commented-Simple-Solution
class Solution(object): def uniqueMorseRepresentations(self, words): setOfAlltransformations=set() #a unique set which will contain unique eles morze = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] #list of all morse code letterMap={} #a dict to map letters to morse code idx=97 # initializing from first ascii. e.g. ascii of a is 97 for item in morze: #iterate through all items letterMap[chr(idx)]=item #map letter to its morse code idx+=1 #incrementing ascii for word in words: #iterate through each word wordDecode="" #initalize our equivalent string for char in word: #iterate through each letter in word wordDecode+=letterMap[char] #forming equivalent string setOfAlltransformations.add(wordDecode) #add that formed string to our set return len(setOfAlltransformations) #return lenght of that set
unique-morse-code-words
( ͡° ͜ʖ ͡°) Easy Commented Simple Solution
fa19-bcs-016
0
2
unique morse code words
804
0.827
Easy
13,062
https://leetcode.com/problems/unique-morse-code-words/discuss/2797499/Python-Solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: l=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] s=set() st="" for word in words: for i in range(len(word)): st+=l[ord(word[i])-97] s.add(st) st="" return len(s)
unique-morse-code-words
Python Solution
sbhupender68
0
2
unique morse code words
804
0.827
Easy
13,063
https://leetcode.com/problems/unique-morse-code-words/discuss/2781388/Python3-Easier-Solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: s = set() mos = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] for w in words: m = '' for l in w: m += mos[ord(l) - ord('a')] s.add(m) return len(s)
unique-morse-code-words
Python3 Easier Solution
avs-abhishek123
0
1
unique morse code words
804
0.827
Easy
13,064
https://leetcode.com/problems/unique-morse-code-words/discuss/2751647/Simple-Python-Solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morse_code_array = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] result = set() for word in words: word = word.lower() transformations = "" for chr in word: transformations += morse_code_array[ord(chr) - 97] result.add(transformations) return len(result)
unique-morse-code-words
Simple Python Solution
dnvavinash
0
4
unique morse code words
804
0.827
Easy
13,065
https://leetcode.com/problems/unique-morse-code-words/discuss/2743419/Python-easy-to-understand
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morsecodes = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] alphabet = ["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"] translation = {} for letter, code in zip(alphabet, morsecodes): translation[letter] = code def translate(word: str): code = '' for letter in word: code += translation[letter] return code seen = [] count = 0 for word in words: morse = translate(word) if morse not in seen: seen.append(morse) count += 1 return count
unique-morse-code-words
Python, easy to understand
vegancyberpunk
0
5
unique morse code words
804
0.827
Easy
13,066
https://leetcode.com/problems/unique-morse-code-words/discuss/2736849/Python-simple-solution-using-a-dictionary-and-a-set
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: def transform(word): morse_alphabet = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] english_alphabet = 'abcdefghijklmnopqrstuvwxyz' d = dict(zip(english_alphabet, morse_alphabet)) res = '' for letter in word: res += d[letter] return res transformations = set() for word in words: transformations.add(transform((word))) return len(transformations)
unique-morse-code-words
Python simple solution using a dictionary and a set
Mark_computer
0
6
unique morse code words
804
0.827
Easy
13,067
https://leetcode.com/problems/unique-morse-code-words/discuss/2718770/Python3-Solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] decoder = {chr(i):morse[i-97] for i in range(97,123)} morse_list = [] for word in words: item = "" for c in word: item += decoder[c] morse_list.append(item) return len(set(morse_list))
unique-morse-code-words
Python3 Solution
sipi09
0
2
unique morse code words
804
0.827
Easy
13,068
https://leetcode.com/problems/unique-morse-code-words/discuss/2605446/43-ms-faster-than-81.45-of-Python3
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: arr = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] l = [] for i in words: s = "" for j in i: s+=arr[ord(j)-97] l.append(s) l = Counter(l) return len(list(l))
unique-morse-code-words
43 ms, faster than 81.45% of Python3
Abdulahad_Abduqahhorov
0
31
unique morse code words
804
0.827
Easy
13,069
https://leetcode.com/problems/unique-morse-code-words/discuss/2449235/Python-3-Explanied-solution-with-Dict
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: # In this solution, we want to count unique morse translations of the input words # Let's use a dict (seen) for our output, because it makes it easy to only record new unique records seen = {} # Now, we need a way to take a word "gig" and turn it to morse before we can add it to our dict # `morse_list` is the morse representation of each char in alphabetical order (a=0, b=1, ...) # To get from a character to its morse, let's use the ASCII of that character as index #print(ord('a')) # uncomment this to see the position of 'a' (hint, it's 97) # If the ASCII of 'a' is 97, then (ASCII(character) - 97) will give us the right position in the morse list! # E.g. ASCII('b') - 97 = 98 - 97 = morse[1] = '-..' - Perfect! morse_list = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] # Now that we know how to convert to morse, we can loop through the list of words. For each word, we need to loop through # its characters, turning them one by one to morse. We will use the string 'morse' to hold the morse of the word so far # When the word is done, we can update the dict with that representation. If it is a duplicate, the VALUE in the key, value # pair will increase, but it won't add a new KEY. This means the same reperesentation has only one entry! Unique! for word in words: morse = '' for letter in word: morse += morse_list[ord(letter)-97] seen[morse] = seen.get(morse, 0) + 1 # So finally, all we need to do is return the length of the dict we used to store the seen representations! :) return len(seen)
unique-morse-code-words
[Python 3] Explanied solution with Dict
connorthecrowe
0
13
unique morse code words
804
0.827
Easy
13,070
https://leetcode.com/problems/unique-morse-code-words/discuss/2442152/98.45-memory-efficient-solution-using-set-and-ord-in-Python
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-", ".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-", ".--","-..-","-.--","--.."] res = set() for w in words: temp = '' for c in w: pos = ord(c) - ord('a') temp += morse[pos] res.add(temp) return len(list(res))
unique-morse-code-words
98.45% memory efficient solution using set and ord in Python
ankurbhambri
0
15
unique morse code words
804
0.827
Easy
13,071
https://leetcode.com/problems/unique-morse-code-words/discuss/2441222/Simple-Hashmap-Solution-or-Python
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: trans = {'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':"--.."} ans = set() for word in words: res = "" for i in word: res += trans[i] ans.add(res) return len(ans)
unique-morse-code-words
Simple Hashmap Solution | Python
Abhi_-_-
0
8
unique morse code words
804
0.827
Easy
13,072
https://leetcode.com/problems/unique-morse-code-words/discuss/2441149/Python-oror-Simple-and-Short-Solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morse_code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] res = set() for word in words: res.add(''.join([morse_code[ord(c)-ord('a')] for c in word])) return len(res)
unique-morse-code-words
Python || Simple and Short Solution
Gyalecta
0
13
unique morse code words
804
0.827
Easy
13,073
https://leetcode.com/problems/unique-morse-code-words/discuss/2441062/Python-Short-and-Easy-Solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: # Morse Code Words Charachter Representation stored in Dictionary morse = { "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":"--.." } # list in which transformed Morse Strings(morseStrings) will be stored transformed=[] # Loop on list of words for i in words: # Re-initialising morseString to empty string morseString = "" # Loop on Characters in a word for j in i: # Mapping charachter to Morse Charachter Representation and Concatenating to string morseString += morse[j] # Appending the transformed Morse String to list(named as transformed) transformed.append(morseString) # Returning the Length of Unique Morse Code Words using Sets return len(set(transformed))
unique-morse-code-words
Python Short & Easy Solution
arshdeepsahni
0
4
unique morse code words
804
0.827
Easy
13,074
https://leetcode.com/problems/unique-morse-code-words/discuss/2440957/Python3-oror-Optimal-and-Straight-Forward
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] res = set() for word in words: s = '' for c in word: s += morse[ord(c) - ord('a')] res.add(s) return len(res)
unique-morse-code-words
Python3 || Optimal & Straight Forward
Dewang_Patil
0
5
unique morse code words
804
0.827
Easy
13,075
https://leetcode.com/problems/unique-morse-code-words/discuss/2440215/Python-Easy-and-Simple-using-Set-Top-98-Space
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: # 25 len, 0 = a, ... 26 = z morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] # Not counting duplicates words_morse = set() # Iterate through each word for word in words: word_morse = "" # Iterate through each letter for letter in word: # Ord(letter) - ord('a') transforms letters into their index number on morse # we add these to the string word_morse += morse[ord(letter) - ord('a')] # Add the morse code word to the set words_morse.add(word_morse) # Return the len! return len(words_morse)
unique-morse-code-words
Python Easy and Simple using Set, Top 98% Space
drblessing
0
11
unique morse code words
804
0.827
Easy
13,076
https://leetcode.com/problems/unique-morse-code-words/discuss/2439765/Simple-Python-Solution-or-Easy-and-Fast
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: t = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] s = set() for word in words: code = '' for l in word: code += t[ord(l) - 97] s.add(code) return len(s)
unique-morse-code-words
Simple Python Solution | Easy and Fast
prameshbajra
0
12
unique morse code words
804
0.827
Easy
13,077
https://leetcode.com/problems/unique-morse-code-words/discuss/2439663/Simple-Python-solution-Set
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: #First, create a dict with the morse equivalencies morse_dict = {'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': '--..'} #Use a set to count unique sequences. unique = set() for word in words: morse = "" for char in word: morse += morse_dict[char] unique.add(morse) #Add already checks whether the morse string exists within the set return len(unique)
unique-morse-code-words
Simple Python solution - Set
GMFB
0
5
unique morse code words
804
0.827
Easy
13,078
https://leetcode.com/problems/unique-morse-code-words/discuss/2439582/GolangPython-O(N)-time-or-O(N)-space
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: letter_to_code = {"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":"--.."} words = set(words) codes = set() for word in words: codes.add("".join(letter_to_code[letter] for letter in word)) return len(codes)
unique-morse-code-words
Golang/Python O(N) time | O(N) space
vtalantsev
0
7
unique morse code words
804
0.827
Easy
13,079
https://leetcode.com/problems/unique-morse-code-words/discuss/2439412/Python-Super-Simple-Cake-Walk-Solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: # Dictionary containing all the corresponding Morse code values of characters dict = {'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':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'} # Converting all the strings into Morse Code for i in range (len(words)): words[i] = ''.join(dict[c] for c in words[i]) # Converting the array/list into set to filter out unique values sets = set(words) # Returning the length of this set containing unique Morse Code values return len(sets)
unique-morse-code-words
🐍🐲 Python Super Simple Cake Walk Solution 🐲🐍
sHadowSparK
0
11
unique morse code words
804
0.827
Easy
13,080
https://leetcode.com/problems/unique-morse-code-words/discuss/2439262/Python3-String-manipulationorSimple-and-understandable-approachorEasy
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: alpha=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] st=[] for i in words: s="" for j in i: s+=alpha[ord(j)-97] st.append(s) return len(set(st))
unique-morse-code-words
Python3 String manipulation|Simple and understandable approach|Easy
sushant332
0
5
unique morse code words
804
0.827
Easy
13,081
https://leetcode.com/problems/unique-morse-code-words/discuss/2439249/Python-Solution-with-explanation-in-comments
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: # Create an empty set s = set() # Initialize the morse code with code for each letter in a list named as code. code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] # Iterate through each word in the list words for i in words: # Initialize res with "" so that in future we can concatenate things in it. res = "" # Iterate for each letter in each word for j in i: # Now re-initialize the res res = res+code[ord(j)-ord('a')] # Now add this res to the set we've created earlier. s.add(res) # Now return the length of the set s. return(len(s))
unique-morse-code-words
Python Solution with explanation in comments
yashkumarjha
0
2
unique morse code words
804
0.827
Easy
13,082
https://leetcode.com/problems/unique-morse-code-words/discuss/2439003/Python3-oror-Easy-Solution-with-Explanation-oror-Faster
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: li = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] a = ord('a') s1 = set() for word in words: str1 = "" for w in word: str1 += "".join(li[ord(w)-a]) s1.add(str1) return(len(s1)) ```
unique-morse-code-words
Python3 || Easy Solution with Explanation || Faster
NITIN_DS
0
4
unique morse code words
804
0.827
Easy
13,083
https://leetcode.com/problems/unique-morse-code-words/discuss/2438706/Python3-HashTable-and-Set-based-solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: # Morse code mapping to alphabets. mapping = { "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": "--.." } for i, word in enumerate(words): new = "" for char in word: new += mapping[char] # Replace word with it's morse code representation in the original word list. words[i] = new return len(set(words)) # Turn the original list into set to remove duplicates and return length of set.
unique-morse-code-words
[Python3] HashTable and Set based solution
aakash111295
0
4
unique morse code words
804
0.827
Easy
13,084
https://leetcode.com/problems/unique-morse-code-words/discuss/2438705/Simple-and-Clean-Python3-code-using-2-'FOR-LOOPS'-oror-Beginner-friendly
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: c=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] s="abcdefghijklmnopqrstuvwxyz" codes=[] for i in words: morse='' for j in i: ind=s.index(j) morse=morse+c[ind] codes.append(morse) return len(set(codes))
unique-morse-code-words
Simple and Clean Python3 code using 2 'FOR LOOPS' || Beginner friendly
keertika27
0
6
unique morse code words
804
0.827
Easy
13,085
https://leetcode.com/problems/unique-morse-code-words/discuss/2438397/python3-simple-solution
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: ans = set() morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] for word in words: tmp = '' for c in word: tmp += morse[ord(c)-ord('a')] ans.add(tmp) return len(ans)
unique-morse-code-words
python3, simple solution
pjy953
0
2
unique morse code words
804
0.827
Easy
13,086
https://leetcode.com/problems/unique-morse-code-words/discuss/2438041/Python3-One-Liner-With-Breakdown
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: dictionary = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] def transform(word: str) -> str: return ''.join(dictionary[ord(ch) - ord('a')] for ch in word) transformations = set() for word in words: transformations.add(transform(word)) return len(transformations)
unique-morse-code-words
[Python3] One Liner With Breakdown
jeffreyhu8
0
5
unique morse code words
804
0.827
Easy
13,087
https://leetcode.com/problems/unique-morse-code-words/discuss/2438041/Python3-One-Liner-With-Breakdown
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: return len(set(''.join([".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."][ord(ch) - ord('a')] for ch in word) for word in words))
unique-morse-code-words
[Python3] One Liner With Breakdown
jeffreyhu8
0
5
unique morse code words
804
0.827
Easy
13,088
https://leetcode.com/problems/unique-morse-code-words/discuss/2438041/Python3-One-Liner-With-Breakdown
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: return len(set( # find the length of the set of all morse transformations (i.e. find the number of different transformations) ''.join( # join together the morse translation of each individual char to get the morse of the entire word [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."][ord(ch) - ord('a')] # translate each char of word to morse for ch in word # loop through all chars ) for word in words)) # loop through all words
unique-morse-code-words
[Python3] One Liner With Breakdown
jeffreyhu8
0
5
unique morse code words
804
0.827
Easy
13,089
https://leetcode.com/problems/unique-morse-code-words/discuss/2437898/As-easy-as-it-can-get-python3-solution-with-complexity-analysis
class Solution: # O(len(words) * m) time, m --> the longest word in words # O(len(words)) space, # Apporach: array, hashset def uniqueMorseRepresentations(self, words: List[str]) -> int: morse_code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] transformations = set() def convertToMorse(word:str) -> str: morse_version = '' a_ascii_val = 97 for ch in word: morse_version += morse_code[ord(ch)-a_ascii_val] return morse_version for word in words: transformations.add(convertToMorse(word)) return len(transformations)
unique-morse-code-words
As easy as it can get python3 solution with complexity analysis
destifo
0
3
unique morse code words
804
0.827
Easy
13,090
https://leetcode.com/problems/unique-morse-code-words/discuss/2437713/Hashing-oror-Easy-understanding-oror-98-Efficient
class Solution(object): def uniqueMorseRepresentations(self, words): """ :type words: List[str] :rtype: int """ listWord = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] dict_ = {} count = 0 for i in words: res = '' for j in i: res+=listWord[-97+ord(j)] if(res not in dict_): count+=1 dict_[res] = 1 return count
unique-morse-code-words
Hashing || Easy-understanding || 98% Efficient
mridulbhas
0
18
unique morse code words
804
0.827
Easy
13,091
https://leetcode.com/problems/unique-morse-code-words/discuss/2437634/Python3-Solution-with-using-hashset
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: alphabet = [".-","-...","-.-.","-..",".","..-.","--.", "....","..",".---","-.-",".-..","--","-.", "---",".--.","--.-",".-.","...","-","..-", "...-",".--","-..-","-.--","--.."] s = set() for word in words: s.add(''.join([alphabet[ord(char) - 97] for char in word])) return len(s)
unique-morse-code-words
[Python3] Solution with using hashset
maosipov11
0
4
unique morse code words
804
0.827
Easy
13,092
https://leetcode.com/problems/unique-morse-code-words/discuss/2437493/Python-easy-solution-(32-ms-beats-98)
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] d = {chr(i+96):morse[i-1] for i in range(1, 27)} res = [] for i in words: code = "" for j in i: code += d[j] res.append(code) return len(set(res))
unique-morse-code-words
Python easy solution (32 ms, beats 98%)
CasualTrash
0
9
unique morse code words
804
0.827
Easy
13,093
https://leetcode.com/problems/unique-morse-code-words/discuss/2437261/Python-soln-using-set
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: charToMorse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] wordSet = set() for word in words: temp = '' for c in word: temp += charToMorse[ord(c) - ord('a')] wordSet.add(temp) return len(wordSet)
unique-morse-code-words
Python soln using set
logeshsrinivasans
0
3
unique morse code words
804
0.827
Easy
13,094
https://leetcode.com/problems/unique-morse-code-words/discuss/2437230/python-runtime-29-ms
class Solution(object): def uniqueMorseRepresentations(self, words): """ :type words: List[str] :rtype: int """ morse_chars = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..", "--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] result = [] for word in words: morse_str = '' for char in word: idx = ord(char) - 97 morse_str += morse_chars[idx] result.append(morse_str) return len(list(set(result))) ```
unique-morse-code-words
python - runtime 29 ms
user2354hl
0
4
unique morse code words
804
0.827
Easy
13,095
https://leetcode.com/problems/unique-morse-code-words/discuss/2437161/48ms-or-fast-and-easy
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: code=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] transformation=set() for word in words: s='' for letter in word: s=s+code[ord(letter)-97] transformation.add(s) return len(transformation)
unique-morse-code-words
48ms | fast & easy
ayushigupta2409
0
7
unique morse code words
804
0.827
Easy
13,096
https://leetcode.com/problems/split-array-with-same-average/discuss/120654/Simple-python-with-explanation
class Solution(object): def splitArraySameAverage(self, A): if len(A)==1: return False global_avg = sum(A)/float(len(A)) for lenB in range(1, len(A)/2+1): if int(lenB*global_avg) == lenB*global_avg: if self.exist(lenB*global_avg, lenB, A): return True return False def exist(self, tosum, item_count, arr): if item_count==0: return False if tosum else True if item_count > len(arr) or not arr: return False if any([self.exist(tosum-arr[0], item_count-1, arr[1:]), self.exist(tosum, item_count, arr[1:])]): return True return False
split-array-with-same-average
Simple python with explanation
licaiuu
26
4,200
split array with same average
805
0.259
Hard
13,097
https://leetcode.com/problems/split-array-with-same-average/discuss/663594/Python-Lee215's-solution-with-explanations-and-added-memorization-pass-new-case
class Solution: def splitArraySameAverage(self, A: List[int]) -> bool: # A subfunction that see if total k elements sums to target # target is the goal, k is the number of elements in set B, i is the index we have traversed through so far mem = {} def find(target, k, i): # if we are down searching for k elements in the array, see if the target is 0 or not. This is a basecase if k == 0: return target == 0 # if the to-be selected elements in B (k) + elements we have traversed so far is larger than total length of A # even if we choose all elements, we don't have enough elements left, there should be no valid answer. if k + i > len(A): return False if (target, k, i) in mem: return mem[(target, k, i)] # if we choose the ith element, the target becomes target - A[i] for total sum # if we don't choose the ith element, the target doesn't change mem[(target - A[i], k - 1, i + 1)] = find(target - A[i], k - 1, i + 1) or find(target, k, i + 1) return mem[(target - A[i], k - 1, i + 1)] n, s = len(A), sum(A) # Note that the smaller set has length j ranging from 1 to n//2+1 # we iterate for each possible length j of array B from length 1 to length n//2+1 # if s*j%n, which is the sum of the subset, it should be an integer, so we only proceed to check if s * j % n == 0 # we check if we can find target sum s*j//n (total sum of j elements that sums to s*j//n) return any(find(s * j // n, j, 0) for j in range(1, n // 2 + 1) if s * j % n == 0)
split-array-with-same-average
[Python] Lee215's solution with explanations and added memorization [pass new case]
lichuan199010
9
1,300
split array with same average
805
0.259
Hard
13,098
https://leetcode.com/problems/split-array-with-same-average/discuss/471354/Python-3-DP-solution
class Solution: def splitArraySameAverage(self, A: List[int]) -> bool: A.sort() DP=[set() for _ in range(len(A)//2+1)] #DP[i] stores the all available sum with i items in a bracket all_sum=sum(A) DP[0]=set([0]) for item in A: #iterate over items in the list for count in range(len(DP)-2,-1,-1): # iterate backwards w.r.t. the bracket size if len(DP[count])>0: # if DP[i] is not empty, then update DP[i+1] by adding the current item into all sums in DP[i] for a in DP[count]: DP[count+1].add(a+item) for size in range(1,len(DP)): if all_sum*size/len(A) in DP[size]: return True return False
split-array-with-same-average
Python 3 DP solution
wangzi100
8
892
split array with same average
805
0.259
Hard
13,099