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/remove-all-adjacent-duplicates-in-string-ii/discuss/2012211/Python3-simple-stack-solution | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = list() #list of [char, accumulative freq]
for char in s:
if not stack or char != stack[-1][0]:
stack.append([char, 1])
else:
next_freq = stack[-1][1] + 1
stack.append([char, next_freq])
if next_freq == k: # pop
for _ in range(k):
stack.pop()
ans = str()
for char, freq in stack:
ans += char
return ans | remove-all-adjacent-duplicates-in-string-ii | [Python3] simple stack solution | sshinyy | 0 | 20 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,300 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/2012108/Python-easy-to-understand-solution-using-Stack | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
# stack to store the pair[character, count]
stack = []
for char in s:
# If the stack is not empty and last char in stack and current char are same,
# then increment the count
if stack and char == stack[-1][0]:
stack[-1][1] += 1
#if count of char == k, pop it from stack
if stack[-1][1] == k:
stack.pop()
else:
stack.append([char,1])
res = ""
for char, count in stack:
res += char*count
return res | remove-all-adjacent-duplicates-in-string-ii | Python easy to understand solution using Stack | firefist07 | 0 | 27 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,301 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/1973128/Python3-or-Complete-Tutorial-Step-by-Step-Progress | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
currentIndex = 0
while currentIndex < len(s):
#Extract k elements from string
#O(1) or O(k)
kthStr = s[currentIndex: currentIndex+k]
#if len is equal and all characters are same, remove from original string
uniques = set(kthStr)
if len(kthStr) == k and len(uniques) == 1:
s = s[:currentIndex] + s[currentIndex+k:]
noOfBackSteps = k
while currentIndex-noOfBackSteps < 0:
noOfBackSteps -= 1
#update currentIndex by next close margin of k
currentIndex -= noOfBackSteps
else:
currentIndex += 1
return s | remove-all-adjacent-duplicates-in-string-ii | Python3 | Complete Tutorial Step by Step Progress | avi-arora | 0 | 100 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,302 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/1973128/Python3-or-Complete-Tutorial-Step-by-Step-Progress | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
def isKElementSame():
nonlocal stack, k
topElem = stack[len(stack)-1]
counter, index = 0, len(stack)-2
while counter < k-1:
if stack[index] != topElem:
return False
counter, index = counter+1, index-1
return True
stack = []
for c in s:
stack.append(c)
if len(stack) >= k and isKElementSame():
for _ in range(k):
stack.pop()
return "".join(stack) | remove-all-adjacent-duplicates-in-string-ii | Python3 | Complete Tutorial Step by Step Progress | avi-arora | 0 | 100 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,303 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/1973128/Python3-or-Complete-Tutorial-Step-by-Step-Progress | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
index = 1
stack = [[s[index-1], 1]]
while index < len(s):
if stack and stack[-1][0] == s[index]:
stack[-1][1] += 1
#pop condition
if stack[-1][1] == k:
stack.pop()
else:
stack.append([s[index], 1])
index += 1
#whatever stack is left, perform join
result = ""
for (character, count) in stack:
result += character * count
return result | remove-all-adjacent-duplicates-in-string-ii | Python3 | Complete Tutorial Step by Step Progress | avi-arora | 0 | 100 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,304 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/1807834/python-simple-easy-to-understand-solution | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack=[["#", 0]]
for ch in s:
last_ch, last_count = stack[-1]
if last_ch == ch:
if last_count == k-1:
stack.pop()
else:
stack[-1][1] += 1
else:
stack.append([ch, 1])
return "".join([ch*count for ch,count in stack]) | remove-all-adjacent-duplicates-in-string-ii | python simple easy to understand solution | coder_Im_not | 0 | 146 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,305 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/1801567/Python-3-Solution-Using-Stack | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack=[[s[0],1]]
for ele in s[1:]:
if stack and stack[-1][0]==ele:
stack[-1][1]+=1
else:
stack.append([ele,1])
if stack[-1][1]==k:
stack.pop()
return ''.join(key*value for key,value in stack) | remove-all-adjacent-duplicates-in-string-ii | [Python 3 ] Solution Using Stack | jiteshbhansali | 0 | 93 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,306 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/1497287/Clean-solution-in-Python-using-stack-of-tuples. | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = [(s[0], 1)]
for i in range(1, len(s)):
cnt = stack[-1][1] + 1 if stack and stack[-1][0] == s[i] else 1
stack += (s[i], cnt),
while stack and stack[-1][1] == k:
for _ in range(k):
stack.pop()
return "".join(letter for letter, _ in stack) | remove-all-adjacent-duplicates-in-string-ii | Clean solution in Python, using stack of tuples. | mousun224 | 0 | 261 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,307 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/1165084/Simplest-Python-Solution-Stack | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
st=[]
st.append([s[0],1])
for i in range(1,len(s)):
if len(st)>0 and s[i]==st[-1][0]:
st[-1][1]+=1
else:
st.append([s[i],1])
if st[-1][1]==k:
st.pop()
ans=""
for i in range(len(st)):
ans=(st[-1][0]*st[-1][1])+ans
st.pop()
return ans | remove-all-adjacent-duplicates-in-string-ii | Simplest Python Solution- Stack | Ayu-99 | 0 | 189 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,308 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/1161115/Simple-solution-using-a-stack-in-Python3 | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = []
for char in s:
if not stack:
stack.append([char, 1])
else:
if stack[-1][0] == char:
stack[-1][1] += 1
else:
stack.append([char, 1])
while stack and stack[-1][1] >= k:
newtop = stack[-1][1] - k
if newtop == 0:
stack.pop()
else:
stack[-1][1] = newtop
ans = ""
for i in stack:
ans += (i[0] * i[1])
return ans | remove-all-adjacent-duplicates-in-string-ii | Simple solution using a stack in Python3 | amoghrajesh1999 | 0 | 54 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,309 |
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/1134903/Python3-stack | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = []
for c in s:
if stack and stack[-1][0] == c:
stack[-1][1] += 1
else: stack.append([c, 1])
if stack[-1][1] == k: stack.pop()
return "".join(x*c for x, c in stack) | remove-all-adjacent-duplicates-in-string-ii | [Python3] stack | ye15 | 0 | 79 | remove all adjacent duplicates in string ii | 1,209 | 0.56 | Medium | 18,310 |
https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/discuss/393042/Python-3-(BFS-DFS-and-DP)-(With-Explanation)-(beats-100.00) | class Solution:
def minimumMoves(self, G: List[List[int]]) -> int:
N, S, T, V, c = len(G), [(0, 0, 'h')], [], set(), 0
while S:
for i in S:
if i in V: continue
if i == (N-1, N-2, 'h'): return c
(a, b, o), _ = i, V.add(i)
if o == 'h':
if b + 2 != N and G[a][b+2] == 0: T.append((a, b+1, o))
if a + 1 != N and G[a+1][b] == 0 and G[a+1][b+1] == 0: T.append((a+1, b, o)), T.append((a, b, 'v'))
elif o == 'v':
if a + 2 != N and G[a+2][b] == 0: T.append((a+1, b, o))
if b + 1 != N and G[a][b+1] == 0 and G[a+1][b+1] == 0: T.append((a, b+1, o)), T.append((a, b, 'h'))
S, T, c = T, [], c + 1
return -1 | minimum-moves-to-reach-target-with-rotations | Python 3 (BFS, DFS, and DP) (With Explanation) (beats 100.00%) | junaidmansuri | 8 | 896 | minimum moves to reach target with rotations | 1,210 | 0.491 | Hard | 18,311 |
https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/discuss/393042/Python-3-(BFS-DFS-and-DP)-(With-Explanation)-(beats-100.00) | class Solution:
def minimumMoves(self, G: List[List[int]]) -> int:
N, V, M, self.t, self.m = len(G), set(), collections.defaultdict(int), 0, math.inf
print(N)
def dfs(a,b,o):
if (a,b,o) in V or M[(a,b,o)] == 2 or self.t > self.m: return
if (a,b,o) == (N-1,N-2,'h'):
self.m = min(self.m,self.t)
for i in V: M[i] = 1
return
self.t, _ = self.t + 1, V.add((a,b,o))
if o == 'h':
if b + 2 != N and G[a][b+2] == 0: dfs(a, b+1, o)
if a + 1 != N and G[a+1][b] == 0 and G[a+1][b+1] == 0: dfs(a+1, b, o), dfs(a, b, 'v')
elif o == 'v':
if a + 2 != N and G[a+2][b] == 0: dfs(a+1, b, o)
if b + 1 != N and G[a][b+1] == 0 and G[a+1][b+1] == 0: dfs(a, b+1, o), dfs(a, b, 'h')
if M[(a,b,o)] == 0: M[(a,b,o)] = 2
self.t, _ = self.t - 1, V.remove((a,b,o))
dfs(0,0,'h')
return -1 if self.m == math.inf else self.m | minimum-moves-to-reach-target-with-rotations | Python 3 (BFS, DFS, and DP) (With Explanation) (beats 100.00%) | junaidmansuri | 8 | 896 | minimum moves to reach target with rotations | 1,210 | 0.491 | Hard | 18,312 |
https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/discuss/393042/Python-3-(BFS-DFS-and-DP)-(With-Explanation)-(beats-100.00) | class Solution:
def minimumMoves(self, G: List[List[int]]) -> int:
N, I, DP = len(G)-1, math.inf, [[math.inf]*2 for i in range(len(G)+1)]
DP[N-1][0] = I if 1 in [G[N][N],G[N][N-1]] else 0
for j in range(N-2,-1,-1): DP[j][0] = (DP[j+1][0] + 1) if G[N][j] == 0 else I
for i,j in itertools.product(range(N-1,-1,-1),range(N,-1,-1)):
n = [G[i][j],G[i][min(j+1,N)],G[min(i+1,N)][j],G[min(i+1,N)][min(j+1,N)]]
DP[j][0], DP[j][1] = min(1+DP[j+1][0],1+DP[j][0]), min(1+DP[j+1][1],1+DP[j][1])
if 1 not in n: DP[j][0], DP[j][1] = min(DP[j][0],2+DP[j+1][1],1+DP[j][1]), min(DP[j][1],2+DP[j+1][0],1+DP[j][0])
if 1 in [n[0],n[1]]: DP[j][0] = I
if 1 in [n[0],n[2]]: DP[j][1] = I
return -1 if DP[0][0] == I else DP[0][0]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | minimum-moves-to-reach-target-with-rotations | Python 3 (BFS, DFS, and DP) (With Explanation) (beats 100.00%) | junaidmansuri | 8 | 896 | minimum moves to reach target with rotations | 1,210 | 0.491 | Hard | 18,313 |
https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/discuss/1134913/Python3-Dijkstra's-algo | class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
n = len(grid)
dist = {(0, 0, 0, 1): 0}
pq = [(0, 0, 0, 0, 1)]
while pq:
x, i, j, ii, jj = heappop(pq)
if i == n-1 and j == n-2 and ii == n-1 and jj == n-1: return x
if ii+1 < n and grid[i+1][j] == grid[ii+1][jj] == 0 and x+1 < dist.get((i+1, j, ii+1, jj), inf):
heappush(pq, (x+1, i+1, j, ii+1, jj))
dist[i+1, j, ii+1, jj] = x + 1
if jj+1 < n and grid[i][j+1] == grid[ii][jj+1] == 0 and x+1 < dist.get((i, j+1, ii, jj+1), inf):
heappush(pq, (x+1, i, j+1, ii, jj+1))
dist[i, j+1, ii, jj+1] = x + 1
if i == ii and ii+1 < n and grid[i+1][j] == grid[i+1][jj] == 0 and x+1 < dist.get((i, j, i+1, j), inf):
heappush(pq, (x+1, i, j, i+1, j))
dist[i, j, i+1, j] = x + 1
if j == jj and jj+1 < n and grid[i][j+1] == grid[ii][j+1] == 0 and x+1 < dist.get((i, j, i, j+1), inf):
heappush(pq, (x+1, i, j, i, j+1))
dist[i, j, i, j+1] = x + 1
return -1 | minimum-moves-to-reach-target-with-rotations | [Python3] Dijkstra's algo | ye15 | 2 | 86 | minimum moves to reach target with rotations | 1,210 | 0.491 | Hard | 18,314 |
https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/discuss/2317313/PYTHON-or-100-FASTEST-SOL-or-BFS-%2B-HASHMAP-or-FULLY-EXPLAINED-or | class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
queue , vis , n = [(0,1,0,0)] , {} , len(grid)
while queue:
x,y,pos,moves = queue.pop(0)
if x == y == n-1 and pos == 0: return moves
if pos == 0:
if y + 1 < n and grid[x][y+1] == 0 and (x,y+1,0) not in vis:
vis[(x,y+1,0)] = True
queue.append((x,y+1,0,moves+1))
if x + 1 < n and grid[x+1][y-1] == 0 and grid[x+1][y] == 0:
if (x+1,y-1,1) not in vis:
vis[(x+1,y-1,1)] = True
queue.append((x+1,y-1,1,moves+1))
if (x+1,y,0) not in vis:
vis[(x+1,y,0)] = True
queue.append((x+1,y,0,moves+1))
else:
if x + 1 < n and grid[x+1][y] == 0 and (x+1,y,1) not in vis:
vis[(x+1,y,1)] = True
queue.append((x+1,y,1,moves+1))
if y + 1 < n and grid[x-1][y+1] == grid[x][y+1] == 0:
if (x-1,y+1,0) not in vis:
vis[(x-1,y+1,0)] = True
queue.append((x-1,y+1,0,moves+1))
if (x,y+1,1) not in vis:
vis[(x,y+1,1)] = True
queue.append((x,y+1,1,moves+1))
return -1 | minimum-moves-to-reach-target-with-rotations | PYTHON | 100 % FASTEST SOL | BFS + HASHMAP | FULLY EXPLAINED | | reaper_27 | 0 | 32 | minimum moves to reach target with rotations | 1,210 | 0.491 | Hard | 18,315 |
https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/discuss/1656775/Python-or-BFS-or-Template-or-Explanation | class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
n = len(grid)
def findNeighbors(head, state):
actual = []
x, y = head
if state == 'H':
# go right when horizontal
if y + 1 <= n - 1 and grid[x][y + 1] == 0:
actual.append((x, y + 1, 'H'))
# go down when horizontal
if x + 1 <= n - 1 and grid[x + 1][y] == 0 and grid[x + 1][y - 1] == 0:
actual.append((x + 1, y, 'H'))
# can rotate clkwise here
actual.append((x + 1, y - 1, 'V'))
else:
# go down when vertical
if x + 1 <= n - 1 and grid[x + 1][y] == 0:
actual.append((x + 1, y, 'V'))
# go right when vertical
if y + 1 <= n - 1 and grid[x][y + 1] == 0 and grid[x - 1][y + 1] == 0:
actual.append((x, y + 1, 'V'))
# can rotate anti clkwise here
actual.append((x - 1, y + 1, 'H'))
return actual
visited = set()
q = deque()
q.append((0, 1, 'H', 0))
while q:
x, y, state, dist = q.popleft()
if (x, y, state) == (n - 1, n - 1, 'H'):
return dist
if (x, y, state) in visited:
continue
visited.add((x, y, state))
for nx, ny, ndir in findNeighbors((x, y), state):
q.append((nx, ny, ndir, dist + 1))
return -1 | minimum-moves-to-reach-target-with-rotations | Python | BFS | Template | Explanation | detective_dp | 0 | 71 | minimum moves to reach target with rotations | 1,210 | 0.491 | Hard | 18,316 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1510460/Greedy-Approach-oror-Well-Explained-oror-Easy-to-understand | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
dic = Counter([n%2 for n in position])
return min(dic[0],dic[1]) | minimum-cost-to-move-chips-to-the-same-position | ππ Greedy Approach || Well-Explained || Easy-to-understand π | abhi9Rai | 5 | 165 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,317 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1510460/Greedy-Approach-oror-Well-Explained-oror-Easy-to-understand | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
dic = defaultdict(int)
for n in position:
dic[n%2] += 1
return min(dic[0],dic[1]) | minimum-cost-to-move-chips-to-the-same-position | ππ Greedy Approach || Well-Explained || Easy-to-understand π | abhi9Rai | 5 | 165 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,318 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1614631/PYTHON.-one-liner-easy-and-clear-solution.-O(N)-time. | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
return min(len(list(filter(lambda x: x%2 == 0, position))), len(list(filter(lambda x: x%2 == 1, position)))) | minimum-cost-to-move-chips-to-the-same-position | PYTHON. one-liner, easy & clear solution. O(N) time. | m-d-f | 3 | 134 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,319 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1614628/PYTHON.-one-liner-easy-and-cute-solution.-O(N)-time.-faster-than-98.08 | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
return min(len([1 for x in position if x%2 == 0]), len([1 for x in position if x%2 == 1])) | minimum-cost-to-move-chips-to-the-same-position | PYTHON. one liner, easy & cute solution. O(N) time. faster than 98.08% | m-d-f | 3 | 83 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,320 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1613822/Simple-1-liner | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
pos_at_zero = sum(pos % 2 == 0 for pos in position)
return min(pos_at_zero, len(position) - pos_at_zero) | minimum-cost-to-move-chips-to-the-same-position | Simple 1-liner | kryuki | 1 | 200 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,321 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1613822/Simple-1-liner | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
return min(sum(pos % 2 == 0 for pos in position), sum(pos % 2 == 1 for pos in position)) | minimum-cost-to-move-chips-to-the-same-position | Simple 1-liner | kryuki | 1 | 200 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,322 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1601718/Python-3-two-line-solution | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
odd = sum(pos % 2 for pos in position)
return min(odd, len(position) - odd) | minimum-cost-to-move-chips-to-the-same-position | Python 3 two line solution | dereky4 | 1 | 94 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,323 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1395387/Python3-Faster-Than-97.17 | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
# You either move even positions to odd or the opposite based on their count
even, odd = 0, 0
for i in position:
if i & 1:
odd += 1
else:
even += 1
if even > odd:
return odd
else:
return even | minimum-cost-to-move-chips-to-the-same-position | Python3 Faster Than 97.17% | Hejita | 1 | 51 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,324 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/432480/Python3%3A-2-lines-with-explanation-24-ms-(faster-than-99.76) | class Solution:
def minCostToMoveChips(self, chips: List[int]) -> int:
odd = sum(c & 1 for c in chips)
return min(odd, len(chips) - odd) | minimum-cost-to-move-chips-to-the-same-position | Python3: 2 lines with explanation, 24 ms (faster than 99.76%) | andnik | 1 | 195 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,325 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/2779084/python-simplest-approach | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
ep=0
op=0
for i in position:
if i%2==0:
ep+=1
else:
op+=1
return min(ep,op) | minimum-cost-to-move-chips-to-the-same-position | [python] simplest approach | user9516zM | 0 | 5 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,326 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/2628707/Python3-Solution | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
return odd if (odd:= len(list(filter(lambda x: (x%2 != 0) , position))))<(even:=len(position)-odd) else even | minimum-cost-to-move-chips-to-the-same-position | Python3 Solution | hobbabeau | 0 | 8 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,327 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/2604662/Python-Easy-Solution | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
od_cnt, ev_cnt = 0, 0
for p in position:
if(p%2 == 0):
ev_cnt += 1
else:
od_cnt += 1
return min(od_cnt, ev_cnt) | minimum-cost-to-move-chips-to-the-same-position | Python Easy Solution | Jack_Chang | 0 | 41 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,328 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/2367625/Minimum-of-odd-and-even-freq | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
count_even=0
count_odd=0
for i in position:
if i%2==0:
count_even+=1
else:
count_odd+=1
return min(count_even,count_odd) | minimum-cost-to-move-chips-to-the-same-position | Minimum of odd and even freq | sunakshi132 | 0 | 32 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,329 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/2255471/Python-Easiest-Solution | class Solution(object):
def minCostToMoveChips(self, position):
"""
:type position: List[int]
:rtype: int
"""
even = 0
odd = 0
for i in position:
if i%2 == 0:
even +=1
else:
odd+=1
return min(even,odd)
`` | minimum-cost-to-move-chips-to-the-same-position | Python Easiest Solution | Abhi_009 | 0 | 47 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,330 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1938211/easy-python-code | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
d = {}
x = []
for i in range(len(position)):
if position[i] in d:
d[position[i]] += 1
else:
d[position[i]] = 1
for i in d:
count = 0
for j in d:
if (abs(i - j))%2 != 0:
count += d[j]
x.append([count])
return (min(x)[0]) | minimum-cost-to-move-chips-to-the-same-position | easy python code | dakash682 | 0 | 48 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,331 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1840282/Python-solution-using-hashmap | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
d = {0:0, 1:0}
min_=0
for i in position:
if i%2==1:
d[1]+=1
else:
d[0]+=1
min_ = max(min_, min(d[0], d[1]))
return min_ | minimum-cost-to-move-chips-to-the-same-position | Python solution using hashmap | prajwalahluwalia | 0 | 35 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,332 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1825038/Simple-Python-Solution-oror-30-Faster-oror-Memory-less-than-80 | class Solution:
def minCostToMoveChips(self, P: List[int]) -> int:
ans=[] ; C=Counter(P)
for c in C.keys():
res=0
for x in C.keys():
if x%2!=c%2 and x!=c: res+=C[x]
ans.append(res)
return min(ans) | minimum-cost-to-move-chips-to-the-same-position | Simple Python Solution || 30% Faster || Memory less than 80% | Taha-C | 0 | 33 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,333 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1615976/Python3-Even-odd-solution | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
# if all move to even position, return the number of odd positions
# if all move to odd position, return the number of even positions
# we are not sure, so return the minimum value
odd_count, even_count = 0, 0
for p in position:
if p%2 == 0:
even_count += 1
else:
odd_count += 1
return min(even_count, odd_count) | minimum-cost-to-move-chips-to-the-same-position | [Python3] Even odd solution | Rainyforest | 0 | 15 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,334 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1615322/Easy-100-python | class Solution:
def minCostToMoveChips(self, positions: List[int]) -> int:
odd_count = sum(position % 2 for position in positions)
even_count = len(positions) - odd_count
return min(odd_count, even_count) | minimum-cost-to-move-chips-to-the-same-position | Easy 100% python | tamat | 0 | 16 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,335 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1614793/Python3-Greedy-solution | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
odd = 0
even = 0
for pos in position:
if pos % 2 == 0:
even += 1
else:
odd += 1
return min(odd, even) | minimum-cost-to-move-chips-to-the-same-position | [Python3] Greedy solution | maosipov11 | 0 | 28 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,336 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1614653/Python-oror-O(n)-time-oror-O(1)-space | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
even = 0
odd = 0
for i in position:
if i % 2 == 0:
even += 1
else:
odd += 1
return min(even,odd) | minimum-cost-to-move-chips-to-the-same-position | Python || O(n) time || O(1) space | s_m_d_29 | 0 | 15 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,337 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1614469/faster-than-100-oror-C%2B%2B-code-python3 | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
even, odd = 0, 0
for i in position:
if i & 1 :
odd += 1
else:
even += 1
return min(even, odd) | minimum-cost-to-move-chips-to-the-same-position | faster than 100% || C++ code/ python3 | qikang1994 | 0 | 36 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,338 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1298841/Easy-Python-Solution(99.42) | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
e=0
o=0
for i in position:
if(i%2!=0):
o+=1
else:
e+=1
return o if o<e else e | minimum-cost-to-move-chips-to-the-same-position | Easy Python Solution(99.42%) | Sneh17029 | 0 | 169 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,339 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1232398/python-or-easy-or-97%2B | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
od, ev = 0, 0
for i in range(len(position)):
if position[i] % 2 == 0:
ev += 1
else:
od += 1
return min(od, ev) | minimum-cost-to-move-chips-to-the-same-position | python | easy | 97%+ | chikushen99 | 0 | 61 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,340 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1041448/Python3-simple-solution | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
odd = 0
even = 0
for i in position:
if i % 2 == 0:
even += 1
else:
odd += 1
return min(odd,even) | minimum-cost-to-move-chips-to-the-same-position | Python3 simple solution | EklavyaJoshi | 0 | 64 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,341 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1031651/one-line-in-Python-not-very-fast | class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
return min(sum([i % 2 for i in position]),sum([1 - i % 2 for i in position])) | minimum-cost-to-move-chips-to-the-same-position | one line in Python, not very fast | user3943I | 0 | 34 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,342 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/593111/Python-O(-n-)-sol-with-even-odd-judgement.-90%2B-w-Comment | class Solution:
def minCostToMoveChips(self, chips: List[int]) -> int:
# Two variables for
# cost of odd position to even position, and
# cost of even position to odd position
odd_to_even, even_to_odd = 0, 0
for position in chips:
# update moving cost
if position % 2 == 0:
even_to_odd += 1
else:
odd_to_even += 1
return min( even_to_odd, odd_to_even ) | minimum-cost-to-move-chips-to-the-same-position | Python O( n ) sol with even odd judgement. 90%+ [w/ Comment] | brianchiang_tw | 0 | 111 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,343 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/550597/Python-Super-Simple | class Solution:
def minCostToMoveChips(self, chips: List[int]) -> int:
counte = 0
counto = 0
for i in chips:
if i%2==0:
counte+=1
else:
counto+=1
return min(counte,counto) | minimum-cost-to-move-chips-to-the-same-position | Python Super Simple | rachit007 | 0 | 103 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,344 |
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/398307/Solution-in-Python-3-(one-line)-(beats-100.00-)-(-O(n)-time-) | class Solution:
def minCostToMoveChips(self, C: List[int]) -> int:
return min(sum(c % 2 for c in C), len(C) - sum(c % 2 for c in C))
- Junaid Mansuri
(LeetCode ID)@hotmail.com | minimum-cost-to-move-chips-to-the-same-position | Solution in Python 3 (one line) (beats 100.00 %) ( O(n) time ) | junaidmansuri | 0 | 162 | minimum cost to move chips to the same position | 1,217 | 0.722 | Easy | 18,345 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1605339/Python3-dp-and-hash-table-easy-to-understand | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
"""
dp is a hashtable, dp[x] is the longest subsequence ending with number x
"""
dp = {}
for x in arr:
if x - difference in dp:
dp[x] = dp[x-difference] + 1
else:
dp[x] = 1
return max(dp.values()) | longest-arithmetic-subsequence-of-given-difference | [Python3] dp and hash table, easy to understand | nick19981122 | 18 | 761 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,346 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/823115/Python-easy-O(n) | class Solution:
def longestSubsequence(self, arr: List[int], d: int) -> int:
if not arr:
return 0
cache={}
maxc=0
for i in arr:
if i-d in cache:
cache[i]=cache[i-d]+1
else:
cache[i]=1
maxc=max(maxc,cache[i])
return maxc | longest-arithmetic-subsequence-of-given-difference | Python easy, O(n) | kritika90mahi | 2 | 95 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,347 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/822287/Python-3-or-One-pass-DP-or-Dictionary | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
d, ans = collections.defaultdict(int), 0
for num in arr:
d[num] = d[num-difference] + 1
ans = max(ans, d[num])
return ans | longest-arithmetic-subsequence-of-given-difference | Python 3 | One-pass DP | Dictionary | idontknoooo | 2 | 260 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,348 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1733965/Very-simple-Python-hashmap-solution | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
myDict=Counter()
for n in arr:
myDict[n+difference]=myDict[n]+1 if n in myDict else 1
return max(myDict.values()) | longest-arithmetic-subsequence-of-given-difference | Very simple Python π hashmap solution | InjySarhan | 1 | 125 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,349 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1538489/Python3-dictionary | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
"""
7 8 5 3 2 1 dif = -2
previous 9. 10. 8. 5. 4 3
key 7 8. 5 3 4 1
previoulen 1 1 2 3 1 4
key is the ending integer in subsequence,
value is the length of subsequence ending with key
ma
"""
mapping = {}
for i in arr:
previous = i - difference
if previous not in mapping.keys():
mapping[i] = 1
else:
mapping[i] = mapping[previous] + 1
res = max(mapping.values())
return res | longest-arithmetic-subsequence-of-given-difference | [Python3] dictionary | zhanweiting | 1 | 102 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,350 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1274399/python-three-line-or-clean-and-concise-or | class Solution:
def longestSubsequence(self, arr: List[int], d: int) -> int:
f=defaultdict(int)
for i in arr:f[i] = max(1,f[i-d]+1)
return max(list(f.values())) | longest-arithmetic-subsequence-of-given-difference | python three line | clean and concise | | chikushen99 | 1 | 134 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,351 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1090197/Python3-dp | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
ans = 0
seen = {}
for x in arr:
seen[x] = 1 + seen.get(x-difference, 0)
ans = max(ans, seen[x])
return ans | longest-arithmetic-subsequence-of-given-difference | [Python3] dp | ye15 | 1 | 90 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,352 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/2840521/python-solution-Longest-Arithmetic-Subsequence-of-Given-Difference | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
n = len(arr)
dp = {}
ans = 0
for i in range(n):
k = arr[i]
temp = 0
if (k - difference) in dp:
temp = dp[k - difference]
dp[k] = 1 + temp
ans = max(ans, dp[k])
return max(ans,1) | longest-arithmetic-subsequence-of-given-difference | python solution Longest Arithmetic Subsequence of Given Difference | sarthakchawande14 | 0 | 1 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,353 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/2536578/Python-easy-to-read-and-understand-or-hashmap-dp | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
d = collections.defaultdict(int)
t = [1 for _ in range(len(arr))]
#res = 0
for i, num in enumerate(arr):
if num-difference in d:
t[i] = t[d[num-difference]] + 1
d[num] = i
#print(t)
return max(t) | longest-arithmetic-subsequence-of-given-difference | Python easy to read and understand | hashmap dp | sanial2001 | 0 | 40 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,354 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/2492149/python-3-or-simple-dp-or-O(n)O(n) | class Solution:
def longestSubsequence(self, nums: List[int], difference: int) -> int:
dp = collections.defaultdict(lambda: 0)
for num in nums:
dp[num] = 1 + dp[num - difference]
return max(dp.values()) | longest-arithmetic-subsequence-of-given-difference | python 3 | simple dp | O(n)/O(n) | dereky4 | 0 | 26 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,355 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/2317579/PYHTON-or-HASHMAP-SOL-or-EXPLAINED-or-FAST-orSIMPLE-or | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
d = defaultdict(int)
for num in arr:
if num - difference in d:
d[num] = d[num - difference] + 1
else:
d[num] = 1
return max((d[x] for x in d)) | longest-arithmetic-subsequence-of-given-difference | PYHTON | HASHMAP SOL | EXPLAINED | FAST |SIMPLE | | reaper_27 | 0 | 72 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,356 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1558265/Python3-DP-Time%3A-O(n)-and-Space%3A-O(n) | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
# dp and map
# Time: O(n)
# Space: O(n)
dp = [1] * len(arr)
arr_dict = defaultdict(int)
for i,val in enumerate(arr): # O(n)
if val - difference in arr_dict:
dp[i] = dp[arr_dict[val-difference]] + 1
arr_dict[val] = i
return max(dp) | longest-arithmetic-subsequence-of-given-difference | [Python3] DP - Time: O(n) & Space: O(n) | jae2021 | 0 | 90 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,357 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1274386/Two-approaches-to-help-you-out-iterative-and-than-optimizing-using-dictionary | class Solution:
def longestSubsequence(self, arr: List[int], d: int) -> int:
n=len(arr)
dp= [1]*(n)
ans=1
for i in range(1,n):
for j in range(i):
if arr[i]-arr[j] ==d:
dp[i] = max(dp[i],dp[j]+1)
return max(dp) | longest-arithmetic-subsequence-of-given-difference | Two approaches to help you out , iterative and than optimizing using dictionary | chikushen99 | 0 | 82 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,358 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1274386/Two-approaches-to-help-you-out-iterative-and-than-optimizing-using-dictionary | class Solution:
def longestSubsequence(self, arr: List[int], d: int) -> int:
f=defaultdict(int)
for i in arr:f[i] = max(1,f[i-d]+1)
return max(list(f.values())) | longest-arithmetic-subsequence-of-given-difference | Two approaches to help you out , iterative and than optimizing using dictionary | chikushen99 | 0 | 82 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,359 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1179782/Welcome-suggestions-for-improvement!-I-don't-want-to-use-Counter() | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
# iterate over array
# create a hash map to store each number and their longest sequence so far
# for each number check if num-difference already exists
# if yes, extend the previous longest sequence by 1 (current number is a qualified number just found)
# otherwise, add the number to the hashmap with default occurence 1
# I have to use index i to make sure that the second if condition only checks previous keys
# edge case: arr = [4,12,10,0,-2,7,-8,9,-9,-12,-12,8,8]
# difference = 0
maps = {}
for i, num in enumerate(arr):
if num not in maps:
maps[num] = [1, i]
if num - difference in maps and maps[num-difference][1] < i: # previous numbers only, not including the current one
maps[num] = [maps[num-difference][0] + 1, i]
# print(maps)
return max([v[0] for v in maps.values()]) | longest-arithmetic-subsequence-of-given-difference | Welcome suggestions for improvement! I don't want to use Counter() | Yan_Air | 0 | 44 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,360 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/872904/Parallel-waiting%3A-quite-similar-to-792%3A-Number-of-Matching-Subsequences | class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
waiting = {}
for num in arr:
previous = waiting.pop(num, 0)
waiting[num+difference] = max(waiting.get(num+difference, 0), previous + 1)
# print(waiting)
return max(waiting.values()) | longest-arithmetic-subsequence-of-given-difference | Parallel waiting: quite similar to 792: Number of Matching Subsequences | Joe_Bao | 0 | 76 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,361 |
https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/398436/Solution-in-Python-3-(beats-100.00-)-(five-lines) | class Solution:
def longestSubsequence(self, A: List[int], k: int) -> int:
D, C = {}, {}
for a in A:
if a not in D: D[a], C[a+k] = 1, a
if a in C: C[a+k], D[C.pop(a)] = C[a], D[C[a]] + 1
return max(D.values())
- Junaid Mansuri
(LeetCode ID)@hotmail.com | longest-arithmetic-subsequence-of-given-difference | Solution in Python 3 (beats 100.00 %) (five lines) | junaidmansuri | 0 | 113 | longest arithmetic subsequence of given difference | 1,218 | 0.518 | Medium | 18,362 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/1742414/very-easy-to-understand-using-backtracking-python3 | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
def solve(i,j,grid,vis,val):
# print(i,j,grid,vis,val)
if(i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 0 or vis[i][j]):
# print(i,m,j,n)
return val
vis[i][j] = True
a = solve(i,j-1,grid,vis,val+grid[i][j])
b = solve(i,j+1,grid,vis,val+grid[i][j])
c = solve(i+1,j,grid,vis,val+grid[i][j])
d = solve(i-1,j,grid,vis,val+grid[i][j])
vis[i][j] = False
return max(a,b,c,d)
ma = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if(grid[i][j] != 0):
vis = [[False for i in range(len(grid[0]))] for j in range(len(grid))]
ma = max(ma,solve(i,j,grid,vis,0))
return ma | path-with-maximum-gold | very easy to understand using backtracking, python3 | jagdishpawar8105 | 1 | 99 | path with maximum gold | 1,219 | 0.64 | Medium | 18,363 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/1477458/Python3-Solution-with-using-backtracking | class Solution:
def __init__(self):
self.max_gold = 0
def backtracking(self, grid, i, j, cur_gold):
cur_val = grid[i][j]
grid[i][j] = 0
if i > 0 and grid[i - 1][j] != 0:
self.backtracking(grid, i - 1, j, [cur_gold[0] + cur_val])
if i < len(grid) - 1 and grid[i + 1][j] != 0:
self.backtracking(grid, i + 1, j, [cur_gold[0] + cur_val])
if j > 0 and grid[i][j - 1] != 0:
self.backtracking(grid, i, j - 1, [cur_gold[0] + cur_val])
if j < len(grid[0]) - 1 and grid[i][j + 1] != 0:
self.backtracking(grid, i, j + 1, [cur_gold[0] + cur_val])
self.max_gold = max(self.max_gold, cur_gold[0] + cur_val)
grid[i][j] = cur_val
def getMaximumGold(self, grid: List[List[int]]) -> int:
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] != 0:
self.backtracking(grid, i, j, [0])
return self.max_gold | path-with-maximum-gold | [Python3] Solution with using backtracking | maosipov11 | 1 | 92 | path with maximum gold | 1,219 | 0.64 | Medium | 18,364 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/985524/Python-Solution-DFS | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
visited = []
for i in range(m):
visited.append([False]*n)
def dfs(i,j,temp):
if i<0 or i>=m or j<0 or j>=n or visited[i][j] == True or grid[i][j] == 0:
return 0
ans1 = temp
visited[i][j] = True
if i+1 < m:
ans1 = max(ans1,dfs(i+1,j,temp+grid[i+1][j]))
if i-1>=0:
ans1 = max(ans1,dfs(i-1,j,temp+grid[i-1][j]))
if j+1<n:
ans1 = max(ans1,dfs(i,j+1,temp+grid[i][j+1]))
if j-1>=0:
ans1 = max(ans1,dfs(i,j-1,temp+grid[i][j-1]))
visited[i][j] = False
return ans1
max_path = 0
for i in range(m):
for j in range(n):
if grid[i][j]!=0:
max_path = max(max_path,dfs(i,j,grid[i][j]))
return max_path | path-with-maximum-gold | Python Solution DFS | SaSha59 | 1 | 312 | path with maximum gold | 1,219 | 0.64 | Medium | 18,365 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/750542/Python-Backtracking-or-DFS-simple-Solution | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
res = 0
check = [ [False]*len(grid[0]) for _ in range(len(grid)) ]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]:
res = max(res, self.backtrack(grid,i,j,check))
return res
def backtrack(self, grid, i, j,check):
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or check[i][j] or grid[i][j] == 0:
return 0
check[i][j] = True
down = self.backtrack(grid, i+1, j, check)
up = self.backtrack(grid, i-1, j, check)
right = self.backtrack(grid, i, j+1, check)
left = self.backtrack(grid, i, j-1, check)
check[i][j] = False
return max(down, max(up, max(left, right)))+grid[i][j] | path-with-maximum-gold | [Python] Backtracking | DFS simple Solution | Prodyte | 1 | 149 | path with maximum gold | 1,219 | 0.64 | Medium | 18,366 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/2804581/Python-Solution-oror-Beats-93 | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
vis = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
a_vis = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
def isvalid(i,j):
if(i <0 or j <0 or i == len(grid) or j == len(grid[0])):
return False
return True
def get_adj(i, j, vis):
sides = [[-1,0], [1,0], [0, 1], [0, -1]]
retval = []
for a,b in sides:
x,y = a+ i, b+j
if(isvalid(x, y) and not vis[x][y] and grid[x][y] !=0):
retval.append([x,y])
return retval
self.ans = 0
def recursive(grid, vis, i, j, cur):
a_vis[i][j] = True
cur += grid[i][j]
self.ans = max(cur, self.ans)
vis[i][j] = True
for a, b in get_adj(i,j, vis):
recursive(grid, vis, a, b, cur)
vis[i][j] = False
for i in range(len(grid)):
for j in range(len(grid[0])):
if(not a_vis[i][j]):
recursive(grid, vis, i, j, 0)
return self.ans | path-with-maximum-gold | Python Solution || Beats 93% | geek_thor | 0 | 21 | path with maximum gold | 1,219 | 0.64 | Medium | 18,367 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/2502763/Python3-or-Backtracking | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def helper(i, j, visited):
if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 0 or (i,j) in visited:
return 0
visited.add((i,j))
d = helper(i+1, j, visited)
u = helper(i-1, j, visited)
r = helper(i, j+1, visited)
l = helper(i, j-1, visited)
visited.discard((i,j))
return grid[i][j] + max(d, u, r, l)
max_gold = 0
for i in range(m):
for j in range(n):
if grid[i][j]:
max_gold = max(max_gold, helper(i, j, set()))
return max_gold | path-with-maximum-gold | Python3 | Backtracking | Ploypaphat | 0 | 128 | path with maximum gold | 1,219 | 0.64 | Medium | 18,368 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/2469139/Python3-or-Recursion-%2B-Backtracking-Solution | class Solution:
#Time-Complexity: O(m*n*4^max(m,n)) -> since in worst case, you call rec. helper function
#m*n times if input has all cells with pos. gold and rec. call branching factor is 4 and
#the height of rec. tree is at most max(m,n) going across the grid input!
#Space-Complexity:O(max(m,n))
def getMaximumGold(self, grid: List[List[int]]) -> int:
#Approach: Utilize recursion w/ backtracking!
#Basically, find the max gold you can get by recursing along all 4 directions!
#Get the max of those 4 values and add the current cell amount of gold and return the
#info to parent caller! This would indicate that from parent cell, recursing along
#the current cell would give that max amount of gold in the direction!
n, m = len(grid), len(grid[0])
ans = 0
#visited will be boolean array -> 1 if already visited 0 else!
visited = [[0 for _ in range(m)]for _ in range(n)]
def helper(r, c):
nonlocal n, m, visited
#base case: out of bounds, already visited, or cell with 0 gold! -> Want to immediately
#return and not recurse any further!
if(r < 0 or r >= n or
c < 0 or c >= m or
(r, c) in visited or
grid[r][c] == 0):
return 0
#if not base case, current [r,c] cell is valid!
#mark it as visited!
visited[r][c] = 1
#after marking current cell as visited, we need to recurse along the 4 neighboring
#cell positions and get the best direction!
up = helper(r -1, c)
left = helper(r, c-1)
right = helper(r, c+1)
down = helper(r + 1, c)
#we need to take max out of 4 local variable values -> we need to find max gold
#we can get from recursing along all possible 4 paths from current cell!
maximum = max(down, max(right, max(up, left)))
#before returning the result to parent caller, we need to backtrack and restore
#visited bool array!
visited[r][c] = 0
#then, max gold path starting from rth row and cth column cell will equal...
return grid[r][c] + maximum
for i in range(n):
for j in range(m):
#as long as ith row and jth column cell entry has postiive amount of gold,
#recurse from there!
if(grid[i][j] > 0):
cur_result = helper(i, j)
ans = max(ans, cur_result)
return ans
#traverse each cell of grid and if cell has pos. amount of gold recurse from there!
for i in range(n):
for j in range(m):
if(grid[i][j] > 0):
helper(i, j, 0)
visited = set()
return ans | path-with-maximum-gold | Python3 | Recursion + Backtracking Solution | JOON1234 | 0 | 37 | path with maximum gold | 1,219 | 0.64 | Medium | 18,369 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/2318324/PYTHON-or-93.50-FASTER-or-EXPLAINED-or-DEPTH-FIRST-SEARCH-or-BACKTRACKING-or | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
rows,cols = len(grid) , len(grid[0])
def dfs(r,c):
cpy = grid[r][c]
grid[r][c] = 0
ans = 0
for x,y in ((r+1,c),(r-1,c),(r,c-1),(r,c+1)):
if 0 <= x < rows and 0 <= y < cols and grid[x][y] != 0:
ans = max(ans, dfs(x,y))
grid[r][c] = cpy
return ans + cpy
ans = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] != 0:
ans = max(ans,dfs(i,j))
return ans | path-with-maximum-gold | PYTHON | 93.50% FASTER | EXPLAINED | DEPTH FIRST SEARCH | BACKTRACKING | | reaper_27 | 0 | 132 | path with maximum gold | 1,219 | 0.64 | Medium | 18,370 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/2309108/Python-Plain-Backtracking | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
max_gold = 0
end_row = len(grid)
end_col = len(grid[0])
def dfs(r,c,gold):
## base case
if not (0<=r<end_row and 0<=c<end_col and grid[r][c]>0):
nonlocal max_gold
max_gold = max(max_gold, gold)
return
## recursion relationship
gold+= grid[r][c]
grid[r][c] *= -1 ## mark visited
dfs(r+1,c,gold)
dfs(r-1,c,gold)
dfs(r,c+1,gold)
dfs(r,c-1,gold)
grid[r][c] *= -1 # reset
for r in range(end_row):
for c in range(end_col):
if grid[r][c] != 0:
dfs(r,c,0)
return max_gold | path-with-maximum-gold | Python Plain Backtracking | Abhi_009 | 0 | 69 | path with maximum gold | 1,219 | 0.64 | Medium | 18,371 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/1667613/Python-clean-dfs-solution | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def valid(x, y):
return x>=0 and x<=m-1 and y>=0 and y<=n-1
def dfs(x, y):
stack = [(x, y, grid[x][y], {(x, y)})]
res = 0
while stack:
p, q, point, visited = stack.pop()
res = max(res, point)
for dx, dy in [[-1, 0], [1, 0], [0, 1], [0, -1]]:
if valid(p+dx, q+dy) and (p+dx, q+dy) not in visited and grid[p+dx][q+dy] != 0:
stack.append((p+dx, q+dy, point + grid[p+dx][q+dy], visited | {(p+dx, q+dy)}))
return res
tot = 0
for i in range(m):
for j in range(n):
if grid[i][j] != 0:
tot = max(tot, dfs(i, j))
return tot | path-with-maximum-gold | Python clean dfs solution | byuns9334 | 0 | 186 | path with maximum gold | 1,219 | 0.64 | Medium | 18,372 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/1623799/Faster-than-73-and-space-efficient-than-98. | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
def backtrack(currRow, currCol):
ans = 0
# checking for out of bounds
if currRow < 0 or currCol < 0 or currRow == rows or currCol == cols:
return 0
# if cell gold is 0 then return
if grid[currRow][currCol] == 0:
return 0
gold = grid[currRow][currCol]# to apply backtracking storing the value of current gold
grid[currRow][currCol] = 0# setting the cell visited to 0
ans = max(ans, backtrack(currRow - 1, currCol))
ans = max(ans, backtrack(currRow + 1, currCol))
ans = max(ans, backtrack(currRow, currCol - 1))
ans = max(ans, backtrack(currRow, currCol + 1))
grid[currRow][currCol] = gold# backtracking
return ans + grid[currRow][currCol]# this will be added to the 4 recursive calls above
ans = 0
for r in range(rows):
for c in range(cols):
ans = max(ans, backtrack(r, c))
return ans | path-with-maximum-gold | Faster than 73% and space efficient than 98%. | guptaanshik1 | 0 | 75 | path with maximum gold | 1,219 | 0.64 | Medium | 18,373 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/1508439/WEEB-DOES-PYTHON-BFS | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
queue = deque([])
max_gold = 0
for x in range(row):
for y in range(col):
if grid[x][y] != 0:
queue.append((x, y, [(x,y)], grid[x][y]))
max_gold = max(max_gold, self.bfs(row, col, grid, queue))
return max_gold
def bfs(self, row, col, grid, queue):
curMaxGold = 0
while queue:
x, y, visited, curGold = queue.popleft()
if curGold > curMaxGold:
curMaxGold = curGold
for nx,ny in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 0<=nx<row and 0<=ny<col and grid[nx][ny] != 0 and (nx,ny) not in visited:
queue.append((nx, ny, visited +[(nx,ny)], curGold + grid[nx][ny]))
return curMaxGold | path-with-maximum-gold | WEEB DOES PYTHON BFS | Skywalker5423 | 0 | 200 | path with maximum gold | 1,219 | 0.64 | Medium | 18,374 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/1376013/Python3-or-Backtracking | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
visited=[[False for i in range(len(grid[0]))] for j in range(len(grid))]
gold=0
self.ans=0
for i in range(len(grid)):
for j in range(len(grid[0])):
self.solve(i,j,grid,visited,gold)
return self.ans
def solve(self,row,col,grid,visited,gold):
if self.validcell(row,col,grid,visited):
gold+=grid[row][col]
visited[row][col]=True
if row-1>=0 and visited[row-1][col]==False:
self.solve(row-1,col,grid,visited,gold)
visited[row-1][col]=False
if row+1<len(grid) and visited[row+1][col]==False:
self.solve(row+1,col,grid,visited,gold)
visited[row+1][col]=False
if col-1>=0 and visited[row][col-1]==False:
self.solve(row,col-1,grid,visited,gold)
visited[row][col-1]=False
if col+1<len(grid[0]) and visited[row][col+1]==False:
self.solve(row,col+1,grid,visited,gold)
visited[row][col+1]=False
self.ans=max(self.ans,gold)
visited[row][col]=False
return
def validcell(self,row,col,grid,visited):
if grid[row][col]!=0 and visited[row][col]==False:
return True
else:
return False | path-with-maximum-gold | Python3 | Backtracking | swapnilsingh421 | 0 | 74 | path with maximum gold | 1,219 | 0.64 | Medium | 18,375 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/1090211/Python3-backtracking | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def fn(i, j):
"""Collect maximum gold from (i, j) via backtracking."""
if grid[i][j] <= 0: return 0
grid[i][j] *= -1 # mark as visited
ans = 0
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n:
ans = max(ans, fn(ii, jj) - grid[i][j])
grid[i][j] *= -1 # backtracking
return ans
return max(fn(i, j) for i in range(m) for j in range(n) if grid[i][j]) | path-with-maximum-gold | [Python3] backtracking | ye15 | 0 | 107 | path with maximum gold | 1,219 | 0.64 | Medium | 18,376 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/789000/python3-recursively-stepping-through-grid | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
# walk through grid
# if finding a non-zero value
# call helper function to recursively check resulting sum
# update max_sum if larger
# helper function can step in 4 different directions
# point is to find the greatest path of available directions
# but "paint" cells negative on entry to prevent revisiting
# unpaint when unwinding the recursive calls (back to positive)
# to avoid messing up future calls
# return collected gold
# O(MN + K * 4^K) time
# O(MN) "height" or worst case stack calls
def rcrs(r, c):
grid[r][c] *= -1
max_path = 0
for dr, dc in [(-1,0),(0,1),(1,0),(0,-1)]:
if (0 <= r+dr < len(grid)) and (0 <= c+dc < len(grid[0])):
if grid[r+dr][c+dc] > 0:
max_path = max(max_path, rcrs(r+dr, c+dc))
grid[r][c] *= -1
return grid[r][c] + max_path
# grid traversal and function calls
max_sum = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] > 0:
max_sum = max(max_sum, rcrs(i,j))
return max_sum | path-with-maximum-gold | python3 - recursively stepping through grid | dachwadachwa | 0 | 92 | path with maximum gold | 1,219 | 0.64 | Medium | 18,377 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/605231/Python-Simple-Backtracking | class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
if m==0:
return 0
ans = 0
def dfs(i,j):
if i<0 or i>=m or j>=n or j<0 or grid[i][j]<=0:return 0
grid[i][j]*=-1
a = dfs(i+1,j)
b = dfs(i-1,j)
c = dfs(i,j+1)
d = dfs(i,j-1,)
grid[i][j]*=-1
return grid[i][j] + max(a,b,c,d)
for x in range(m):
for y in range(n):
if grid[x][y]!=0:
ans = max(ans,dfs(x,y))
return ans | path-with-maximum-gold | [Python] Simple Backtracking | spongeb0b | 0 | 102 | path with maximum gold | 1,219 | 0.64 | Medium | 18,378 |
https://leetcode.com/problems/path-with-maximum-gold/discuss/398377/Python-3-(DFS)-(nine-lines) | class Solution:
def getMaximumGold(self, G: List[List[int]]) -> int:
M, N, V, m = len(G), len(G[0]), set(), [0]
def dfs(i, j, t):
V.add((i,j))
for k,l in (i-1,j),(i,j+1),(i+1,j),(i,j-1):
if 0 <= k < M and 0 <= l < N and G[k][l] and (k,l) not in V: dfs(k, l, t + G[k][l])
m[0], _ = max(m[0], t), V.remove((i,j))
for i,j in itertools.product(range(M),range(N)):
if G[i][j]: dfs(i, j, G[i][j])
return m[0]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | path-with-maximum-gold | Python 3 (DFS) (nine lines) | junaidmansuri | 0 | 327 | path with maximum gold | 1,219 | 0.64 | Medium | 18,379 |
https://leetcode.com/problems/count-vowels-permutation/discuss/398231/Dynamic-programming-in-Python-with-in-depth-explanation-and-diagrams | class Solution:
def countVowelPermutation(self, n: int) -> int:
dp_array = [[0] * 5 for _ in range(n + 1)]
dp_array[1] = [1, 1, 1, 1, 1]
for i in range(2, n + 1):
# a is allowed to follow e, i, or u.
dp_array[i][0] = dp_array[i - 1][1] + dp_array[i - 1][2] + dp_array[i - 1][4]
# e is allowed to follow a or i.
dp_array[i][1] = dp_array[i - 1][0] + dp_array[i - 1][2]
# i is allowed to follow e or o.
dp_array[i][2] = dp_array[i - 1][1] + dp_array[i - 1][3]
# o is allowed to follow i
dp_array[i][3] = dp_array[i - 1][2]
# u is allowed to follow i or o.
dp_array[i][4] = dp_array[i - 1][2] + dp_array[i - 1][3]
return sum(dp_array[n]) % ((10 ** 9) + 7) | count-vowels-permutation | Dynamic programming in Python with in-depth explanation and diagrams | Hai_dee | 36 | 1,600 | count vowels permutation | 1,220 | 0.605 | Hard | 18,380 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2391936/Python-oror-Detailed-Explanation-oror-Fast-Than-91-oror-Less-Than-93-oror-DP-oror-Fast-oror-MATH | class Solution:
def countVowelPermutation(self, n: int) -> int:
# dp[i][j] means the number of strings of length i that ends with the j-th vowel.
dp = [[1] * 5] + [[0] * (5) for _ in range(n - 1)]
moduler = math.pow(10, 9) + 7
for i in range(1, n):
# For vowel a
dp[i][0] = (dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][4]) % moduler
# For vowel e
dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % moduler
# For vowel i
dp[i][2] = (dp[i - 1][1] + dp[i - 1][3]) % moduler
# For vowel o
dp[i][3] = (dp[i - 1][2]) % moduler
# For vowel u
dp[i][4] = (dp[i - 1][2] + dp[i - 1][3]) % moduler
return int(sum(dp[-1]) % moduler) | count-vowels-permutation | π₯ Python || Detailed Explanation β
|| Fast Than 91% || Less Than 93% || DP || Fast || MATH | wingskh | 33 | 1,700 | count vowels permutation | 1,220 | 0.605 | Hard | 18,381 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2391936/Python-oror-Detailed-Explanation-oror-Fast-Than-91-oror-Less-Than-93-oror-DP-oror-Fast-oror-MATH | class Solution:
def countVowelPermutation(self, n: int) -> int:
moduler = math.pow(10, 9) + 7
a, e, i, o, u = [1] * 5
for _ in range(n - 1):
a, e, i, o, u = map(lambda x: x % moduler, [(e + i + u), (a + i), (e + o), (i), (i + o)])
return int((a + e + i+ o + u) % moduler) | count-vowels-permutation | π₯ Python || Detailed Explanation β
|| Fast Than 91% || Less Than 93% || DP || Fast || MATH | wingskh | 33 | 1,700 | count vowels permutation | 1,220 | 0.605 | Hard | 18,382 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2390077/99.63-faster-or-python3-or-solution | class Solution:
def countVowelPermutation(self, n: int) -> int:
MOD = pow(10,9) + 7
def multiply(a, b):
result = [ [0] * len(b[0]) for _ in range(len(a))]
# This is just simple matrix multiplicaiton
for i in range(len(a)):
for j in range(len(b[0])):
for k in range(len(a[0])):
result[i][j] += (a[i][k] * b[k][j]) % MOD
result[i][j] %= MOD
return result
adjacency_matrix = [
[0,1,0,0,0],
[1,0,1,0,0],
[1,1,0,1,1],
[0,0,1,0,1],
[1,0,0,0,0]
]
result = [[0]*5 for _ in range(5)]
for i in range(5):
result[i][i] = 1
s = 0
n -= 1
while n:
if n & 1:
result = multiply(adjacency_matrix,result)
n >>= 1
adjacency_matrix = multiply(adjacency_matrix,adjacency_matrix)
for i in range(5):
s += sum(result[i])
return s % MOD | count-vowels-permutation | 99.63% faster | python3 | solution | vimla_kushwaha | 9 | 598 | count vowels permutation | 1,220 | 0.605 | Hard | 18,383 |
https://leetcode.com/problems/count-vowels-permutation/discuss/1413566/explained-CLEAN-O(N)-DP(remaining-choices)-depends-on-previous-choice | class Solution:
def countVowelPermutation(self, n: int) -> int:
vowels = {'a', 'e', 'i', 'o', 'u'}
self.adj = {
'0': list(vowels),
'a': ['e'],
'e': ['a', 'i'],
'i': list(vowels - {'i'}),
'o': ['i', 'u'],
'u': ['a']
}
@functools.cache
def ways(prev, n):
if n == 0: return 1
res = 0
for cur in self.adj[prev]:
res = (res + ways(cur,n-1)) % (10**9+7)
return res
return ways('0', n)
# LOG N is possible WOW https://leetcode.com/problems/count-vowels-permutation/discuss/398173/C%2B%2B-Bottom-up-Recursive-DPs-O(n)-and-Matrix-Exponentiation-O(logn) | count-vowels-permutation | explained CLEAN O(N) DP(remaining choices), depends on previous choice | yozaam | 4 | 135 | count vowels permutation | 1,220 | 0.605 | Hard | 18,384 |
https://leetcode.com/problems/count-vowels-permutation/discuss/398241/Solution-in-Python-3-(DP)-(three-lines)-(-O(n)-time-)-(-O(1)-space-) | class Solution:
def countVowelPermutation(self, n: int) -> int:
C, m = [1]*5, 10**9 + 7
for i in range(n-1): C = [(C[1]+C[2]+C[4]) % m, (C[0]+C[2]) % m, (C[1]+C[3]) % m, C[2] % m, (C[2]+C[3]) % m]
return sum(C) % m
- Junaid Mansuri
(LeetCode ID)@hotmail.com | count-vowels-permutation | Solution in Python 3 (DP) (three lines) ( O(n) time ) ( O(1) space ) | junaidmansuri | 2 | 289 | count vowels permutation | 1,220 | 0.605 | Hard | 18,385 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2396245/Python-Solution-or-1D-Dynamic-Programming-or-100-Faster | class Solution:
def countVowelPermutation(self, n: int) -> int:
store = [1,1,1,1,1]
MOD = 10**9 + 7
A, E, I, O, U = 0, 1, 2, 3, 4
for _ in range(1,n):
a, e, i, o, u = store
store[A] = (e + i + u) % MOD
store[E] = (a + i) % MOD
store[I] = (e + o) % MOD
store[O] = (i)
store[U] = (i + o) % MOD
return sum(store) % MOD | count-vowels-permutation | Python Solution | 1D Dynamic Programming | 100% Faster | Gautam_ProMax | 1 | 23 | count vowels permutation | 1,220 | 0.605 | Hard | 18,386 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2395157/Easy-to-Understand-Python-Solution | class Solution:
def countVowelPermutation(self, n: int) -> int:
a, e, i, o, u = 1, 1, 1, 1, 1 #
for _ in range(n - 1):
a, e, i, o, u = e, a + i, e + o + a + u, i + u, a
return (a + e + i + o + u) % (10**9 + 7) | count-vowels-permutation | Easy to Understand Python Solution | user5262rR | 1 | 20 | count vowels permutation | 1,220 | 0.605 | Hard | 18,387 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2394874/Python-Easy-DP | class Solution:
def countVowelPermutation(self, n: int) -> int:
myStore = {'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1}
for i in range(n - 1):
myStore['a'],myStore['e'],myStore['i'],myStore['o'],myStore['u'] = myStore['e'] + myStore['i'] + myStore['u'],myStore['a'] + myStore['i'],myStore['e'] + myStore['o'], myStore['i'], myStore['i'] + myStore['o']
return sum(myStore.values()) % (10**9+7) | count-vowels-permutation | Python Easy DP | syji | 1 | 10 | count vowels permutation | 1,220 | 0.605 | Hard | 18,388 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2391652/Dynamic-Programming-or-Top-Down-or-Recursion-with-Memoization-or-Easy-Understanding | class Solution:
def countVowelPermutation(self, n: int) -> int:
followed_by = {'a':{'e'},
'e':{'a', 'i'},
'o':{'i', 'u'},
'u':{'a'},
'i':{'a', 'e', 'o', 'u'}
}
cache = {}
def rec(ln=0, prev=None):
if ln==n:
return 1
ans = 0
if not prev:
for vowel in followed_by:
if (ln+1, vowel) not in cache:
cache[(ln+1, vowel)] = rec(ln+1, vowel)
ans += cache[(ln+1, vowel)]
else:
for vowel in followed_by[prev]:
if (ln+1, vowel) not in cache:
cache[(ln+1, vowel)] = rec(ln+1, vowel)
ans += cache[(ln+1, vowel)]
cache[(ln, prev)] = ans
return cache[(ln, prev)]
return rec()%(10**9+7) | count-vowels-permutation | Dynamic Programming | Top Down | Recursion with Memoization | Easy-Understanding | bisrat_walle | 1 | 24 | count vowels permutation | 1,220 | 0.605 | Hard | 18,389 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2318505/PYTHON-or-EXPLAINED-or-MEMOIZATION-%2B-RECURSION-or-EASY-or-DP-or | class Solution:
def countVowelPermutation(self, n: int) -> int:
d = {"x":["a","e","i","o","u"],"a":["e"],"e":["a","i"],"i":["a","e","o","u"],"o":["i","u"],"u":["a"]}
dp = {}
def solve(character,n):
if n == 0: return 1
if (character,n) in dp: return dp[(character,n)]
ans = 0
for i in d[character]:
ans += solve(i,n-1)
dp[(character,n)] = ans
return ans
return solve("x",n) % 1000000007 | count-vowels-permutation | PYTHON | EXPLAINED | MEMOIZATION + RECURSION | EASY | DP | | reaper_27 | 1 | 63 | count vowels permutation | 1,220 | 0.605 | Hard | 18,390 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2730303/Python3-solution-using-a-for-loop-to-calculate-permutations-from-each-letter | class Solution:
def countVowelPermutation(self, n: int) -> int:
x = [1, 1, 1, 1, 1]
for i in range(n - 1):
new = [x[1], x[0] + x[2], x[0] + x[1] + x[3] + x[4], x[2] + x[4], x[0]]
x = new
res = sum(x) % (pow(10, 9) + 7)
return res | count-vowels-permutation | Python3 solution using a for loop to calculate permutations from each letter | thomwebb | 0 | 4 | count vowels permutation | 1,220 | 0.605 | Hard | 18,391 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2549033/Python-Easy-Solution! | class Solution:
def countVowelPermutation(self, n: int) -> int:
a, e, i, o, u = 0, 1, 2, 3, 4
mod = 10**9 + 7
dp = [1, 1, 1, 1, 1]
for _ in range(2, n + 1):
temp = dp
dp = [0, 0, 0, 0, 0]
dp[a] = (temp[e] + temp[i] + temp[u]) % mod
dp[e] = (temp[a] + temp[i]) % mod
dp[i] = (temp[e] + temp[o]) % mod
dp[o] = temp[i]
dp[u] = (temp[i] + temp[o]) % mod
return sum(dp) % mod | count-vowels-permutation | Python Easy Solution! | Manojkc15 | 0 | 48 | count vowels permutation | 1,220 | 0.605 | Hard | 18,392 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2418554/Pythonor-DP-or-Easy-to-undertand-or-beginner-or-Time-O(n)-orSpace-O(1) | class Solution:
def countVowelPermutation(self, n: int) -> int:
dp={'a':1,'e':1,'i':1,'o':1,'u':1}
for i in range(n-1):
dp1={}
for c in 'aeiou':
if c=='a':
dp1[c]=dp['e']
elif c=='e':
dp1[c]=dp['a']+dp['i']
elif c=="i":
dp1[c]=dp['a']+dp['e']+dp['o']+dp['u']
elif c=='o':
dp1[c]=dp['i']+dp['u']
elif c=='u':
dp1[c]=dp['a']
dp=dp1
mod=10**9+7
return sum(dp.values())%mod | count-vowels-permutation | Python| DP | Easy to undertand | beginner | Time O(n) |Space O(1) | user2559cj | 0 | 68 | count vowels permutation | 1,220 | 0.605 | Hard | 18,393 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2407074/Efficient-Python3-Solution-to-Count-Vowels-Permutation-using-DP | class Solution:
def countVowelPermutation(self, n: int) -> int:
op = [[],[1, 1, 1, 1, 1]]
a, e, i, o, u = 0, 1, 2, 3, 4
mod = 10**9 + 7
for j in range(2, n + 1):
op.append([0, 0, 0, 0, 0])
op[j][a] = (op[j-1][e] + op[j-1][i] + op[j-1][u]) % mod
op[j][e] = (op[j-1][a] + op[j-1][i]) % mod
op[j][i] = (op[j-1][e] + op[j-1][o]) % mod
op[j][o] = (op[j-1][i]) % mod
op[j][u] = (op[j-1][i] + op[j-1][o]) % mod
return sum(op[n])%mod | count-vowels-permutation | Efficient Python3 Solution to Count Vowels Permutation using DP | WhiteBeardPirate | 0 | 15 | count vowels permutation | 1,220 | 0.605 | Hard | 18,394 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2400206/Easy-Python-Solution | class Solution:
def countVowelPermutation(self, n: int) -> int:
a,e,i,o,u=1,1,1,1,1
M=10**9+7
for j in range(2,n+1):
ca=a
ce=e
ci=i
co=o
cu=u
a=(ce+ci+cu)%M
e=(ca+ci)%M
i=(ce+co)%M
o=ci%M
u=(ci+co)%M
return (a+e+i+o+u)%M | count-vowels-permutation | Easy Python Solution | a_dityamishra | 0 | 26 | count vowels permutation | 1,220 | 0.605 | Hard | 18,395 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2395383/Top-down-approach-using-dictionary | class Solution:
def countVowelPermutation(self, n: int) -> int:
v_dic = {'a': ['e'], 'e': ['a', 'i'], 'i':['a', 'e', 'o', 'u'],
'o':['i', 'u'], 'u':['a']}
@cache
def search(n, v):
num = 0
if n == 1:
return 1
next_v_lst = v_dic[v]
for next_v in next_v_lst:
num += search(n-1, next_v)
return num
return sum([search(n, v) for v in v_dic]) % (10**9+7) | count-vowels-permutation | Top-down approach using dictionary | JiaxuLi | 0 | 10 | count vowels permutation | 1,220 | 0.605 | Hard | 18,396 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2394966/Python-Bottom-Up-DP | class Solution:
def countVowelPermutation(self, n: int) -> int:
N = 10**9 + 7
dp = [[0] * 5 for _ in range(n)]
dp[0] = [1,1,1,1,1]
# Encode rules
for i in range(1, n):
dp[i][0] = dp[i-1][1]
dp[i][1] = dp[i-1][0] + dp[i-1][2]
dp[i][2] = dp[i-1][0] + dp[i-1][1] + dp[i-1][3] + dp[i-1][4]
dp[i][3] = dp[i-1][2] + dp[i-1][4]
dp[i][4] = dp[i-1][0]
return sum(dp[n-1]) % N | count-vowels-permutation | Python - Bottom-Up DP | Strafespey | 0 | 9 | count vowels permutation | 1,220 | 0.605 | Hard | 18,397 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2394926/Python-solution-or-Count-Vowels-Permutation | class Solution:
def countVowelPermutation(self, n: int) -> int:
dp = [[], [1,1,1,1,1]]
a,e,i,o,u = 0,1,2,3,4
mod = 10**9 + 7
for j in range(2, n+1):
dp.append([0,0,0,0,0])
dp[j][a] = ( dp[j-1][e] + dp[j-1][i] + dp[j-1][u] ) % mod
dp[j][e] = ( dp[j-1][a] + dp[j-1][i] ) % mod
dp[j][i] = ( dp[j-1][e] + dp[j-1][o] ) % mod
dp[j][o] = dp[j-1][i]
dp[j][u] = ( dp[j-1][i] + dp[j-1][o] ) % mod
return sum(dp[n]) % mod | count-vowels-permutation | Python solution | Count Vowels Permutation | nishanrahman1994 | 0 | 8 | count vowels permutation | 1,220 | 0.605 | Hard | 18,398 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2393761/Easy-Python-Solution-or-O(N)-or-Dynamic-programming | class Solution:
def countVowelPermutation(self, n: int) -> int:
dp = {"a":1, "e":1, "i":1, "o":1, "u":1}
for i in range(1, n):
e = dp["a"] + dp["i"]
a = dp["e"] + dp["i"] + dp["u"]
i = dp["e"] + dp["o"]
o = dp["i"]
u = dp["o"] + dp["i"]
dp["e"] = e
dp["a"] = a
dp["i"] = i
dp["o"] = o
dp["u"] = u
return sum(dp.values()) % 1000000007 | count-vowels-permutation | Easy Python Solution | O(N) | Dynamic programming | pivovar3al | 0 | 17 | count vowels permutation | 1,220 | 0.605 | Hard | 18,399 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.