post_href
stringlengths 57
213
| python_solutions
stringlengths 71
22.3k
| slug
stringlengths 3
77
| post_title
stringlengths 1
100
| user
stringlengths 3
29
| upvotes
int64 -20
1.2k
| views
int64 0
60.9k
| problem_title
stringlengths 3
77
| number
int64 1
2.48k
| acceptance
float64 0.14
0.91
| difficulty
stringclasses 3
values | __index_level_0__
int64 0
34k
|
---|---|---|---|---|---|---|---|---|---|---|---|
https://leetcode.com/problems/count-asterisks/discuss/2209938/Python-or-faster-than-99 | class Solution:
def countAsterisks(self, s: str) -> int:
strs = s.split('|')
count = 0
final_string = ''.join(strs[i] for i in range(0,len(strs)+1,2))
for ch in final_string:
if ch=='*':
count += 1
return count | count-asterisks | Python | faster than 99% | NiketaM | 0 | 37 | count asterisks | 2,315 | 0.825 | Easy | 31,900 |
https://leetcode.com/problems/count-asterisks/discuss/2200503/Python-simple-solution | class Solution:
def countAsterisks(self, s: str) -> int:
arr = [x for x in s.split('|')]
ans = [arr[x] for x in range(len(arr)) if x%2 == 0]
return (''.join(ans)).count('*') | count-asterisks | Python simple solution | StikS32 | 0 | 22 | count asterisks | 2,315 | 0.825 | Easy | 31,901 |
https://leetcode.com/problems/count-asterisks/discuss/2199105/Python3-or-Faster-than-100... | class Solution:
def countAsterisks(self, s: str) -> int:
switch = False
cnt = 0
for c in s:
if c == '|':
switch = not switch
if c == '*' and not switch:
cnt += 1
return cnt | count-asterisks | Python3 | Faster than 100%... | anels | 0 | 7 | count asterisks | 2,315 | 0.825 | Easy | 31,902 |
https://leetcode.com/problems/count-asterisks/discuss/2198092/python-3-or-simple-one-pass-solution | class Solution:
def countAsterisks(self, s: str) -> int:
flag = True
res = 0
for c in s:
if c == '|':
flag = not flag
continue
res += c == '*' and flag
return res | count-asterisks | python 3 | simple one pass solution | dereky4 | 0 | 19 | count asterisks | 2,315 | 0.825 | Easy | 31,903 |
https://leetcode.com/problems/count-asterisks/discuss/2197084/One-Liner-Python3-beats-100 | class Solution:
def countAsterisks(self, s: str) -> int:
ls=s.split("|")
return sum([ls[i].count("*") for i in range(0,len(ls),2)]) | count-asterisks | One Liner Python3 beats 100% | svr300 | 0 | 6 | count asterisks | 2,315 | 0.825 | Easy | 31,904 |
https://leetcode.com/problems/count-asterisks/discuss/2196863/Python-or-Easy-and-Understanding | class Solution:
def countAsterisks(self, s: str) -> int:
check=True
ans=0
n=len(s)
for i in range(n):
ch=s[i]
if(ch=='|'):
check=not(check)
if(check==True):
if(ch=='*'):
ans+=1
return ans | count-asterisks | Python | Easy & Understanding | backpropagator | 0 | 17 | count asterisks | 2,315 | 0.825 | Easy | 31,905 |
https://leetcode.com/problems/count-asterisks/discuss/2195999/Python-Way | class Solution:
def countAsterisks(self, s: str) -> int:
s = list(s)
stackA, stackB = [], []
countTatal, count = 0, 0
for letter in s:
if letter == "|" or letter == "*":
stackA.append(letter)
if letter == "*":
countTatal += 1
for i in stackA:
if stackB and i == "|":
stackB.pop()
elif i == '|':
stackB.append(i)
elif stackB and i == "*":
count += 1
return countTatal - count | count-asterisks | Python Way | YangJenHao | 0 | 10 | count asterisks | 2,315 | 0.825 | Easy | 31,906 |
https://leetcode.com/problems/count-asterisks/discuss/2195908/Python3-One-Line-Sum-Odd-Indexed-Substrings | class Solution:
def countAsterisks(self, s: str) -> int:
return sum([str_.count('*') for str_ in s.split('|')[::2]]) | count-asterisks | [Python3] One Line - Sum Odd Indexed Substrings | 0xRoxas | 0 | 31 | count asterisks | 2,315 | 0.825 | Easy | 31,907 |
https://leetcode.com/problems/count-asterisks/discuss/2195881/python | class Solution:
def countAsterisks(self, s: str) -> int:
result = 0
for i, chunk in enumerate(s.split("|")):
if i % 2 == 0:
result += chunk.count("*")
return result | count-asterisks | python | emersonexus | 0 | 26 | count asterisks | 2,315 | 0.825 | Easy | 31,908 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2199190/Simple-and-easy-to-understand-using-dfs-with-explanation-Python | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
def dfs(graph,node,visited):
visited.add(node)
self.c += 1
for child in graph[node]:
if child not in visited:
dfs(graph, child, visited)
#build graph
graph = {}
for i in range(n):
graph[i] = []
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
visited = set()
count = 0
totalNodes = 0
#run dfs in unvisited nodes
for i in range(n):
if i not in visited:
self.c = 0
dfs(graph, i, visited)
count += totalNodes*self.c # result
totalNodes += self.c # total nodes visited
return count | count-unreachable-pairs-of-nodes-in-an-undirected-graph | Simple and easy to understand using dfs with explanation [Python] | ratre21 | 8 | 217 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,909 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2206955/Python-DSU-or-Easy-to-understand-code | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
class dsu:
def __init__(self,n):
self.parent=[i for i in range(n)]
self.size=[1]*n
def find(self,x):
if x!=self.parent[x]:self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u!=v:
if self.size[u]<self.size[v]:
u,v=v,u
self.size[u]+=self.size[v]
self.size[v]=0
self.parent[v]=u
def cout(self):
mp=defaultdict(int)
for i in range(n):
mp[self.find(i)]+=1
return mp
d=dsu(n)
for u,v in edges:
if d.find(u)!=d.find(v):
d.union(u,v)
mp=d.cout()
ans=0
for i in mp:
ans+=(mp[i]*(n-mp[i]))
return ans//2 | count-unreachable-pairs-of-nodes-in-an-undirected-graph | Python DSU | Easy to understand code | neelmehta0086 | 5 | 123 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,910 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2204310/Python-or-connected-components-or-dfs | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
graph=[]
for i in range(n):
graph.append([])
for i,j in edges:
graph[i].append(j)
graph[j].append(i)
visited=[0]*n
def dfs(graph,i,visited):
if graph[i]==[]:
return
for neigh in graph[i]:
if not visited[neigh]:
visited[neigh]=1
self.count+=1
dfs(graph,neigh,visited)
tot=0
prev=0
for i in range(n):
if not visited[i]:
visited[i]=1
self.count=1
dfs(graph,i,visited)
tot+=prev*self.count
prev+=self.count
return tot | count-unreachable-pairs-of-nodes-in-an-undirected-graph | Python | connected components | dfs | anjalianupam23 | 1 | 94 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,911 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2196173/Python-or-DFS-or-Easy-Solution | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
vis = [True]*n
adj = [[] for i in range(n)]
for i in edges:
adj[i[0]].append(i[1])
adj[i[1]].append(i[0])
components = []
def dfs(v):
if not vis[v]:
return
vis[v] = False
components[-1] += 1
for i in adj[v]:
dfs(i)
for vtx in range(n):
if vis[vtx]:
components.append(0)
dfs(vtx)
ans = 0
curr = n
for i in components:
ans += (curr-i)*i
curr -= i
return ans | count-unreachable-pairs-of-nodes-in-an-undirected-graph | Python | DFS | Easy Solution | arjuhooda | 1 | 111 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,912 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2195956/Python3-union-find | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
parent = list(range(n))
def find(p):
if parent[p] != p: parent[p] = find(parent[p])
return parent[p]
for p, q in edges:
prt, qrt = find(p), find(q)
if prt != qrt: parent[prt] = qrt
freq = Counter(find(p) for p in range(n))
return sum(v*(n-v) for v in freq.values())//2 | count-unreachable-pairs-of-nodes-in-an-undirected-graph | [Python3] union-find | ye15 | 1 | 19 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,913 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2835010/Python-easy-to-read-and-understand-or-DFS | class Solution:
def dfs(self, graph, node, visit):
for nei in graph[node]:
if nei not in visit:
visit.add(nei)
self.cnt += 1
self.dfs(graph, nei, visit)
def countPairs(self, n: int, edges: List[List[int]]) -> int:
graph = {i:[] for i in range(n)}
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
#print(graph.items())
sums, ans = 0, 0
visit = set()
for i in range(n):
if i not in visit:
visit.add(i)
self.cnt = 1
self.dfs(graph, i, visit)
ans += sums*self.cnt
sums += self.cnt
return ans | count-unreachable-pairs-of-nodes-in-an-undirected-graph | Python easy to read and understand | DFS | sanial2001 | 0 | 2 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,914 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2702674/Union-Find-python-solution | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
parent = [i for i in range(n)] # initially all nodes are independent
rank = [0]*n # initial rank will be same
# finding super parent
def find_parent(node):
if node != parent[node]:
parent[node] = find_parent(parent[node])
return parent[node]
# union nodes of the same component by rank
def union(u, v):
u = find_parent(u)
v = find_parent(v)
if rank[u] < rank[v]:
parent[u] = v
elif rank[v] < rank[u]:
parent[v] = u
else:
parent[v] = u
rank[u] += 1
# main
for u, v in edges:
union(u, v)
parent = [find_parent(i) for i in parent] # replacing every node by its superparent
ans = 0
for i in Counter(parent).values(): # number of nodes in each component
ans += i* (n - i)
return ans//2 | count-unreachable-pairs-of-nodes-in-an-undirected-graph | Union-Find python solution | Tensor08 | 0 | 6 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,915 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2334044/python-3-or-union-find | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
parent = [i for i in range(n)]
rank = [1] * n
def find(i):
while i != parent[i]:
parent[i] = i = parent[parent[i]]
return i
def union(i, j):
i, j = find(i), find(j)
if i == j:
return 0
pairs = rank[i] * rank[j]
if rank[i] >= rank[j]:
parent[j] = i
rank[i] += rank[j]
else:
parent[i] = j
rank[j] += rank[i]
return pairs
return math.comb(n, 2) - sum(union(i, j) for i, j in edges) | count-unreachable-pairs-of-nodes-in-an-undirected-graph | python 3 | union find | dereky4 | 0 | 78 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,916 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2219347/Find-groups-of-connected-nodes-68-speed | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
neighbors = {i: set() for i in range(n)}
for a, b in edges:
neighbors[a].add(b)
neighbors[b].add(a)
nodes = set(range(n))
double_count = 0
while nodes:
start = nodes.pop()
group = {start}
frontier = {start}
while frontier:
new_frontier = set()
for node in frontier:
for new_node in neighbors[node]:
if new_node in nodes:
nodes.remove(new_node)
group.add(new_node)
new_frontier.add(new_node)
frontier = new_frontier
double_count += len(group) * (n - len(group))
return double_count // 2 | count-unreachable-pairs-of-nodes-in-an-undirected-graph | Find groups of connected nodes, 68% speed | EvgenySH | 0 | 36 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,917 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2196166/Python-or-Simple-DFS-to-identify-Connected-Components-or-O(n) | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
adjList = defaultdict(list)
for a, b in edges:
adjList[a].append(b)
adjList[b].append(a)
def dfs(src):
if src in visit:
return 0
visit.add(src)
area = 1
for nei in adjList[src]:
if nei not in visit:
area += dfs(nei)
return area
visit = set()
areas = []
for i in range(n):
if i not in visit:
res = dfs(i)
areas.append(res)
if len(areas) <= 1:
return 0
totalSum = sum(areas)
res = 0
prefixSum = 0
for a in areas[:-1]:
prefixSum += a
res += a*(totalSum-prefixSum)
return res | count-unreachable-pairs-of-nodes-in-an-undirected-graph | Python | Simple DFS to identify Connected Components | O(n) | Tanayk | 0 | 22 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,918 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2196105/Python3-Union-Find-or-Visual-Explanation | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
#Initialize DSU
dsu = DSU(n)
res = 0
#Union edges
for u, v in edges:
dsu.union(u, v)
groups = defaultdict(int)
#Getting number of nodes per group
for i in range(n):
groups[dsu.find(i)] += 1
#Calculating pairs
nodes_seen = 0
for group_cnt in groups.values():
res += group_cnt * (n - group_cnt - nodes_seen)
nodes_seen += group_cnt
return res
class DSU:
def __init__(self, size):
self.p = [idx for idx in range(size)]
self.rank = [0 for _ in range(size)]
def find(self, i):
j = self.p[i]
while j != self.p[j]:
self.p[j] = self.p[self.p[j]]
j = self.p[j]
return self.p[j]
def union(self, i, j):
i, j = self.find(i), self.find(j)
if i == j:
return False
if self.rank[i] > self.rank[j]:
self.p[j] = i
self.rank[i] += self.rank[j]
else:
self.p[i] = j
self.rank[j] += self.rank[i]
return True | count-unreachable-pairs-of-nodes-in-an-undirected-graph | [Python3] Union Find | Visual Explanation | 0xRoxas | 0 | 43 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,919 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2196091/Python-Union-Find | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
result = 0
parent = collections.defaultdict()
for node in range(n):
parent[node] = node
def find_parent(node):
if parent[node] != node:
parent[node] = find_parent(parent[node])
return parent[node]
def union(node1, node2):
parent1 = find_parent(node1)
parent2 = find_parent(node2)
if parent1 != parent2:
parent[parent2] = parent1
for a, b in edges:
union(a, b)
counter = collections.Counter([find_parent(node) for node in parent])
nums = sorted([val for val in counter.values()], reverse = True)
_sum = sum(nums)
sum_so_far = 0
if len(nums) >= 2:
for num in nums:
sum_so_far += num
result += num * (_sum - sum_so_far)
return result | count-unreachable-pairs-of-nodes-in-an-undirected-graph | [Python] Union Find | emersonexus | 0 | 48 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,920 |
https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2195918/python-dfs-or-comments | class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
g = collections.defaultdict(list)
seen = set()
res = []
# generate an adjacency list from edges
for a, b in edges:
g[a].append(b)
g[b].append(a)
# count nodes in each disjoint graph segments
def dfs(node):
if node in seen:
return
self.count += 1
seen.add(node)
for nei in g[node]:
dfs(nei)
return
for i in range(n):
self.count = 0
if i not in seen:
dfs(i)
res.append(self.count)
self.count = 0
# returning sum of product all unique pairs
# (a1+a2+a3+...)^2 = (a1^2 + a2^2 + ...) + 2*(a1.a2 + a2.a3 + ...)
# using above formula we can return the desired result
return (sum(res)**2 - sum(num**2 for num in res))//2 | count-unreachable-pairs-of-nodes-in-an-undirected-graph | python dfs | comments | abkc1221 | 0 | 25 | count unreachable pairs of nodes in an undirected graph | 2,316 | 0.386 | Medium | 31,921 |
https://leetcode.com/problems/maximum-xor-after-operations/discuss/2366537/Python3-oror-1-line-bit-operations-w-explanation-oror-TM%3A-8887 | class Solution:
def maximumXOR(self, nums: List[int]) -> int:
return reduce(lambda x,y: x|y, nums)
class Solution:
def maximumXOR(self, nums: List[int]) -> int:
return reduce(or_, nums)
class Solution:
def maximumXOR(self, nums: List[int]) -> int:
ans = 0
for n in nums:
ans |= n
return ans | maximum-xor-after-operations | Python3 || 1 line, bit operations, w/ explanation || T/M: 88%/87% | warrenruud | 5 | 88 | maximum xor after operations | 2,317 | 0.786 | Medium | 31,922 |
https://leetcode.com/problems/maximum-xor-after-operations/discuss/2195923/Python3-bit-operation | class Solution:
def maximumXOR(self, nums: List[int]) -> int:
return reduce(or_, nums) | maximum-xor-after-operations | [Python3] bit operation | ye15 | 1 | 11 | maximum xor after operations | 2,317 | 0.786 | Medium | 31,923 |
https://leetcode.com/problems/maximum-xor-after-operations/discuss/2197305/Python-one-liner | class Solution:
def maximumXOR(self, nums: List[int]) -> int:
return reduce(operator.or_, nums) | maximum-xor-after-operations | Python one liner | blue_sky5 | 0 | 11 | maximum xor after operations | 2,317 | 0.786 | Medium | 31,924 |
https://leetcode.com/problems/maximum-xor-after-operations/discuss/2197143/2-approaches-Python-Easy-Understanding | class Solution(object):
def maximumXOR(self, nums):
#approach1
# lis=[0 for _ in range(32)]
# for i in range(32):
# for j in nums:
# if 1<<i & j:
# lis[i]=1
# break
# s=0
# val=1
# for i in range(32):
# if lis[i]:
# s+=val
# val*=2
# return s
#approach2
#as we know we have to find the xor of all the elements
#so we can observe there that we are calculating the sum only(of the odd bits)
#lets take example
#[3,2,4,6]
#3-0011
#2-0010
#4-0100
#6-0110
#so we have to find only odd bit sum
#so we make the 6th 3rd bit 0 to make the odd bit at the 3rd position
#and we know that if there exist 1 in any number at that position then we can make others 0 and take the first one to make the odd
#so here we are taking the or (which will take only the set bits - as we know 0 or 0 means 0 and 1 for all other cases)
r = 0
for num in nums:
r |= num
return r
"""
:type nums: List[int]
:rtype: int
""" | maximum-xor-after-operations | 2 approaches - Python Easy Understanding | prateekgoel7248 | 0 | 15 | maximum xor after operations | 2,317 | 0.786 | Medium | 31,925 |
https://leetcode.com/problems/maximum-xor-after-operations/discuss/2196898/Python-or-Easy-and-Understanding | class Solution:
def maximumXOR(self, nums: List[int]) -> int:
ans=nums[0]
n=len(nums)
for i in range(1,n):
ans|=nums[i]
return ans | maximum-xor-after-operations | Python | Easy & Understanding | backpropagator | 0 | 13 | maximum xor after operations | 2,317 | 0.786 | Medium | 31,926 |
https://leetcode.com/problems/maximum-xor-after-operations/discuss/2195975/Python-Easy-to-understand-solution | class Solution:
def maximumXOR(self, nums: List[int]) -> int:
res = 0
for i in nums:
res = res | i
return res | maximum-xor-after-operations | [Python] Easy to understand solution | samirpaul1 | 0 | 24 | maximum xor after operations | 2,317 | 0.786 | Medium | 31,927 |
https://leetcode.com/problems/maximum-xor-after-operations/discuss/2195954/Python-or-Super-Simple-or-One-Line | class Solution:
def maximumXOR(self, nums: List[int]) -> int:
return reduce(lambda x,y:x|y, nums) | maximum-xor-after-operations | Python | Super-Simple | One-Line | rajabi | 0 | 23 | maximum xor after operations | 2,317 | 0.786 | Medium | 31,928 |
https://leetcode.com/problems/number-of-distinct-roll-sequences/discuss/2196009/Python3-top-down-dp | class Solution:
def distinctSequences(self, n: int) -> int:
@lru_cache
def fn(n, p0, p1):
"""Return total number of distinct sequences."""
if n == 0: return 1
ans = 0
for x in range(1, 7):
if x not in (p0, p1) and gcd(x, p0) == 1: ans += fn(n-1, x, p0)
return ans % 1_000_000_007
return fn(n, -1, -1) | number-of-distinct-roll-sequences | [Python3] top-down dp | ye15 | 2 | 48 | number of distinct roll sequences | 2,318 | 0.562 | Hard | 31,929 |
https://leetcode.com/problems/number-of-distinct-roll-sequences/discuss/2195931/Python3-or-Clear-Top-Down-DP | class Solution:
def distinctSequences(self, n: int) -> int:
mod = 1_000_000_007
# edge case
if n == 1: return 6
# to create possible adjacent pairs
next_option = {
1: (2, 3, 4, 5, 6),
2: (1, 3, 5),
3: (1, 2, 4, 5),
4: (1, 3, 5),
5: (1, 2, 3, 4, 6),
6: (1, 5)
}
# create dictionary where the key is allowed adjacent pairs and the value is list of third elment after the pair
allowed_third = defaultdict(list)
for i, j, k in product(list(range(1, 7)), repeat=3):
if k != i and j in next_option[i] and k in next_option[j]:
allowed_third[(i, j)] += k,
# memoize the answers
@cache
def get_help(i, j, rem):
ans = 0
if rem == 0:
return 1
for k in allowed_third[(i, j)]:
ans += get_help(j, k, rem - 1) % mod
return ans
ans = 0
for i, j in allowed_third:
ans += get_help(i, j, n - 2) % mod
return ans % mod | number-of-distinct-roll-sequences | Python3] | Clear Top Down DP | yag313 | 1 | 47 | number of distinct roll sequences | 2,318 | 0.562 | Hard | 31,930 |
https://leetcode.com/problems/number-of-distinct-roll-sequences/discuss/2196221/Python-or-Top-down-dfs-w-cache | class Solution:
def distinctSequences(self, n: int) -> int:
M = 10**9 + 7
@lru_cache()
def dfs(i, prev, prevOfPrev):
if i == n:
return 1
res = 0
for dice in [1, 2, 3, 4, 5, 6]:
if dice != prev and dice != prevOfPrev and (prev == -1 or math.gcd(prev, dice) == 1):
res += (dfs(i+1, dice, prev) % M)
return res
return dfs(0, -1, -1) % M | number-of-distinct-roll-sequences | Python | Top-down dfs w/ cache | Tanayk | 0 | 15 | number of distinct roll sequences | 2,318 | 0.562 | Hard | 31,931 |
https://leetcode.com/problems/number-of-distinct-roll-sequences/discuss/2196209/Python-DP-%2BDFS | class Solution:
def distinctSequences(self, n: int) -> int:
edgeList = {
1: [2,3,4,5,6],
2:[1,3, 5],
3:[1, 2, 5, 4],
4:[1, 3, 5],
5:[1,2,3,4,6],
6:[1, 5]
}
dp = dict()
def solve(curr_node, prev_node, sequence_length):
if sequence_length == 1:
return 1
if (curr_node, prev_node, sequence_length) in dp:
return dp[(curr_node, prev_node, sequence_length)]
count = 0
for node in edgeList[curr_node]:
if node != prev_node:
count += solve(node, curr_node, sequence_length-1)
dp[(curr_node, prev_node, sequence_length)] =count
return count
ans = 0
for i in range(1, 7):
ans += solve(i, -1, n)
ans = ans % int(1e9+7)
return ans | number-of-distinct-roll-sequences | [Python] DP +DFS | vikrant-sinha | 0 | 19 | number of distinct roll sequences | 2,318 | 0.562 | Hard | 31,932 |
https://leetcode.com/problems/number-of-distinct-roll-sequences/discuss/2195886/Python3-Easy-Solution-oror-Easy-to-understand | class Solution:
def distinctSequences(self, n: int) -> int:
MOD = 10**9 + 7
@cache
def dfs(i, prev, prev_prev):
if i >= n:
return 1
result = 0
for dice in range(1, 7):
if dice == prev or dice == prev_prev:
continue
if dice % 2 == 0 and prev % 2 == 0:
continue
if dice % 3 == 0 and prev % 3 == 0:
continue
result += dfs(i + 1, dice, prev)
return result % MOD
return dfs(0, -1, -1) | number-of-distinct-roll-sequences | Python3 Easy Solution || Easy to understand | pramodjoshi_222 | 0 | 17 | number of distinct roll sequences | 2,318 | 0.562 | Hard | 31,933 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2368873/Easiest-Python-solution-you-will-find.......-Single-loop | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
a=0
j=len(grid)-1
for i in range(0,len(grid)):
if grid[i][i]==0 or grid[i][j]==0:
return False
else:
if i!=j:
a=grid[i][i]+grid[i][j]
elif i==j:
a=grid[i][i]
if a!=sum(grid[i]):
return False
j-=1
return True | check-if-matrix-is-x-matrix | Easiest Python solution you will find....... Single loop | guneet100 | 1 | 46 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,934 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2211546/Python-simple-solution | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
n = len(grid)
for i in range(n):
for j in range(n):
if i == j or i + j == n-1:
if grid[i][j] == 0:
return False
else:
if grid[i][j] != 0:
return False
return True | check-if-matrix-is-x-matrix | Python simple solution | byuns9334 | 1 | 67 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,935 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2846132/python-easy-solution | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
for i in range(len(grid)):
if grid[i][i] == 0 or grid[i][len(grid)-1-i]==0:
return False
for j in range(len(grid)):
if j==i or j==len(grid)-1-i:
continue
if grid[i][j] != 0:
return False
return True | check-if-matrix-is-x-matrix | python easy solution | Cosmodude | 0 | 1 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,936 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2808956/Simple-Python-Solution | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
r = len(grid)
c = len(grid[0])
for m in range(r):
for n in range(c):
if (m==n and grid[m][n]==0) or (m==((r-1)-n) and grid[m][n]==0):return False
elif not(m==n or m==((r-1)-n)) and grid[m][n]!=0:return False
return True | check-if-matrix-is-x-matrix | Simple Python Solution | user0160h | 0 | 1 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,937 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2780335/python | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
n=len(grid)
f=True
for i in range(n):
if grid[i][i] == 0 :
return False
for i in range(n):
for j in range(n):
if i!=j and (i+j) != (n-1):
if grid[i][j] != 0:
return False
if i+j == (n-1):
if grid[i][j] == 0:
return False
return True | check-if-matrix-is-x-matrix | python | sarvajnya_18 | 0 | 2 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,938 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2749234/When-checking-diagonals-assign-elements-to-zero-make-checking-other-elements-easier. | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
"""TC: O(n), SC: O(1)"""
# check diagonals
for i in range(len(grid)):
if grid[i][i] == 0 or grid[-i-1][i] == 0:
return False
else: # make checking other elements easier
grid[i][i] = 0
grid[-i-1][i] = 0
# check other elements
for row in grid:
if any(elem != 0 for elem in row):
return False
return True | check-if-matrix-is-x-matrix | When checking diagonals, assign elements to zero, make checking other elements easier. | woora3 | 0 | 3 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,939 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2624965/Python-solution | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
for i in range(len(grid)):
for j in range(len(grid)):
if i == j or i + j == len(grid) - 1:
if grid[i][j] == 0:
return False
else:
if grid[i][j] != 0:
return False
return True | check-if-matrix-is-x-matrix | Python solution | samanehghafouri | 0 | 9 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,940 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2391547/Python-easy | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
l=len(grid)
for i in range(l):
for j in range(l):
if (grid[i][j] != 0) and ((i==j) or (i+j==l-1)):
pass
elif (grid[i][j] == 0) and ((i!=j) and (i+j!=l-1)):
pass
else:
return False
return True | check-if-matrix-is-x-matrix | Python easy | sunakshi132 | 0 | 63 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,941 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2373205/easy-python-solution | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
n=len(grid)
for i in range(n):
for j in range(n):
if i==j or j==n-i-1:
if grid[i][j]==0: return False
else:
if grid[i][j]!=0: return False
return True | check-if-matrix-is-x-matrix | easy python solution | keertika27 | 0 | 50 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,942 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2227829/Simplest-Approach-and-Solution | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
firstDiagnol = 0
secondDiagnol = 0
remaining = 0
m, n = len(grid), len(grid[0])
for i in range(m):
if grid[i][i] != 0:
firstDiagnol += 1
for i in range(m):
if grid[i][n - i - 1] != 0:
secondDiagnol += 1
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
remaining += 1
if n%2 == 0:
return firstDiagnol == n and secondDiagnol == n and remaining == (n**2 - 2*n)
else:
return firstDiagnol == n and secondDiagnol == n and remaining == (n**2 - (2*n - 1)) | check-if-matrix-is-x-matrix | Simplest Approach and Solution | Vaibhav7860 | 0 | 45 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,943 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2212940/Python-simple-solution | class Solution:
def checkXMatrix(self, g: List[List[int]]) -> bool:
for i in range(len(g)):
if g[i][i] == 0 or g[i][len(g)-1-i] == 0:
return False
return (len(g)*2 if len(g)%2 == 0 else (len(g)*2)-1) == sum([1 for y in g for x in y if x]) | check-if-matrix-is-x-matrix | Python simple solution | StikS32 | 0 | 28 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,944 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2208653/Python3-simple-solution | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
a = 0
b = len(grid)-1
for i in range(len(grid)):
for j in range(len(grid)):
if (i == j) or (i == a and j == b):
if grid[i][j] == 0:
return False
elif grid[i][j] != 0:
return False
a += 1
b -= 1
return True | check-if-matrix-is-x-matrix | Python3 simple solution | EklavyaJoshi | 0 | 21 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,945 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2200739/Python | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
n = len(grid)
for r in range(n):
for c in range(n):
if r == c or c == n - 1 - r:
if grid[r][c] == 0:
return False
elif grid[r][c] != 0:
return False
return True | check-if-matrix-is-x-matrix | Python | blue_sky5 | 0 | 33 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,946 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2200640/One-pass-100-speed | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
n1 = len(grid) - 1
for r, row in enumerate(grid):
for c, v in enumerate(row):
if r == c or r + c == n1:
if v == 0:
return False
elif v != 0:
return False
return True | check-if-matrix-is-x-matrix | One pass, 100% speed | EvgenySH | 0 | 17 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,947 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2199026/Python-easy-implementation | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
for i in range(0,len(grid)):
for j in range(0,len(grid[0])):
if i==j or i+j==len(grid[0])-1:
if grid[i][j]!=0:pass
else:return False
else:
if grid[i][j]!=0:
return False
return True | check-if-matrix-is-x-matrix | Python easy implementation | Sadika12 | 0 | 18 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,948 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2198405/Python3-enumerate-elements | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
n = len(grid)
for i, row in enumerate(grid):
for j, x in enumerate(row):
if (i == j or i+j == n-1) and not x or i != j and i+j != n-1 and x: return False
return True | check-if-matrix-is-x-matrix | [Python3] enumerate elements | ye15 | 0 | 12 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,949 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2198373/Python-Simple-Python-Solution-Using-Two-Approach | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
length = len(grid)
diagonal = []
for i in range(length):
diagonal.append([i,i])
diagonal.append([i,length-1-i])
if grid[i][i] == 0 or grid[i][length-1-i] == 0:
return False
for j in range(length):
for k in range(length):
if [j,k] not in diagonal and grid[j][k] != 0:
return False
return True | check-if-matrix-is-x-matrix | [ Python ] ✅✅ Simple Python Solution Using Two Approach 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 19 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,950 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2198373/Python-Simple-Python-Solution-Using-Two-Approach | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
length = len(grid)
for row in range(length):
for col in range(length):
if row == col or row + col == length - 1:
if grid[row][col] == 0:
return False
else:
if grid[row][col] != 0:
return False
return True | check-if-matrix-is-x-matrix | [ Python ] ✅✅ Simple Python Solution Using Two Approach 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 19 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,951 |
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2198131/Python3-Straight-Forward-Check | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
n = len(grid)
for i in range(n):
for j in range(n):
if i == j or i == n - j - 1:
if grid[i][j] == 0:
return False
else:
if grid[i][j] != 0:
return False
return True | check-if-matrix-is-x-matrix | [Python3] Straight Forward Check | 0xRoxas | 0 | 31 | check if matrix is x matrix | 2,319 | 0.673 | Easy | 31,952 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198265/Python-Simple-Solution-or-O(n)-time-complexity-or-Basic-Approach-or-DP | class Solution:
def countHousePlacements(self, n: int) -> int:
pre,ppre = 2,1
if n==1:
return 4
for i in range(1,n):
temp = pre+ppre
ppre = pre
pre = temp
return ((pre)**2)%((10**9) + 7) | count-number-of-ways-to-place-houses | Python Simple Solution | O(n) time complexity | Basic Approach | DP | AkashHooda | 2 | 95 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,953 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198315/Python-or-Easy-Solution-or-Fibonacci-Pattern-or-O(n) | class Solution:
def countHousePlacements(self, n: int) -> int:
prev, pprev = 2,1
for i in range(1,n):
temp = pprev+prev
pprev= prev
prev = temp
return (prev**2)%(10**9+7) | count-number-of-ways-to-place-houses | Python | Easy Solution | Fibonacci Pattern | O(n) | arjuhooda | 1 | 36 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,954 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2450371/Python-easy-to-read-and-understand-or-dp | class Solution:
def countHousePlacements(self, n: int) -> int:
if n == 1:
return 4
t = [0 for _ in range(n)]
t[0], t[1] = 2, 3
for i in range(2, n):
t[i] = (t[i-1]+t[i-2])%(10**9 + 7)
return t[n-1]**2%(10**9 + 7) | count-number-of-ways-to-place-houses | Python easy to read and understand | dp | sanial2001 | 0 | 40 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,955 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2227885/Dynamic-Programming-oror-Simple-Approach | class Solution:
def countHousePlacements(self, n: int) -> int:
dpArray = [0]*(n + 1)
dpArray[0] = 1
dpArray[1] = 2
mod = 10**9 + 7
for i in range(2, n + 1):
dpArray[i] = dpArray[i - 1] + dpArray[i - 2]
dpArray[i] = dpArray[i] % mod
return (dpArray[n]**2) % mod | count-number-of-ways-to-place-houses | Dynamic Programming || Simple Approach | Vaibhav7860 | 0 | 116 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,956 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2225969/pyhton-oror-python3-oror-DP-oror-fibonacci-(with-explanation) | class Solution(object):
def countHousePlacements(self, n):
ans = self.fibonacci(n, {})
# n*2 plots
return (ans*ans) % (10**9+7)
def fibonacci(self, n, dp):
state = n
if n <= 1:
return n+1
if state in dp:
return dp[state]
else:
#fibonacci pattern
ans = self.fibonacci(n-1, dp) + self.fibonacci(n-2, dp)
dp[state] = ans
return ans | count-number-of-ways-to-place-houses | pyhton || python3 || DP || fibonacci (with explanation) | aul- | 0 | 53 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,957 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2219935/Python3-4-line-O(n)-DP-Solution | class Solution:
def countHousePlacements(self, n: int) -> int:
A, B, C, D = 1, 1, 1, 1
for t in range(1, n):
A, B, C, D = D, C + D, B + D, A + B + C + D
return (A + B + C + D) % (10**9 + 7) | count-number-of-ways-to-place-houses | Python3 4-line O(n) DP Solution | xxHRxx | 0 | 25 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,958 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2206457/Python3-DP-Solution-or-Visual-Explanation-or-Recurrence-Relation | class Solution:
def countHousePlacements(self, n: int) -> int:
#Rightmost slice type counts
a = [1] + [0]*(n - 1)
b = [1] + [0]*(n - 1)
c = [1] + [0]*(n - 1)
d = [1] + [0]*(n - 1)
for i in range(1, n):
a[i] = a[i - 1] + b[i - 1] + c[i - 1] + d[i - 1]
b[i] = a[i - 1] + c[i - 1]
c[i] = a[i - 1] + b[i - 1]
d[i] = a[i - 1]
return (a[n - 1] + b[n - 1] + c[n - 1] + d[n - 1]) % 1000000007 | count-number-of-ways-to-place-houses | [Python3] DP Solution | Visual Explanation | Recurrence Relation | 0xRoxas | 0 | 30 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,959 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2206457/Python3-DP-Solution-or-Visual-Explanation-or-Recurrence-Relation | class Solution:
def countHousePlacements(self, n: int) -> int:
dp = [1, 1] + [0]*(n - 1)
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return (dp[n] + dp[n-1])**2 % 1000000007 | count-number-of-ways-to-place-houses | [Python3] DP Solution | Visual Explanation | Recurrence Relation | 0xRoxas | 0 | 30 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,960 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2199047/Pythonor-without-recursionor-simple-DP | class Solution:
def countHousePlacements(self, n: int) -> int:
M=1000000007
def fibo (n):
l=[2,3]
sum=0
for i in range(2,n):
l.append(l[i-1]+l[i-2])
return l[n-1]
return ((fibo(n))**2)%M | count-number-of-ways-to-place-houses | Python| without recursion| simple DP | Sadika12 | 0 | 11 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,961 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2199042/Python-Solution-oror-Fibonacci-Series | class Solution:
def countHousePlacements(self, n: int) -> int:
def fib(n):
a=0
b=1
if n==1:
return b
else:
for i in range(2,n+1):
c=a+b
a=b
b=c
return b
return fib(n+2)**2%(10**9+7) | count-number-of-ways-to-place-houses | Python Solution || Fibonacci Series | a_dityamishra | 0 | 5 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,962 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198555/Fibonacci-sequence-somehow | class Solution:
def countHousePlacements(self, n: int) -> int:
fibbo = [1, 1]
while len(fibbo) < n + 2:
fibbo.append(fibbo[-1] + fibbo[-2])
return (fibbo[n + 1]**2) % (10**9 + 7) | count-number-of-ways-to-place-houses | Fibonacci sequence somehow | WoodlandXander | 0 | 7 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,963 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198516/Python-Simple-Python-Solution-Using-Fibonacci-Series | class Solution:
def countHousePlacements(self, n: int) -> int:
fibonacci = [1,2]
for i in range(1, n + 1):
fibonacci.append(fibonacci[i] + fibonacci[i-1])
return (fibonacci[n] * fibonacci[n]) % ((10**9)+7) | count-number-of-ways-to-place-houses | [ Python ] ✅✅ Simple Python Solution Using Fibonacci Series 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 12 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,964 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198489/Python3-Top-Down-DP | class Solution:
def countHousePlacements(self, n: int) -> int:
def dfs(plot, prev_put):
if plot == 0:
return 1
if (plot, prev_put) in memo:
return memo[(plot, prev_put)]
cnt = 0
if prev_put:
cnt = dfs(plot-1, False)
else:
cnt = dfs(plot-1, False)
cnt += dfs(plot-1, True)
memo[(plot, prev_put)] = cnt
return cnt
memo = {}
ans = dfs(n-1, False)
ans += dfs(n-1, True)
return (ans ** 2) % ((10**9) + 7) | count-number-of-ways-to-place-houses | Python3 Top-Down DP | BreadMuMu | 0 | 4 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,965 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198332/Python3-bottom-up-dp | class Solution:
def countHousePlacements(self, n: int) -> int:
f0 = f1 = 1
for _ in range(n): f0, f1 = f1, (f0+f1) % 1_000_000_007
return f1*f1 % 1_000_000_007 | count-number-of-ways-to-place-houses | [Python3] bottom-up dp | ye15 | 0 | 2 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,966 |
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198289/Python-solution-easy-2-pointer | class Solution:
def countHousePlacements(self, n: int) -> int:
mod = 1000000007
if n==1:
return 4
count_end = 1
count_space = 1
for i in range(2,n+1):
prev_end = count_end
prev_space = count_space
count_space = prev_end + prev_space
count_end =prev_space
ways = count_end + count_space
return (ways*ways)%mod | count-number-of-ways-to-place-houses | Python solution easy 2 pointer | adwtri2012 | 0 | 9 | count number of ways to place houses | 2,320 | 0.401 | Medium | 31,967 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198195/Python-or-Easy-to-Understand-or-With-Explanation-or-No-Kadane | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
# create a difference array between nums1 and nums2
# idea: find two subarray(elements are contiguous) in the diff
# one is the subarray that have the minimum negative sum
# another one is the subarray that have the maximum positive sum
# so there are four candidates for maximum score:
# 1. original_sum1
# 2. original_sum
# 3. original_sum1 - min_negative_sum
# 4. original_sum2 + max_positive_sum
original_sum1 = sum(nums1)
original_sum2 = sum(nums2)
diff = [num1 - num2 for num1, num2 in zip(nums1, nums2)]
min_negative_sum = float('inf')
max_positive_sum = - float('inf')
cur_negative_sum = 0
cur_positive_sum = 0
for val in diff:
cur_negative_sum += val
if cur_negative_sum > 0:
cur_negative_sum = 0
cur_positive_sum += val
if cur_positive_sum < 0:
cur_positive_sum = 0
min_negative_sum = min(min_negative_sum, cur_negative_sum)
max_positive_sum = max(max_positive_sum, cur_positive_sum)
return max(original_sum1 - min_negative_sum, original_sum2 + max_positive_sum, original_sum2, original_sum1) | maximum-score-of-spliced-array | Python | Easy to Understand | With Explanation | No Kadane | Mikey98 | 2 | 150 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,968 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198353/Python-or-Simple-Solution-or-Modified-Subarray-Sum-Approach | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
diff = [0]*n
for i in range(n):
diff[i] = nums1[i]-nums2[i]
mpos,mneg,pos,neg = 0,0,0,0
for i in range(n):
pos += diff[i]
if pos < 0:
pos = 0
neg += diff[i]
if neg > 0:
neg = 0
mpos = max(pos,mpos)
mneg = min(neg,mneg)
return max(sum(nums1)-mneg,sum(nums2)+mpos) | maximum-score-of-spliced-array | Python | Simple Solution | Modified Subarray Sum Approach | arjuhooda | 1 | 62 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,969 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198222/Python-Easy-Solution-or-Kadanes-Algo-or-O(N)-Time-Complexity | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
diff = [0]*len(nums1)
s1,s2=0,0
for i in range(len(nums1)):
diff[i] = nums1[i]-nums2[i]
s1+=nums1[i]
s2+=nums2[i]
mneg,mpos,neg,pos = 0,0,0,0
for i in range(len(nums1)):
neg+=diff[i]
pos+=diff[i]
if neg>0:
neg = 0
if pos<0:
pos = 0
mpos = max(pos,mpos)
mneg = min(neg,mneg)
return max(s1-mneg,s2+mpos) | maximum-score-of-spliced-array | Python Easy Solution | Kadanes Algo | O(N) Time Complexity | AkashHooda | 1 | 63 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,970 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2213720/Python3-or-Variation-of-Maximum-Subarray-Sum-or-Kadane-Algorithm | class Solution:
def maximumSubarraySum(self,arr):
currSum,retval=[0]*2
for i in range(len(arr)):
currSum=max(currSum+arr[i],arr[i])
retval=max(retval,arr[i],currSum)
return retval
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
n=len(nums1)
s1,s2=sum(nums1),sum(nums2)
diff1,diff2=[],[]
for i in range(n):
diff1.append(nums2[i]-nums1[i])
for i in range(n):
diff2.append(nums1[i]-nums2[i])
return max(s1+self.maximumSubarraySum(diff1),s2+self.maximumSubarraySum(diff2)) | maximum-score-of-spliced-array | [Python3] | Variation of Maximum-Subarray-Sum | Kadane Algorithm | swapnilsingh421 | 0 | 16 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,971 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2208040/Double-Kadane-oror-Easy-oror-Python | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
# Double Kadane
# T(c)=O(n)
# Either replace nums from arr1 or from arr2
# Then find maximum
n=len(nums1)
msfar1=0
msfar2=0
k_sum1=0
k_sum2=0
for i in range(n):
msfar1+=nums2[i]-nums1[i]
k_sum1=max(msfar1,k_sum1)
msfar2+=nums1[i]-nums2[i]
k_sum2=max(msfar2,k_sum2)
if msfar1<0:
msfar1=0
if msfar2<0:
msfar2=0
return max(sum(nums1)+k_sum1,sum(nums2)+k_sum2) | maximum-score-of-spliced-array | Double Kadane || Easy || Python | Aniket_liar07 | 0 | 13 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,972 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2205349/Python-Kadane's-algo.-Time%3A-O(N)-Space%3A-O(1) | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
def maximum_contiguous_subarray(nums1, nums2):
max_sum = sum_ = -math.inf
for n1, n2 in zip(nums1, nums2):
sum_ = max(sum_ + n2 - n1, n2 - n1)
max_sum = max(max_sum, sum_)
return max(max_sum, 0)
d1 = maximum_contiguous_subarray(nums1, nums2)
d2 = maximum_contiguous_subarray(nums2, nums1)
return max(sum(nums1) + d1, sum(nums2) + d2) | maximum-score-of-spliced-array | Python, Kadane's algo. Time: O(N)/ Space: O(1) | blue_sky5 | 0 | 9 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,973 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198723/max(sum1%2Bmax_dif21-sum2%2Bmax_dif12) | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
dif21, maxDif21, dif12, maxDif12 = 0, 0, 0, 0
for i in range(len(nums1)):
delta = nums2[i] - nums1[i]
dif21 = max(delta, dif21 + delta)
dif12 = max(-delta, dif12 - delta)
maxDif21 = max(dif21, maxDif21)
maxDif12 = max(dif12, maxDif12)
return max(sum(nums1)+maxDif21, sum(nums2)+maxDif12) | maximum-score-of-spliced-array | max(sum1+max_dif21, sum2+max_dif12) | torocholazzz | 0 | 22 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,974 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198688/python-3-or-simple-Kadane's-algorithm-solution | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
s1 = maxDiff1 = curDiff1 = s2 = maxDiff2 = curDiff2 = 0
for num1, num2 in zip(nums1, nums2):
s1 += num1
curDiff1 = max(curDiff1, 0) + num2 - num1
maxDiff1 = max(maxDiff1, curDiff1)
s2 += num2
curDiff2 = max(curDiff2, 0) + num1 - num2
maxDiff2 = max(maxDiff2, curDiff2)
return max(s1 + maxDiff1, s2 + maxDiff2) | maximum-score-of-spliced-array | python 3 | simple Kadane's algorithm solution | dereky4 | 0 | 13 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,975 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198625/Pythonor-Dynamic-Programmingor-O(N)-or-simple-solution | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
num1=nums1.copy()
num2=nums2.copy()
nm1,nm2,sum1,sum2=[],[],[],[]
for i in range(len(nums1)):
ans=nums1[i]-nums2[i]
nm1.append(-ans)
nm2.append(ans)
sm1,s1,e1,mxsm1,sm2,s2,e2,mxsm2,start1,start2=0,0,0,0,0,0,0,0,0,0
for i in range(len(nm1)):
if sm1<=0:
s1=i
sm1=0
if sm1+nm1[i]>0:
sm1=sm1+nm1[i]
if sm1>mxsm1:
mxsm1=sm1
e1=i
start1=s1
else:
sm1=0
if sm2<=0 and nm2[i]>0:
sm2=0
s2=i
if sm2+nm2[i]>0:
sm2=sm2+nm2[i]
if sm2>mxsm2:
mxsm2=sm2
e2=i
start2=s2
else:
sm2=0
sum1.append(sm1)
sum2.append(sm2)
for i in range(start1,e1+1):
num1[i]=nums2[i]
for j in range(start2,e2+1):
num2[j]=nums1[j]
ans=max(sum(nums1),sum(nums2),sum(num1),sum(num2))
return (ans) | maximum-score-of-spliced-array | Python| Dynamic Programming| O(N) | simple solution | shahv74 | 0 | 10 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,976 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198446/Python3-easy-three-pass-solution | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
sum1 = sum(nums1)
sum2 = sum(nums2)
diff1, diff2 = [0 for _ in range(len(nums1))], [0 for _ in range(len(nums2))]
for i in range(len(nums1)):
diff1[i] = nums2[i] - nums1[i]
diff2[i] = nums1[i] - nums2[i]
maxdiff1, curr_diff, left = float('-inf'), 0, 0
for i in range(len(diff1)):
curr_diff = max(curr_diff + diff1[i], diff1[i])
maxdiff1 = max(curr_diff, maxdiff1)
maxdiff2, curr_diff, left = float('-inf'), 0, 0
for i in range(len(diff2)):
curr_diff = max(curr_diff + diff2[i], diff2[i])
maxdiff2 = max(curr_diff, maxdiff2)
return max(sum1+maxdiff1, sum2+maxdiff2) | maximum-score-of-spliced-array | Python3 easy three pass solution | BreadMuMu | 0 | 6 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,977 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198314/Python3-greedy | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
prefix = minv = maxv = diff1 = diff2 = 0
for x1, x2 in zip(nums1, nums2):
prefix += x2-x1
minv = min(minv, prefix)
maxv = max(maxv, prefix)
diff1 = max(diff1, prefix - minv)
diff2 = max(diff2, maxv - prefix)
return max(sum(nums1)+diff1, sum(nums2)+diff2) | maximum-score-of-spliced-array | [Python3] greedy | ye15 | 0 | 9 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,978 |
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198314/Python3-greedy | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
v1 = v2 = m1 = m2 = 0
for x1, x2 in zip(nums1, nums2):
v1 = max(0, v1+x2-x1)
v2 = max(0, v2+x1-x2)
m1 = max(m1, v1)
m2 = max(m2, v2)
return max(sum(nums1)+m1, sum(nums2)+m2) | maximum-score-of-spliced-array | [Python3] greedy | ye15 | 0 | 9 | maximum score of spliced array | 2,321 | 0.554 | Hard | 31,979 |
https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2198386/Python3-dfs | class Solution:
def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
n = len(nums)
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def fn(u):
score[u] = nums[u]
child[u] = {u}
for v in graph[u]:
if seen[v] == 0:
seen[v] = 1
fn(v)
score[u] ^= score[v]
child[u] |= child[v]
seen = [1] + [0]*(n-1)
score = [0]*n
child = [set() for _ in range(n)]
fn(0)
ans = inf
for u in range(1, n):
for v in range(u+1, n):
if u in child[v]:
uu = score[u]
vv = score[v] ^ score[u]
xx = score[0] ^ score[v]
elif v in child[u]:
uu = score[u] ^ score[v]
vv = score[v]
xx = score[0] ^ score[u]
else:
uu = score[u]
vv = score[v]
xx = score[0] ^ score[u] ^ score[v]
ans = min(ans, max(uu, vv, xx) - min(uu, vv, xx))
return ans | minimum-score-after-removals-on-a-tree | [Python3] dfs | ye15 | 6 | 241 | minimum score after removals on a tree | 2,322 | 0.506 | Hard | 31,980 |
https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2198386/Python3-dfs | class Solution:
def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
n = len(nums)
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def fn(u, p):
nonlocal t
score[u] = nums[u]
tin[u] = (t := t+1) # time to enter
for v in graph[u]:
if v != p:
fn(v, u)
score[u] ^= score[v]
tout[u] = t # time to exit
t = 0
score = [0]*n
tin = [0]*n
tout = [0]*n
fn(0, -1)
ans = inf
for u in range(1, n):
for v in range(u+1, n):
if tin[v] <= tin[u] and tout[v] >= tout[u]: # enter earlier & exit later == parent
uu = score[u]
vv = score[v] ^ score[u]
xx = score[0] ^ score[v]
elif tin[v] >= tin[u] and tout[v] <= tout[u]:
uu = score[u] ^ score[v]
vv = score[v]
xx = score[0] ^ score[u]
else:
uu = score[u]
vv = score[v]
xx = score[0] ^ score[u] ^ score[v]
ans = min(ans, max(uu, vv, xx) - min(uu, vv, xx))
return ans | minimum-score-after-removals-on-a-tree | [Python3] dfs | ye15 | 6 | 241 | minimum score after removals on a tree | 2,322 | 0.506 | Hard | 31,981 |
https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2351673/99-faster-at-my-time-or-python3-solution | class Solution:
def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
s,n=0,len(nums)
for x in nums:
s^=x
es=[[] for _ in range(n)]
for a,b in edges:
es[a].append(b)
es[b].append(a)
def f(a,b,c):
return max(a,b,c)-min(a,b,c)
def dfs(x,par=-1):
S,m,p=[],10**9,nums[x]
for y in es[x]:
if y!=par:
t,u,v=dfs(y,x)
m=min(m,u,min(f(s^v,v^k,k) for k in t) if t else u)
t.add(v)
S.append(t)
p^=v
r=set()
for t in S:
r|=t
for i in range(len(S)):
for j in range(i+1,len(S)):
m=min(m,min(f(s^k^l,k,l) for k in S[i] for l in S[j]))
return r,m,p
return dfs(0)[1] | minimum-score-after-removals-on-a-tree | 99% faster at my time | python3 solution | vimla_kushwaha | 1 | 36 | minimum score after removals on a tree | 2,322 | 0.506 | Hard | 31,982 |
https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2792281/Python-O(N2)-DFS | class Solution:
def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
n = len(nums)
graph = [set() for _ in range(n)]
for u, v in edges:
graph[u].add(v)
graph[v].add(u)
ans = float('inf')
def dfs(v, visited, subs):
ret = nums[v]
for u in graph[v]:
if u not in visited:
visited.add(u)
cur = dfs(u, visited, subs)
ret ^= cur
subs.add(cur)
return ret
for u, v in edges:
graph[u].remove(v)
graph[v].remove(u)
leftsubs, rightsubs = set(), set()
left, right = dfs(u, {u}, leftsubs), dfs(v, {v}, rightsubs)
for c in leftsubs:
parts = [right, c, left ^ c]
ans = min(ans, max(parts) - min(parts))
for c in rightsubs:
parts = [left, c, right ^ c]
ans = min(ans, max(parts) - min(parts))
graph[u].add(v)
graph[v].add(u)
return ans | minimum-score-after-removals-on-a-tree | [Python] O(N^2) DFS | cava | 0 | 1 | minimum score after removals on a tree | 2,322 | 0.506 | Hard | 31,983 |
https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2576756/Python3-or-DFS-%2B-DP | class Solution:
def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
hmap=defaultdict(int)
pc,par=[],[]
n=len(nums)
childs=[[False for i in range(n)] for j in range(n)]
graph=[[] for i in range(n)]
for a,b in edges:
graph[a].append(b)
graph[b].append(a)
vis=set()
def dfs(curr):
for p in par:childs[p][curr]=True
par.append(curr)
currXor=nums[curr]
for it in graph[curr]:
if it not in vis:
vis.add(it)
pc.append((curr,it))
val=dfs(it)
currXor^=val
par.pop()
hmap[curr]=currXor
return currXor
vis.add(0)
dfs(0)
m=len(pc)
ans=float('inf')
for a in range(m):
for b in range(a+1,m):
f,s=pc[a][1],pc[b][1]
xf,xs,xp=hmap[f],hmap[s],hmap[0]
if childs[f][s]:
xp^=xf
xf^=xs
else:
xp^=xf
xp^=xs
ans=min(ans,max(xp,xf,xs)-min(xp,xf,xs))
return ans | minimum-score-after-removals-on-a-tree | [Python3] | DFS + DP | swapnilsingh421 | 0 | 19 | minimum score after removals on a tree | 2,322 | 0.506 | Hard | 31,984 |
https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2199356/Python3-using-DFS-and-XOR-of-each-subtree | class Solution:
def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
n = len(nums)
tree = [set() for _ in range(n)]
for e in edges:
tree[e[0]].add(e[1])
tree[e[1]].add(e[0])
def make_tree(i, parent):
ancestors[i].add(parent)
for j in ancestors[parent]:
ancestors[i].add(j)
tree[i].remove(parent)
for child in tree[i]:
make_tree(child, i)
xor[i] ^= xor[child]
xor = [nums[i] for i in range(n)]
ancestors = [set() for _ in range(n)]
for child in tree[0]:
make_tree(child, 0)
xor[0] ^= xor[child]
ans = 2 ** 31 - 1
for i in range(1, n - 1):
for j in range(i + 1, n):
if i in ancestors[j]:
parts = [xor[0] ^ xor[i], xor[i] ^ xor[j], xor[j]]
elif j in ancestors[i]:
parts = [xor[0] ^ xor[j], xor[i], xor[i] ^ xor[j]]
else:
parts = [xor[0] ^ xor[i] ^ xor[j], xor[i], xor[j]]
ans = min(ans, max(parts) - min(parts))
return ans | minimum-score-after-removals-on-a-tree | [Python3] using DFS and XOR of each subtree | yx41_qby | 0 | 4 | minimum score after removals on a tree | 2,322 | 0.506 | Hard | 31,985 |
https://leetcode.com/problems/decode-the-message/discuss/2229844/Easy-Python-solution-using-Hashing | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
mapping = {' ': ' '}
i = 0
res = ''
letters = 'abcdefghijklmnopqrstuvwxyz'
for char in key:
if char not in mapping:
mapping[char] = letters[i]
i += 1
for char in message:
res += mapping[char]
return res | decode-the-message | Easy Python solution using Hashing | MiKueen | 23 | 1,400 | decode the message | 2,325 | 0.848 | Easy | 31,986 |
https://leetcode.com/problems/decode-the-message/discuss/2531674/Python3-or-Compact-(5-line)-solution-or-Hashmap | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
char_map = {' ': ' '}
for char in key:
if char not in char_map:
char_map[char] = chr(ord('a') + len(char_map) - 1)
return ''.join([char_map[char] for char in message]) | decode-the-message | Python3 | Compact (5-line) solution | Hashmap | Ploypaphat | 1 | 108 | decode the message | 2,325 | 0.848 | Easy | 31,987 |
https://leetcode.com/problems/decode-the-message/discuss/2245859/With-Picture-explanation-2325.-Decode-the-Message | class Solution(object):
def decodeMessage(self, key, message):
mapping={' ':' '}
alphabet='abcdefghijklmnopqrstuvwxyz'
res=''
i=0
for eachchar in key:
if eachchar not in mapping:
mapping[eachchar]=alphabet[i]
i+=1
print(mapping)
for j in message:
res+=mapping[j]
return res | decode-the-message | With Picture explanation 2325. Decode the Message | m_e_shivam | 1 | 39 | decode the message | 2,325 | 0.848 | Easy | 31,988 |
https://leetcode.com/problems/decode-the-message/discuss/2847127/Python-Brute-Force-Approach-Easy-to-understand | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
alpha = "abcdefghijklmnopqrstuvwxyz"
y = key.replace(" ","")
al = [i for i in alpha]
ke = []
for i in y :
if i not in ke:
ke.append(i)
nano = [i for i in zip(ke,al)]
nano.append([" ", " "])
nano1 = []
nano2 = []
for i in nano:
nano1.append(i[0])
for i in nano:
nano2.append(i[1])
dec = ""
for i in message:
ind = nano1.index(i)
dec += nano2[ind]
return dec | decode-the-message | Python Brute Force Approach, Easy to understand | Shagun_Mittal | 0 | 2 | decode the message | 2,325 | 0.848 | Easy | 31,989 |
https://leetcode.com/problems/decode-the-message/discuss/2843781/Very-Easy-or-Python | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
res = {}
char = 97
for i in key:
if i not in res and i!=" ":
res[i] = chr(char)
char+=1
if i == " ":
res[i] = " "
decoded = ""
for i in message:
if i!=" ":
decoded+=res[i]
else:
decoded+=" "
return decoded | decode-the-message | Very Easy | Python | khanismail_1 | 0 | 2 | decode the message | 2,325 | 0.848 | Easy | 31,990 |
https://leetcode.com/problems/decode-the-message/discuss/2829114/Simple-explained-solution-with-python | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
## SC O(n+m)
## TC O(n+m)
# create support dictionary and set
my_set = set()
my_dic = {}
# create English alpabeth
ab = string.ascii_lowercase
# support index
index = 0
# iterate through key and create support dictionary
for char in key:
# only count first appearence of letter & discard empty strings & stop at 26 (length of English alpabeth)
if char not in my_set and char != ' ' and index <= 26:
my_set.add(char)
my_dic[char] = ab[index]
index += 1
# create support result string
res = ''
# iterate through message
for char in message:
# keep empty spaces
if char == ' ':
res += ' '
# translate
else:
res += my_dic[char]
return res | decode-the-message | Simple explained solution with python | MPoinelli | 0 | 3 | decode the message | 2,325 | 0.848 | Easy | 31,991 |
https://leetcode.com/problems/decode-the-message/discuss/2812558/Python-easy-code | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
d = dict()
ki = 0
for i in range(26):
while key[ki] == ' ' or key[ki] in d.keys():
ki += 1
d[key[ki]] = chr(i + ord('a'))
ki += 1
ans = ''
for m in message:
c = d[m] if m != ' ' else m
ans += c
return ans | decode-the-message | Python easy code | jsyx1994 | 0 | 5 | decode the message | 2,325 | 0.848 | Easy | 31,992 |
https://leetcode.com/problems/decode-the-message/discuss/2693780/A-Simple-and-Efficient-Python-Solution | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
table = {' ':' '}
i = 97
for char in key:
if char not in table:
table[char] = chr(i)
i += 1
if i > 128:
break
return "".join(table[char] for char in message) | decode-the-message | A Simple and Efficient Python Solution | kcstar | 0 | 3 | decode the message | 2,325 | 0.848 | Easy | 31,993 |
https://leetcode.com/problems/decode-the-message/discuss/2682098/Python-3-list-comprehension-fast-method | class Solution:
def decodeMessage(self, key, message):
alpha = ['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']
checker = []
[checker.append(x) for x in list(key) if x not in checker and x != ' ']
new_dict = {}
for x in range(len(checker)):
new_dict[checker[x]] = alpha[x]
new_dict[' '] = ' '
my_str = ''
for x in message:
my_str += new_dict[x]
return my_str | decode-the-message | [Python 3] list comprehension fast method | innovin | 0 | 52 | decode the message | 2,325 | 0.848 | Easy | 31,994 |
https://leetcode.com/problems/decode-the-message/discuss/2671815/Python-dictionary-clean-and-easy-solution | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
sub = []
for i in key:
if i != " " and i not in sub:
sub.append(i)
if len(sub) == 26:
break
map_ = {k: chr(i + 97) for i, k in enumerate(sub)}
ans = ""
for c in message:
if c == " ":
ans += " "
else:
ans += map_[c]
return ans | decode-the-message | Python dictionary clean and easy solution | phantran197 | 0 | 2 | decode the message | 2,325 | 0.848 | Easy | 31,995 |
https://leetcode.com/problems/decode-the-message/discuss/2649753/Python3-Solution | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
key = "".join(key.split())
dict_map = {}
unique_char = []
i = 0
for c in key:
if c not in unique_char:
dict_map[c] = chr(97+i)
unique_char.append(c)
i += 1
dict_map[' '] = ' '
return "".join([dict_map[i] for i in message]) | decode-the-message | Python3 Solution | sipi09 | 0 | 5 | decode the message | 2,325 | 0.848 | Easy | 31,996 |
https://leetcode.com/problems/decode-the-message/discuss/2614202/Simple-Python-Code | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
mapping = {}
current = 0
for a in key.replace(" ",""):
if a not in mapping:
mapping[a]=chr(current+ord('a'))
current += 1
ans = []
for c in message:
if c == " ":
ans.append(" ")
continue
ans.append(mapping[c])
return"".join(ans) | decode-the-message | Simple Python Code | ayaz_skipq_2022 | 0 | 42 | decode the message | 2,325 | 0.848 | Easy | 31,997 |
https://leetcode.com/problems/decode-the-message/discuss/2596007/32-ms-faster-than-97.17-of-Python3-online-submissions | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
d = {}
i = 0
for k in key:
if k!=" ":
if k not in d:
d[k] = chr(97 + i)
i+=1
t = ""
for i in message:
if i==" ":
t+=" "
else:
t += d[i]
return t | decode-the-message | 32 ms, faster than 97.17% of Python3 online submissions | Abdulahad_Abduqahhorov | 0 | 39 | decode the message | 2,325 | 0.848 | Easy | 31,998 |
https://leetcode.com/problems/decode-the-message/discuss/2570306/Python-short-solution | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
letters = iter(string.ascii_lowercase)
table = dict()
for letter in key:
if letter.isalpha() and letter not in table:
table[letter] = next(letters)
return ''.join(table[c] if c.isalpha() else c for c in message) | decode-the-message | Python short solution | meatcodex | 0 | 35 | decode the message | 2,325 | 0.848 | Easy | 31,999 |
Subsets and Splits