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/longest-increasing-path-in-a-matrix/discuss/2054546/Python-Simple-Python-Solution-Using-DFS-and-Dynamic-Programming | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
points = [[0,1],[1,0],[0,-1],[-1,0]]
dp = [[0] * len(matrix[0]) for _ in range(len(matrix))]
def dfs(x,y):
if dp[x][y] == 0:
dp[x][y] = 1
for point in points:
path_x, path_y = point
if 0 <= path_x+x <len(matrix) and 0 <= path_y+y <len(matrix[0]) and matrix[x][y] < matrix[path_x + x][path_y + y]:
dp[x][y] = max(dp[x][y],dfs(path_x+x,path_y+y) +1)
return dp[x][y]
result = 1
for i in range(len(matrix)):
for j in range(len(matrix[0])):
result = max(result, dfs(i,j))
return result | longest-increasing-path-in-a-matrix | [ Python ] ✅✅ Simple Python Solution Using DFS and Dynamic Programming ✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 31 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,700 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2054472/Python-Solution-DFS-with-memorization | class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
m, n = len(matrix), len(matrix[0])
seen = {}
def findLongestPath(x, y, parent_val):
if x < 0 or x >= m or y < 0 or y >= n or matrix[x][y] <= parent_val:
return 0
if (x, y) in seen:
return seen[(x, y)]
seen[(x, y)] = 1 + max(findLongestPath(x + 1, y, matrix[x][y]), findLongestPath(x - 1, y, matrix[x][y]), findLongestPath(x, y + 1, matrix[x][y]), findLongestPath(x, y - 1, matrix[x][y]))
return seen[(x, y)]
for i in range(m):
for j in range(n):
findLongestPath(i, j, -1)
return max(seen.values()) | longest-increasing-path-in-a-matrix | Python Solution DFS with memorization | Kennyyhhu | 0 | 16 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,701 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2054014/Python3-or-DFS-%2B-Memo | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m = len(matrix)
n = len(matrix[0])
neighbours = [[0, 1], [0, -1], [1, 0], [-1, 0]]
isValid = lambda x, y: x > -1 and y > -1 and x < m and y < n
visited = set()
@cache
def getMaxPath(curr, prev=None):
visited.add(curr)
i = curr // n
j = curr % n
ret = 0
for nei in neighbours:
to_i = i + nei[0]
to_j = j + nei[1]
to = to_i * n + to_j
if to != prev and isValid(to_i, to_j) and to not in visited and matrix[to_i][to_j] > matrix[i][j]:
ret = max(ret, 1 + getMaxPath(to, curr))
visited.remove(curr)
return ret
ans = 1
for i in range(m):
for j in range(n):
ans = max(ans, getMaxPath(i*n+j) + 1)
return ans | longest-increasing-path-in-a-matrix | Python3 | DFS + Memo | DheerajGadwala | 0 | 12 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,702 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2053057/Python-or-Commented-or-Recursion-or-Memoization-or-DP-or-O(m*n) | # Recursive DFS DP Solution
# Time: O(m*n), Iterates through each cell in 2d list once.
# Space: O(m*n), For cellPathLengths(m x n List) (Plus some aditional memory for recursion stack.)
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
M, N = len(matrix), len(matrix[0]) # Length of rows and columns in 2d list.
cellPathLengths = [[0]*N for _ in range(M)] # 2d List containing the longest path starting at matrix[row][column] (Dynamic Programming).
def isValidCell(row: int, column: int) -> bool: # Checks if cell (row, column) is in the bounds of the 2d list.
return 0 <= row < M and 0 <= column < N
def dfs(row: int, column: int) -> int: # Depth First Search recursive loop.
if cellPathLengths[row][column]: return cellPathLengths[row][column] # If cell has been visited, return previously calculated path length.
cellValue = matrix[row][column] # Current cell value.
neighbors = ((row+1, column), (row-1, column), (row, column+1), (row, column-1)) # Possible cell neighbors in a tuple.
maxPathLength = 0
for neighborRow, neighborColumn in neighbors: # Iterates through possible neighbors.
if not isValidCell(neighborRow, neighborColumn): continue # Passes through out-of-bounds neighbors.
if not cellValue < matrix[neighborRow][neighborColumn]: continue # Passes neighbor with lower or equal value.
maxPathLength = max(maxPathLength, dfs(neighborRow, neighborColumn)) # Sets longest path found using DFS recursion with neighbor.
cellPathLengths[row][column] = 1 + maxPathLength # Sets current cell's value with longest path length found.
return cellPathLengths[row][column] # Returns longest path length.
maxPathLength = 0
for row in range(M): # Iterates through rows in 2d list.
for column in range(N): # Iterates through columns in 2d list.
pathLength = dfs(row, column) # DFS with current cell (row, cloumn), returning it's longest path length.
maxPathLength = max(maxPathLength, pathLength) # Sets longest path found from searched cells.
return maxPathLength # Returns longest path length in 2d list. | longest-increasing-path-in-a-matrix | Python | Commented | Recursion | Memoization | DP | O(m*n) | bensmith0 | 0 | 37 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,703 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2052739/python-3-oror-simple-recursion | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
@lru_cache(None)
def helper(i, j):
res = 1
if i and matrix[i][j] < matrix[i - 1][j]: # up
res = max(res, helper(i - 1, j) + 1)
if i != m - 1 and matrix[i][j] < matrix[i + 1][j]: # down
res = max(res, helper(i + 1, j) + 1)
if j and matrix[i][j] < matrix[i][j - 1]: # left
res = max(res, helper(i, j - 1) + 1)
if j != n - 1 and matrix[i][j] < matrix[i][j + 1]: # right
res = max(res, helper(i, j + 1) + 1)
return res
return max(helper(i, j) for i in range(m) for j in range(n)) | longest-increasing-path-in-a-matrix | python 3 || simple recursion | dereky4 | 0 | 10 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,704 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2041318/DFS-solutionj | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
self.ans = 0
@cache
def dfs(i, j):
ans = 1
val = 0
for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < len(matrix) and 0 <= y < len(matrix[0]):
if matrix[i][j] < matrix[x][y]:
val = max(dfs(x, y), val)
return ans + val
for i in range(len(matrix)):
for j in range(len(matrix[0])):
self.ans = max(dfs(i, j), self.ans)
return self.ans | longest-increasing-path-in-a-matrix | DFS solutionj | user6397p | 0 | 38 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,705 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1925712/90-fast-easy-to-understand-Python-code | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
def findMaxLength(x, y):
if x >= len(matrix) or y >= len(matrix[0]):
return 0
if pathMap[x][y] != 0:
return pathMap[x][y]
length = 0
curr = matrix[x][y]
maxPath = []
if x - 1 >= 0 and matrix[x-1][y] > curr:
maxPath.append(1 + findMaxLength(x-1, y))
if x + 1 < len(matrix) and matrix[x+1][y] > curr:
maxPath.append(1 + findMaxLength(x+1, y))
if y - 1 >= 0 and matrix[x][y-1] > curr:
maxPath.append(1 + findMaxLength(x, y-1))
if y + 1 < len(matrix[0]) and matrix[x][y+1] > curr:
maxPath.append(1 + findMaxLength(x, y+1))
if len(maxPath) == 0:
pathMap[x][y] = 1
return 1
else:
pathMap[x][y] = max(maxPath)
return max(maxPath)
maxLength = 0
pathMap = [[0] * len(matrix[0]) for _ in range(len(matrix))]
for i in range(0, len(matrix) + 1): # +1 for 1-D array
for j in range(0, len(matrix[0]) + 1): # +1 for 1-D array
maxLength = max(maxLength, findMaxLength(i, j))
return maxLength | longest-increasing-path-in-a-matrix | 90% fast easy to understand Python code | syxuan | 0 | 85 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,706 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1714297/Python-Super-simple-and-easy-understanding-DFS-solution-with-memorization | class Solution:
def bfs(self, matrix, parent, x, y, memo) -> int:
if x < 0 or y < 0 or x >= len(matrix) or y >= len(matrix[x]): return 0
if matrix[x][y] <= parent: return 0
if memo[x][y] != 0: return memo[x][y]
memo[x][y] = 1 + max(
self.bfs(matrix, matrix[x][y], x+1, y, memo),
self.bfs(matrix, matrix[x][y], x-1, y, memo),
self.bfs(matrix, matrix[x][y], x, y-1, memo),
self.bfs(matrix, matrix[x][y], x, y+1, memo)
)
return memo[x][y]
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
answer = 0
memo = [[0 for _ in row] for row in matrix]
for x in range(0, len(matrix)):
for y in range(0, len(matrix[x])):
if memo[x][y] == 0:
answer = max(answer, self.bfs(matrix, -1, x, y, memo))
return answer | longest-increasing-path-in-a-matrix | [Python] Super simple and easy understanding DFS solution with memorization | freetochoose | 0 | 109 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,707 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1539127/Python3-DFS-Time%3A-O(mn)-and-Space%3A-O(mn) | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
# DFS using memo
# Time: O(mn)
# Space: O(mn)
m = len(matrix)
n = len(matrix[0])
if m == 1 and n == 1:
return 1
memo = defaultdict(int)
def dfs(i,j,prev):
if i < 0 or j < 0 or i >= m or j >= n or matrix[i][j] <= prev:
return 0
if (i,j) in memo:
return memo[(i,j)]
curr = matrix[i][j]
dist = 1 + max(dfs(i+1,j,curr),dfs(i-1,j,curr),dfs(i,j+1,curr),dfs(i,j-1,curr))
memo[(i,j)] = dist
return dist
maxDist = 0
for i in range(m):
for j in range(n):
maxDist = max(maxDist, dfs(i,j,-1))
return maxDist | longest-increasing-path-in-a-matrix | [Python3] DFS - Time: O(mn) & Space: O(mn) | jae2021 | 0 | 100 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,708 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1362360/Python3%3A-329.-Longest-Increasing-Path-in-a-Matrix-(DP) | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
leaves = []
outdegrees = [[0 for col in matrix[0]] for row in matrix]
for row in range(len(matrix)):
for col in range(len(matrix[0])):
for r, c in self.get_neighbors(row, col, matrix):
if matrix[row][col] < matrix[r][c]:
outdegrees[row][col] += 1
for row in range(len(outdegrees)):
for col in range(len(outdegrees[0])):
if outdegrees[row][col] == 0:
leaves.append((row, col))
longest_path = 0
while leaves:
longest_path += 1
new_leaves = []
for out_r, out_c in leaves:
for n_r, n_c in self.get_neighbors(out_r, out_c, outdegrees):
if matrix[out_r][out_c] > matrix[n_r][n_c]:
outdegrees[n_r][n_c] -= 1
if outdegrees[n_r][n_c] == 0:
new_leaves.append((n_r, n_c))
leaves = new_leaves
return longest_path
def get_neighbors(self, r, c, matrix):
neighbors = []
for row, col in ((r, c + 1), (r, c - 1), (r + 1, c), (r - 1, c)):
if 0<=row<len(matrix) and 0<=col<len(matrix[0]):
neighbors.append((row, col))
return neighbors | longest-increasing-path-in-a-matrix | [Python3]: 329. Longest Increasing Path in a Matrix (DP) | ManmayB | 0 | 125 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,709 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1124660/Python-DFS-%2B-Memoization | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
def find_path(i, j):
'''Simple DFS'''
up, down = i - 1, i + 1
right, left = j + 1, j - 1
current = matrix[i][j]
# create list to hold values for paths
paths = [0] * 4
# move left
if left >= 0 and matrix[i][left] > current:
paths[0] = find_path(i, left)
# move right
if right < len(matrix[0]) and matrix[i][right] > current:
paths[1] = find_path(i, right)
# move up
if up >= 0 and matrix[up][j] > current:
paths[2] = find_path(up, j)
# move down
if down < len(matrix) and matrix[down][j] > current:
paths[3] = find_path(down, j)
ans = max(paths) + 1
return ans
max_path = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
path = find_path(i, j)
max_path = max(max_path, path)
return max_path | longest-increasing-path-in-a-matrix | Python DFS + Memoization | swatirama | 0 | 156 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,710 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1073125/Python-Solution-w-Backtracking | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
@functools.lru_cache(maxsize=None)
def backtrack(i, j):
result = 1
val = matrix[i][j]
matrix[i][j] = -1 # mark seen
for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
# below are a bunch of conditions to terminate
if not x >= 0 <= y: continue
if not x < len(matrix): continue
if not y < len(matrix[0]): continue
if matrix[x][y] == -1: continue
if matrix[x][y] <= val: continue
result = max(result, backtrack(x, y)+1) # calculate best score
matrix[i][j] = val # unmark seen (i.e, backtracking)
return result
result = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
result = max(backtrack(i, j), result)
return result | longest-increasing-path-in-a-matrix | Python Solution w/ Backtracking | dev-josh | 0 | 163 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,711 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/932372/Python-dfs-memoization-clear-solution | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
def max_path(row, col, last=float('-inf')):
if row >= len(matrix) or row < 0 or col >= len(matrix[0]) or col < 0:
return 0
if matrix[row][col] <= last:
return 0
if (row, col) in cache:
return cache[(row, col)]
else:
best = max(max_path(row+1, col, matrix[row][col]),
max_path(row-1, col, matrix[row][col]),
max_path(row, col+1, matrix[row][col]),
max_path(row, col-1, matrix[row][col])) + 1
cache[(row, col)] = best
return best
cache = {}
return max([max_path(i,j) for i in range(len(matrix)) for j in range(len(matrix[0]))] + [0]) | longest-increasing-path-in-a-matrix | Python dfs memoization clear solution | modusV | 0 | 138 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,712 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1811181/Python-SImplest-Toplogical-Sort | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
indegree = defaultdict(int)
graph = defaultdict(list)
queue = deque()
for r in range(m):
for c in range(n):
for r1, c1 in [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]:
if 0 <= r1 < m and 0 <= c1 < n and matrix[r1][c1] > matrix[r][c]:
graph[(r1, c1)].append((r, c))
indegree[(r, c)] += 1
if indegree[(r, c)] == 0: queue.append((r, c, 1))
while queue:
r, c, d = queue.popleft()
for r1, c1 in graph[(r, c)]:
indegree[(r1, c1)] -= 1
if indegree[(r1, c1)] == 0:
queue.append((r1, c1, d+1))
return d | longest-increasing-path-in-a-matrix | Python SImplest Toplogical Sort | totoslg | -1 | 48 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,713 |
https://leetcode.com/problems/patching-array/discuss/1432390/Python-3-easy-solution | class Solution:
def minPatches(self, nums: List[int], n: int) -> int:
ans, total = 0, 0
num_idx = 0
while total < n:
if num_idx < len(nums):
if total < nums[num_idx] - 1:
total = total * 2 + 1
ans += 1
else:
total += nums[num_idx]
num_idx += 1
else:
total = total * 2 + 1
ans += 1
return ans | patching-array | Python 3 easy solution | Andy_Feng97 | 1 | 231 | patching array | 330 | 0.4 | Hard | 5,714 |
https://leetcode.com/problems/patching-array/discuss/1196758/Python3-greedy | class Solution:
def minPatches(self, nums: List[int], n: int) -> int:
ans = prefix = k = 0
while prefix < n:
if k < len(nums) and nums[k] <= prefix + 1:
prefix += nums[k]
k += 1
else:
ans += 1
prefix += prefix + 1
return ans | patching-array | [Python3] greedy | ye15 | 1 | 140 | patching array | 330 | 0.4 | Hard | 5,715 |
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/1459342/Python3-or-O(n)-Time-and-O(n)-space | class Solution:
def isValidSerialization(self, preorder: str) -> bool:
stack = []
items = preorder.split(",")
for i, val in enumerate(items):
if i>0 and not stack:
return False
if stack:
stack[-1][1] -= 1
if stack[-1][1] == 0:
stack.pop()
if val != "#":
stack.append([val, 2])
return not stack | verify-preorder-serialization-of-a-binary-tree | Python3 | O(n) Time and O(n) space | Sanjaychandak95 | 3 | 73 | verify preorder serialization of a binary tree | 331 | 0.443 | Medium | 5,716 |
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/790197/Python3-image-water-flowing-through-the-tree | class Solution:
def isValidSerialization(self, preorder: str) -> bool:
outlet = 1
for x in preorder.split(","):
if outlet == 0: return False #intermediate
outlet += 1 if x != "#" else -1
return outlet == 0 #end result | verify-preorder-serialization-of-a-binary-tree | [Python3] image water flowing through the tree | ye15 | 2 | 132 | verify preorder serialization of a binary tree | 331 | 0.443 | Medium | 5,717 |
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/790197/Python3-image-water-flowing-through-the-tree | class Solution:
def isValidSerialization(self, preorder: str) -> bool:
stack = []
for n in preorder.split(","):
stack.append(n)
while stack[-2:] == ["#", "#"]:
stack.pop()
stack.pop()
if not stack: return False
stack[-1] = "#"
return stack == ["#"] | verify-preorder-serialization-of-a-binary-tree | [Python3] image water flowing through the tree | ye15 | 2 | 132 | verify preorder serialization of a binary tree | 331 | 0.443 | Medium | 5,718 |
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/1427610/python3-solution-oror-easy-oror-clean | class Solution:
def isValidSerialization(self, p: str) -> bool:
i=0
st=1
lst=p.split(",")
while(i<len(lst)):
st-=1
if st<0:
return False
if lst[i]!="#":
st+=2
i=i+1
if st==0:
return True
else:
return False | verify-preorder-serialization-of-a-binary-tree | python3 solution || easy || clean | minato_namikaze | 1 | 104 | verify preorder serialization of a binary tree | 331 | 0.443 | Medium | 5,719 |
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/1252806/Simple-and-Easy-Python-Solution | class Solution:
def isValidSerialization(self, preorder: str) -> bool:
preorder=preorder.split(",")
stack=[]
for node in preorder:
stack.append(node)
while len(stack)>2 and stack[-1]=="#" and stack[-2]=="#":
if stack[-3]=='#':
return False
stack=stack[:-3]
stack.append(node)
if len(stack)==1:
if stack[-1]=="#":
return True
else:
return False | verify-preorder-serialization-of-a-binary-tree | Simple and Easy Python Solution | jaipoo | 1 | 129 | verify preorder serialization of a binary tree | 331 | 0.443 | Medium | 5,720 |
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/2778102/Beat-88.47-Monotonic-stack-top-down-python-simple-solution | class Solution:
def isValidSerialization(self, preorder: str) -> bool:
if preorder == '#':
return True
preorder = preorder.split(',')
stack = []
for i in range(len(preorder)):
c = preorder[i]
if i > 0 and not stack:
return False
if c.isdigit():
stack.append(2)
elif c == '#':
if not stack:
return False
stack[-1] -= 1
while stack and stack[-1] == 0:
stack.pop()
if stack:
stack[-1] -= 1
return not stack | verify-preorder-serialization-of-a-binary-tree | Beat 88.47% / Monotonic stack / top-down python simple solution | Lara_Craft | 0 | 2 | verify preorder serialization of a binary tree | 331 | 0.443 | Medium | 5,721 |
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/1427849/Python3-Reverse-traversal-clean-solution | class Solution:
def isValidSerialization(self, preorder: str) -> bool:
stack = []
preorder = preorder.split(',')
for i in range(len(preorder) - 1, -1, -1):
if preorder[i] != '#':
if len(stack) < 2:
return False
stack.pop()
stack.pop()
stack.append(preorder[i])
return len(stack) == 1 | verify-preorder-serialization-of-a-binary-tree | [Python3] Reverse traversal - clean solution | maosipov11 | 0 | 20 | verify preorder serialization of a binary tree | 331 | 0.443 | Medium | 5,722 |
https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/1424270/Python-3-or-DFS-preorder-build-tree-simulation-or-Explanation | class Solution:
def isValidSerialization(self, preorder: str) -> bool:
preorder = preorder.split(',')
n = len(preorder)
idx, enough = 0, True # static `idx`, `enough` node to build a binary tree
def dfs():
nonlocal n, idx, enough
if idx >= n: enough = False; return # if not enough node to build a binary tree
if preorder[idx] == '#': return
if preorder[idx] != '#':
idx += 1 # say this is `idx_1`
dfs() # build left tree
idx += 1 # now, `idx` is not `idx_1 + 1` because `idx` is static and it's increasing during recursion. Hope this solve your confusion
dfs() # build right tree
dfs()
return enough and idx >= n-1 # all characters are visited and they are enough to build a tree | verify-preorder-serialization-of-a-binary-tree | Python 3 | DFS, preorder, build-tree simulation | Explanation | idontknoooo | 0 | 109 | verify preorder serialization of a binary tree | 331 | 0.443 | Medium | 5,723 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/1475876/Python-LC-but-better-explained | class Solution:
def __init__(self):
self.path = []
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
flights = {}
# as graph is directed
# => no bi-directional paths
for t1, t2 in tickets:
if t1 not in flights:
flights[t1] = []
flights[t1].append(t2)
visited = {}
for k, v in flights.items():
v.sort()
visited[k] = [False for _ in range(len(v))]
base_check = len(tickets) + 1
routes = ['JFK']
self.dfs('JFK', routes, base_check, flights, visited)
return self.path
def dfs(self, curr, routes, base_check, flights, visited):
if len(routes) == base_check:
self.path = routes
return True
# deadlock
if curr not in flights:
return False
for idx in range(len(flights[curr])):
if not visited[curr][idx]:
visited[curr][idx] = True
next_airport = flights[curr][idx]
routes += [next_airport]
result = self.dfs(next_airport, routes, base_check,
flights, visited)
if result:
return True
routes.pop()
visited[curr][idx] = False
return False | reconstruct-itinerary | Python LC, but better explained | SleeplessChallenger | 1 | 213 | reconstruct itinerary | 332 | 0.41 | Hard | 5,724 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/710983/Python3-8-line-Hierholzer's-algo-for-Eulerian-graph | class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
digraph = defaultdict(list) #directed graph
for fm, to in tickets: heappush(digraph[fm], to)
def dfs(n):
"""Hierholzer's algo to traverse every edge exactly once"""
while digraph[n]: dfs(heappop(digraph[n]))
ans.appendleft(n)
ans = deque()
dfs("JFK")
return ans | reconstruct-itinerary | [Python3] 8-line Hierholzer's algo for Eulerian graph | ye15 | 1 | 118 | reconstruct itinerary | 332 | 0.41 | Hard | 5,725 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/2784361/python-easy-solution | class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
adj={u: collections.deque() for u,v in tickets}
res=["JFK"]
tickets.sort()
for u,v in tickets:
adj[u].append(v)
def dfs(cur):
if len(res)==len(tickets)+1:
return True
if cur not in adj:
return False
temp= list(adj[cur])
for v in temp:
adj[cur].popleft()
res.append(v)
if dfs(v):
return res
res.pop()
adj[cur].append(v)
return False
dfs("JFK")
return res | reconstruct-itinerary | python easy solution | prabhatbit2016 | 0 | 10 | reconstruct itinerary | 332 | 0.41 | Hard | 5,726 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/2123985/python3-or-backtracking | class Solution:
def findItinerary(self, tickets: list[list[str]]) -> list[str]:
graph = {}
for s, d in tickets:
if d not in graph:
graph[d] = []
if s in graph:
graph[s].append(d)
graph[s].sort()
continue
graph[s] = [d]
def findPath(source, graph, visited, totalLen):
if len(visited) == totalLen:
return True, [source]
choices = graph[source]
for i in choices:
if visited.count((source, i)) == choices.count(i):
continue
visited.append((source, i))
flag, li = findPath(i, graph, visited, totalLen)
if flag:
return True, [source] + li
visited.pop()
return False, []
flag, itinerary = findPath("JFK", graph, [], len(tickets))
return itinerary | reconstruct-itinerary | python3 | backtracking | ComicCoder023 | 0 | 75 | reconstruct itinerary | 332 | 0.41 | Hard | 5,727 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/1950043/Python3-Deque-simple-solution-beats-99.39 | class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
graph = defaultdict(list)
for ticket in tickets:
graph[ticket[0]].append(ticket[1])
for key in graph:
graph[key].sort()
graph[key] = deque(graph[key])
stack = ['JFK']
result = []
while stack:
if not graph[stack[-1]]:
result.append(stack.pop())
else:
stack.append(graph[stack[-1]].popleft())
result.reverse()
return result | reconstruct-itinerary | Python3 Deque, simple solution, beats 99.39% | Sibi_Chakra | 0 | 66 | reconstruct itinerary | 332 | 0.41 | Hard | 5,728 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/1912634/Python3-DFS-and-Priority-queue | class Solution:
def dfs(self, graph, airport):
terminalTrip = []
result = []
while graph[airport]:
dest = heapq.heappop(graph[airport])
trip = self.dfs(graph, dest)
if airport in trip:
result += trip
else:
terminalTrip = trip
return [airport] + result + terminalTrip
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
graph = collections.defaultdict(list)
for start, dest in tickets:
heapq.heappush(graph[start], dest)
start = "JFK"
return self.dfs(graph, start) | reconstruct-itinerary | [Python3] DFS and Priority queue | vladimir_polyakov | 0 | 107 | reconstruct itinerary | 332 | 0.41 | Hard | 5,729 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/1835122/Python-BFS-solution-with-explanation | class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
flights = collections.defaultdict(list)
#Create dict of {departure airport: [possible destinations]} including repeats
for [dep, arr] in tickets:
flights[dep] += [arr]
# Sort possible destinations alphabetically, to avoid finding multiple itineraries
# since the first found must be the first lexicographically
for key in flights:
flights[key] = sorted(flights[key])
trip = ["JFK"]
def findTrip(trip):
# If there are no more possible flights, we have used all the tickets and
# have found a complete itinerary
if all(dests == [] for dests in flights.values()):
return trip
else:
# possible destinations starting at the most recent airport visited
dests = flights[trip[-1]]
ind = 0
dest = ""
# Breadth first search
while ind < len(dests):
# increment until we find a new destination, in the case that there
# are duplicate tickets
while ind < len(dests) and dests[ind] == dest:
ind += 1
if ind == len(dests):
break
# Main BFS code
dest = dests[ind]
dests.remove(dest)
trip.append(dest)
found = findTrip(trip)
if found:
return found
trip.pop()
dests.insert(ind, dest)
ind += 1
# No valid itineraries complete itinerary with itinerary so far
return False
trip = findTrip(trip)
return trip | reconstruct-itinerary | Python BFS solution with explanation | FayazAhmedUW | 0 | 97 | reconstruct itinerary | 332 | 0.41 | Hard | 5,730 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/1616199/Easy-to-understand-simple-backtracking. | class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
outbounds = defaultdict(list)
counts = collections.Counter([(from_, to_) for from_, to_ in tickets])
for from_, to_ in tickets:
outbounds[from_].append(to_)
for k in outbounds.keys():
outbounds[k].sort()
'''
node is the current node and used checks the counter of the tickets to verify full itinerary is built
'''
def dfs(node, used, path):
for v in outbounds[node]:
if used[(node, v)] < counts[(node, v)]:
used[(node, v)] += 1
sub_path = dfs(v, used, path + [node])
if len(path) + len(sub_path) == len(tickets): # path + node + sub_path == full path
return [node] + sub_path
used[(node, v)] -= 1
return [node]
path = dfs('JFK', defaultdict(int), [])
return path | reconstruct-itinerary | Easy to understand simple backtracking. | yshawn | 0 | 94 | reconstruct itinerary | 332 | 0.41 | Hard | 5,731 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/1613714/Python-Iterative-DFS-on-Dependency-Graph | class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
tick_dict = {}
for i in range(len(tickets)):
if tickets[i][0] in tick_dict:
tick_dict[tickets[i][0]].append(tickets[i][1])
else:
tick_dict[tickets[i][0]] = [tickets[i][1]]
if tickets[i][1] not in tick_dict:
tick_dict[tickets[i][1]] = []
for key in tick_dict.keys():
tick_dict[key].sort(reverse = True)
CALL = 1
HANDLE = 0
stack = [(CALL,'JFK')]
cur_path = []
while stack != []:
action, dest = stack.pop()
if action == CALL:
if len(cur_path) > 0:
tick_dict[cur_path[-1]].remove(dest)
cur_path.append(dest)
if len(cur_path) == len(tickets) + 1:
return cur_path
stack.append((HANDLE,dest))
for child in tick_dict[dest]:
stack.append((CALL,child))
else:
dest = cur_path.pop()
tick_dict[cur_path[-1]].append(dest)
tick_dict[cur_path[-1]].sort(reverse = True)
return [] | reconstruct-itinerary | Python Iterative DFS on Dependency Graph | 17pchaloori | 0 | 125 | reconstruct itinerary | 332 | 0.41 | Hard | 5,732 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/581536/Python3-Simple | class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
graph = defaultdict(list)
for ticket in tickets:
graph[ticket[0]].append(ticket[1])
for begin in graph:
graph[begin].sort()
def traverse(begin, n):
if not graph[begin]:
if n > 0:
return False
return [begin]
else:
for end in graph[begin]:
graph[begin].remove(end)
l = traverse(end, n - 1)
if l:
return [begin] + l
else:
idx = bisect.bisect_left(graph[begin], end)
graph[begin].insert(idx, end)
return traverse("JFK", len(tickets)) | reconstruct-itinerary | Python3 Simple | udayd | 0 | 108 | reconstruct itinerary | 332 | 0.41 | Hard | 5,733 |
https://leetcode.com/problems/reconstruct-itinerary/discuss/440916/Python-DFS-Solution-with-Explanation | class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
edges = collections.defaultdict(list)
n = len(tickets)
for i in range(len(tickets)):
edges[tickets[i][0]].append(tickets[i][1])
for k in edges:
edges[k].sort()
itinerary_list = ['JFK']
self.traverse(edges, itinerary_list, n)
return itinerary_list
def traverse(self, edges, itinerary_list, n):
if len(itinerary_list) == n+1:
return True
cur_node = itinerary_list[-1]
for i in range(len(edges[cur_node])):
if edges[cur_node][i] != '#':
temp = edges[cur_node][i]
itinerary_list.append(temp)
edges[cur_node][i] = '#'
if self.traverse(edges, itinerary_list, n):
return True
edges[cur_node][i] = temp
itinerary_list.pop()
return False | reconstruct-itinerary | Python DFS Solution with Explanation | a29161629 | -1 | 429 | reconstruct itinerary | 332 | 0.41 | Hard | 5,734 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/270884/Python-2-solutions%3A-Right-So-Far-One-pass-O(1)-Space-Clean-and-Concise | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
n = len(nums)
maxRight = [0] * n # maxRight[i] is the maximum element among nums[i+1...n-1]
maxRight[-1] = nums[-1]
for i in range(n-2, -1, -1):
maxRight[i] = max(maxRight[i+1], nums[i+1])
minLeft = nums[0]
for i in range(1, n-1):
if minLeft < nums[i] < maxRight[i]:
return True
minLeft = min(minLeft, nums[i])
return False | increasing-triplet-subsequence | [Python] 2 solutions: Right So Far, One pass - O(1) Space - Clean & Concise | hiepit | 94 | 2,000 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,735 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/270884/Python-2-solutions%3A-Right-So-Far-One-pass-O(1)-Space-Clean-and-Concise | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = second = math.inf
for num in nums:
if num <= first:
first = num
elif num <= second: # Now first < num, if num <= second then try to make `second` as small as possible
second = num
else: # Now first < second < num
return True
return False | increasing-triplet-subsequence | [Python] 2 solutions: Right So Far, One pass - O(1) Space - Clean & Concise | hiepit | 94 | 2,000 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,736 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/1421787/Simple-Python-greedy-solution-3-cases | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
min1 = min2 = float("inf")
for i, n in enumerate(nums):
if min1 < min2 < n:
return True
elif n < min1:
min1 = n
elif min1 < n < min2:
min2 = n
return False | increasing-triplet-subsequence | Simple Python greedy solution - 3 cases | Charlesl0129 | 13 | 868 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,737 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2680538/Python-easy-Sol.-O(n)time-complexity | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first=second=float('inf')
for i in nums:
if i<=first:
first=i
elif i<=second:
second=i
else:
return True
return False | increasing-triplet-subsequence | Python easy Sol. O(n)time complexity | pranjalmishra334 | 11 | 1,000 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,738 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/1923127/Easy-and-straight-forward-solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
least1=float('inf')
least2=float('inf')
for n in nums:
if n<=least1:
least1=n
elif n<=least2:
least2=n
else:
return True
return False | increasing-triplet-subsequence | Easy and straight forward solution | pbhuvaneshwar | 3 | 278 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,739 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688811/Simple-Python-Solution-100-Accepted-or-TC-O(n)-SC-O(1) | class Solution:
def increasingTriplet(self, arr: List[int]) -> bool:
i = j = float('inf')
for num in arr:
if num <= i:
i = num
elif num <= j:
j = num
else:
return True
return False | increasing-triplet-subsequence | Simple Python Solution 100% Accepted | TC O(n) SC O(1) | ShivangVora1206 | 2 | 95 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,740 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688675/Python-solution-with-explanation. | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
nums_i = float('inf')
nums_j = float('inf')
for num in nums:
if(num<=nums_i):
nums_i = num
elif(num<=nums_j):
nums_j = num
else:
return True
return False | increasing-triplet-subsequence | Python solution with explanation. | yashkumarjha | 2 | 67 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,741 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2520391/Clean-Python3-or-O(n)-Time-O(1)-Space-or-Faster-Than-95 | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
if len(nums) < 3:
return False
num1, num2 = nums[0], float('inf')
global_min = nums[0]
for cur in nums[1:]:
if num2 < cur:
return True
if cur < global_min:
global_min = cur
elif global_min < cur < num2:
num1, num2 = global_min, cur
elif num1 < cur < num2:
num2 = cur
return False | increasing-triplet-subsequence | Clean Python3 | O(n) Time, O(1) Space | Faster Than 95% | ryangrayson | 2 | 113 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,742 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691159/C%2B%2B-or-Java-or-Python-or-C-or-Accepted-O(n)-solution-with-explanation | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
if len(nums)<3:
return False
smallest = float('inf')
second_smallest = float('inf')
for num in nums:
if num <= smallest: // Find the smallest number
smallest = num
elif num <= second_smallest: // If get here, this number is larger than smallest number
second_smallest = num
else: // If get here, this number is larger than second smallest number => there is are increasing triplet
return True
return False | increasing-triplet-subsequence | C++ | Java | Python | C# | Accepted O(n) solution with explanation | tunguyenm | 1 | 30 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,743 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/1738429/Self-Understandable-Python-(2-methods-%2B-Linear-time-%2Bconstant-space)%3A | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
a=float('inf')
b=float('inf')
for i in nums:
if i<=a:
a=i
elif i<=b:
b=i
else:
return True
return False | increasing-triplet-subsequence | Self Understandable Python (2 methods + Linear time +constant space): | goxy_coder | 1 | 206 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,744 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/1738429/Self-Understandable-Python-(2-methods-%2B-Linear-time-%2Bconstant-space)%3A | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
if len(nums)<3 or len(set(nums))<3:
return False
i=0
j=1
k=2
while k<len(nums) or j<len(nums)-1:
if nums[j]<=nums[i]:
i=i+1
j=i+1
k=j+1
else:
if nums[k]>nums[j]:
return True
else:
k=k+1
if k==len(nums):
j=j+1
k=j+1
return False | increasing-triplet-subsequence | Self Understandable Python (2 methods + Linear time +constant space): | goxy_coder | 1 | 206 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,745 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/791994/Python3-concise-O(N)-solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
ans = []
for x in nums:
if not ans or ans[-1] < x: ans.append(x)
else:
i = bisect_left(ans, x)
ans[i] = x
return len(ans) >= 3 | increasing-triplet-subsequence | [Python3] concise O(N) solution | ye15 | 1 | 140 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,746 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/791994/Python3-concise-O(N)-solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
x0 = x1 = inf
for x in nums:
if x <= x0: x0 = x
elif x <= x1: x1 = x
else: return True
return False | increasing-triplet-subsequence | [Python3] concise O(N) solution | ye15 | 1 | 140 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,747 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2837675/Python-Solution-O(n) | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
poss = set()
curr_min = float('Inf')
for i in range(len(nums)):
if nums[i] > curr_min:
poss.add(i)
else:
curr_min = nums[i]
curr_max = float('-Inf')
for i in range(len(nums)-1, -1, -1):
if nums[i] < curr_max:
if i in poss:
return True
else:
curr_max = nums[i]
return False | increasing-triplet-subsequence | Python Solution O(n) | sarveshgadre0131 | 0 | 2 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,748 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2743603/LIS-of-length-3 | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
res = []
for num in nums:
if not res or res[-1] < num:
res.append(num)
if len(res) == 3: return True
else:
ind = bisect_left(res, num)
res[ind] = num
return False | increasing-triplet-subsequence | LIS of length 3 | shriyansnaik | 0 | 8 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,749 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2693118/python3 | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = second = math.inf
for i in nums:
if i <= first:
first = i
elif i <= second:
second = i
else:
return True
return False | increasing-triplet-subsequence | python3 | parryrpy | 0 | 3 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,750 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2692184/python3-simple-5-line-function-(694ms81) | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
minleft, maxright = nums[0], nums[-1]
minlefts = [minleft:=min(minleft, num) for num in nums]
maxrights = [maxright:=max(maxright, num) for num in reversed(nums)]
return any(i<j<k for i,j,k in zip(minlefts, nums, reversed(maxrights))) | increasing-triplet-subsequence | python3 simple 5-line function (694ms/81%) | leetavenger | 0 | 7 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,751 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2692046/o(n)-python-3 | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
a ,b =inf,inf
for i in nums:
if i<=a:
a= i
elif i<=b:
b =i
else:
return True | increasing-triplet-subsequence | o(n) python 3 | abhayCodes | 0 | 9 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,752 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2692011/Python-a-simple-O(N)O(1)-solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = second = math.inf
for n in nums:
if n > second:
return True
elif n <= first:
first = n
else:
second = n
return False | increasing-triplet-subsequence | Python, a simple O(N)/O(1) solution | blue_sky5 | 0 | 8 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,753 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691939/Python-or-O(n)-TC-or-O(1)-SC | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
n = len(nums)
if n < 3 :
return False
min = None
nextMin = None
"""
Initialize min and second min
from first two elements
"""
if nums[0] < nums[1] :
min = 0
nextMin = 1
else:
min = 1
for i in range(2 , n) :
x = nums[i]
"""
This will handle the case if secont element is greater than the first element
in array and extMin remains None
"""
if nextMin is None :
if x <= nums[min] :
min = i
else :
nextMin = i
continue
"""
If we have some nextMin , it means we must HAD some min for this nextMin , if we get some
element bigger than nextMin then we have the triplet
"""
if nums[i] > nums[nextMin] :
return True
"""
This part is Tricky
For eg:- array is like [2 , 4 , 1 , 2 , 3]
and x = 1
then only triplet is {1 ,2 ,3}
While traversing array we need to update the min .
After reaching 1 , min will become 2 {index of 1} and nextMin will remain at 1 {index of 4} only
So even if array would have been [2 , 4 , 1 , 5] , in next step x would be 5 and our nextMin
would be on 4 only {nextMin = 1} and above condition will return True .
But for the original array [2 , 4 , 1 ,2, 3 ] when x = 2 {index = 3} , nextMin will become 3 { index
of second 2} .
"""
if x < nums[min] :
min = i
elif x < nums[nextMin] and x > nums[min] :
nextMin = i
return False | increasing-triplet-subsequence | Python | O(n) TC | O(1) SC | 1day_ | 0 | 7 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,754 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691631/Python-or-O(1)-Space-complexity-and-O(n)-Time-Complexity | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
prev=nums[0]
minel=float('inf')
for i in nums[1:]:
# print(minel,'hehe',prev,i)
if i>prev:
if i>minel:
return True
# cnt+=1
minel=min(i,minel)
prev=min(prev,i)
return False | increasing-triplet-subsequence | Python | O(1) Space complexity and O(n) Time Complexity | Prithiviraj1927 | 0 | 11 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,755 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691542/Increasing-Triplets-Subsequence | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
a=False
b=float('inf')
c=float('inf')
i=0
while i<len(nums):
if nums[i]<b:
b=nums[i]
elif nums[i]>b and nums[i]<c:
c=nums[i]
elif nums[i]>c:
a=True
break
i+=1
return a | increasing-triplet-subsequence | Increasing Triplets Subsequence | ravishankarguptacktd | 0 | 4 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,756 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691499/Easy-Python3-and-CPP-solution-or-O(n) | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
left = float('inf')
mid = float('inf')
for i in range(len(nums)):
if nums[i] < left:
left = nums[i]
elif left < nums[i] < mid:
mid = nums[i]
elif nums[i] > mid:
return True
return False | increasing-triplet-subsequence | Easy Python3 and CPP solution | O(n) | prankurgupta18 | 0 | 3 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,757 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691493/Python-3-oror-98-faster-oror-medium-oror-3-pointer-approach | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first, second = inf, inf
for third in nums:
if second < third: return True
if third <= first: first= third
else: second = third
return False | increasing-triplet-subsequence | Python 3 || 98% faster || medium || 3 pointer approach | anurag052002 | 0 | 3 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,758 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691436/Increasing-Triplet-Subsequence | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
n = len(nums)
minOne = math.inf
minTwo = math.inf
for i in range(n):
if nums[i] < minOne:
minOne = nums[i]
if nums[i] > minOne:
minTwo = min(minTwo, nums[i])
if nums[i] > minTwo:
return True
return False | increasing-triplet-subsequence | Increasing Triplet Subsequence | Vedant-G | 0 | 8 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,759 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691294/Python3-One-Line-Version-Pivot-Point-O(n) | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
lmin, rmax = nums.copy(), nums.copy()
for i in range(1,len(nums)):
lmin[i] = min(lmin[i], lmin[i-1])
for i in reversed(range(len(nums)-1)):
rmax[i] = max(rmax[i], rmax[i+1])
for i in range(1,len(nums)-1):
if lmin[i] < nums[i] < rmax[i]:
return True
return False | increasing-triplet-subsequence | Python3 One Line Version, Pivot Point O(n) | godshiva | 0 | 9 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,760 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691294/Python3-One-Line-Version-Pivot-Point-O(n) | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
return any([a<b<c for a,b,c in zip(list(accumulate(nums.copy(), min)), nums, list(reversed(list(accumulate(reversed(nums.copy()), max)))))]) | increasing-triplet-subsequence | Python3 One Line Version, Pivot Point O(n) | godshiva | 0 | 9 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,761 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2691000/Python-Simple-Solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
min1 = float("inf")
min2 = float("inf")
for num in nums:
if num <= min1:
min1 = num
elif num <= min2:
min2 = num
else:
return True
return False | increasing-triplet-subsequence | Python Simple Solution | AxelDovskog | 0 | 8 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,762 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2690486/python-solution-O(N) | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
n=len(nums)
if n<3:
return False
left,mid=float('inf'),float('inf')
for i in nums:
if i>mid:
return True
elif i>left and i<mid:
mid=i
elif i<left:
left=i
return False | increasing-triplet-subsequence | python solution O(N) | shashank_2000 | 0 | 11 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,763 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2690308/Python-Simple-Python-Solution-Using-Greedy-Approach | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
max_num1 = 10000000000
max_num2 = 10000000000
for num in nums:
if num <= max_num1:
max_num1 = num
elif num <= max_num2:
max_num2 = num
else:
return True
return False | increasing-triplet-subsequence | [ Python ] ✅✅ Simple Python Solution Using Greedy Approach 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 28 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,764 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2690104/O(n)-time-(84.86)-and-O(1)-memory-(95.56)-with-explanation | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
d = {
'j': [-inf, -inf],
'h': -inf
}
for e in reversed(nums):
if e >= d.get('h'):
d.update({'h': e})
elif e >= d.get('j')[1]:
d.update({'j': [d.get('h'), e]})
else:
return True
return False | increasing-triplet-subsequence | O(n) time (84.86%) and O(1) memory (95.56%), with explanation | rscoates | 0 | 9 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,765 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2690070/python3-using-longest-increasing-number-solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
seq = []
for i in nums:
index = bisect.bisect_left(seq,i)
if index == len(seq): seq.append(i)
else: seq[index] = i
if len(seq) == 3:
return True
return False | increasing-triplet-subsequence | python3, using longest increasing number solution | pjy953 | 0 | 7 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,766 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2689754/Simplest-Implementation-in-Python | class Solution(object):
def increasingTriplet(self, nums):
a = max(nums)+1
b = a
for i in nums:
if i<=a:
a = i
elif i<=b:
b = i
else:
return True
return False | increasing-triplet-subsequence | Simplest Implementation in Python | A14K | 0 | 2 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,767 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2689641/Python-Greedy-O(N)-Solution-or-Faster-than-95 | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = float('inf')
second = float('inf')
for n in nums:
if n > second:
return True
if n > first:
second = min(n, second)
else:
first = min(n, first)
return False | increasing-triplet-subsequence | Python Greedy O(N) Solution | Faster than 95% | KevinJM17 | 0 | 16 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,768 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2689434/python3-easy-solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
f=s=float("inf")
for i in nums:
if i<=f:
f=i
elif i<=s:
s=i
else:
return True
return False | increasing-triplet-subsequence | python3 easy solution | Narendrasinghdangi | 0 | 10 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,769 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2689165/easy-solution-oror-TC-O(N)-SC-O(1)-oror-99-Faster | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
x,y=None,None
for n in nums:
if x==None or n<=x:
x=n
elif y==None or n<=y:
y=n
else:
return True
return False | increasing-triplet-subsequence | easy solution || TC O(N) SC O(1) || 99 % Faster | aryan3012 | 0 | 5 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,770 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2689093/Python-Greedy-Approach | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
firstNum = secondNum = float('inf')
for num in nums:
# if current num smaller than firstNum than update it
if num < firstNum:
firstNum = num
elif num == firstNum:
continue
elif num < secondNum:
# if current num smaller than secondNum then update secondNum
secondNum = num
elif num == secondNum:
continue
else:
return True
return False | increasing-triplet-subsequence | Python Greedy Approach | zxia545 | 0 | 2 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,771 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688909/Python-Solution-or-Greedy-or-Brute-Force-greater-Optimized | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
# Brute Force
# n=len(nums)
# for i in range(n):
# for j in range(i+1, n):
# if nums[i]<nums[j]:
# for k in range(j+1, n):
# if nums[j]<nums[k]:
# return True
# return False
# Optimised
a,b=1e11,1e11
for num in nums:
if b<num:
return True
if a>=num:
a=num
else:
b=num
return False | increasing-triplet-subsequence | Python Solution | Greedy | Brute Force --> Optimized | Siddharth_singh | 0 | 17 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,772 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688907/Solution-code-including-nums-array-length-check-condition | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
if len(nums)<3:
return False
else:
n1,n2,n3=inf,inf,inf
for i in nums:
if i<n1:
n1=i
if n1<i<n2:
n2=i
if n1<n2<i<n3:
n3=i
return True
return False | increasing-triplet-subsequence | Solution code including nums array length check condition | NandhuS | 0 | 2 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,773 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688887/C%2B%2BPython-Short-and-Crisp-O(N)-Time-and-O(1)-Space-Solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
left, mid = 999999999999, 999999999999
for i in nums:
if i < left:
left = i
elif i > mid and i > left:
return True
elif i > left:
mid = i
return False | increasing-triplet-subsequence | C++/Python Short and Crisp O(N) Time and O(1) Space Solution | MrFit | 0 | 13 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,774 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688767/Python-or-Single-pass-O(n)-or-91-faster-submission-or-Easy-to-understand | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
min1 = min2 = float('inf')
for i,n in enumerate(nums):
if n <= min1:
min1 = n
elif n <= min2:
min2 = n
else:
return True
return False | increasing-triplet-subsequence | Python | Single pass O(n) | 91% faster submission | Easy to understand | __Asrar | 0 | 10 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,775 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688729/Python3-Easiest-Solution-Time-Complexity-O(n) | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = second = math.inf
for num in nums:
if num < first:
first = num
if num > first and num < second:
second = num
if second < num: # Now first < second < num
return True
return False | increasing-triplet-subsequence | Python3 Easiest Solution Time Complexity-O(n)✅✅ | Abhishek586servi | 0 | 10 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,776 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688657/Python3-oror-O(N)-Time-oror-O(1)-Space | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
pair_a = None
pair_b = None
a = nums[0]
b = nums[0]
for i in nums:
if i <= a:
a = i
b = i
continue
if (pair_a != None) and (pair_b < i):
return True
if (a == b and a < i ) or (i <= b):
b = i
if (pair_a == None) or (pair_b >= b):
pair_a = a
pair_b = b
return False | increasing-triplet-subsequence | Python3 || O(N) Time || O(1) Space | Kumada_Takuya | 0 | 15 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,777 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688635/Inspired-on-%22Longest-Valid-Parentheses%22 | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
n = len(nums)
minList = [0 for _ in range(n)]
minList[0] = 0
for i, num in enumerate(nums[1:], start=1):
if num > nums[minList[i - 1]]:
minList[i] = minList[i - 1]
else:
minList[i] = i
maxList = [0 for _ in range (n)]
maxList[-1] = n - 1
for i, num in enumerate(reversed(nums[:-1]), start=1):
if num < nums[maxList[~(i - 1)]]:
maxList[~i] = maxList[~(i - 1)]
else:
maxList[~i] = n - i - 1
return any(minList[i] < i and maxList[i] > i for i in range(n)) | increasing-triplet-subsequence | Inspired on "Longest Valid Parentheses" | sr_vrd | 0 | 4 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,778 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688635/Inspired-on-%22Longest-Valid-Parentheses%22 | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
n = len(nums)
minList = [0 for _ in range(n)]
minList[0] = 0
for i, num in enumerate(nums[1:], start=1):
if num > nums[minList[i - 1]]:
minList[i] = minList[i - 1]
else:
minList[i] = i
currentMax = nums[-1]
for i, num in enumerate(reversed(nums[:-1]), start=2):
if num < currentMax:
if minList[n - i] < n - i:
return True
else:
currentMax = num
return False | increasing-triplet-subsequence | Inspired on "Longest Valid Parentheses" | sr_vrd | 0 | 4 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,779 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688508/python3-Iteration-solution-for-reference | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = float('inf')
second = float('inf')
for n in nums:
if n < first:
first = n
elif n < second and n > first:
second = n
elif n > second:
return True
return False | increasing-triplet-subsequence | [python3] Iteration solution for reference | vadhri_venkat | 0 | 11 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,780 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688471/Easy-and-Faster-linear | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first,second=float(inf),float(inf)
for i in nums:
if(i<=first):
first=i
elif(i<=second):
second=i
else:
return True
return False | increasing-triplet-subsequence | Easy and Faster linear | Raghunath_Reddy | 0 | 10 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,781 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688273/Python-or-Longest-Increasing-Subsquence | class Solution:
def increasingTriplet(self, xs: List[int]) -> bool:
n = len(xs)
triplet = [float('-inf')]
for x in xs:
if x > triplet[-1]:
triplet.append(x)
if len(triplet) == 4:
# The first element is the sentinel float('-inf'), so
# we need a length of 4.
return True
else:
i = bisect.bisect_left(triplet, x)
triplet[i] = x
return False | increasing-triplet-subsequence | Python | Longest Increasing Subsquence | on_danse_encore_on_rit_encore | 0 | 15 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,782 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2688269/Python-solution-with-mins-and-max-lists | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
mins = [nums[0] for _ in nums]
maxs = [nums[-1] for _ in nums]
for idx in range(len(nums)):
if idx == 0:
continue
else:
mins[idx] = min(mins[idx-1], nums[idx])
maxs[-idx-1] = max(maxs[-idx], nums[-idx-1])
for idx, val in enumerate(nums):
if mins[idx] < val < maxs[idx]:
return True
return False | increasing-triplet-subsequence | Python solution with mins and max lists | Terry_Lah | 0 | 5 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,783 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2564360/Python-DP-solution-a-variant-of-300.-Longest-Increasing-Subsequence | class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
n = len(nums)
# f[i] = length of longest increasing subsequences that ends with nums[i]
f = [1 for i in range(n)]
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
f[i] = max(f[i], f[j] + 1)
return max(f) | increasing-triplet-subsequence | [Python] DP solution, a variant of #300. Longest Increasing Subsequence | bbshark | 0 | 51 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,784 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2564360/Python-DP-solution-a-variant-of-300.-Longest-Increasing-Subsequence | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
n = len(nums)
# consider 2 kinds of corner cases to avoid TLE
# 1st corner case: len(nums) < 3
if n < 3:
return False
# 2nd corner case: there's no triplet such as nums[i] < nums[j] < nums[k]
# if max(nums) - min(nums) < 2
# Ex. [1,2,1,2,1,2,1,2,1,2,1,2,1] -> False
if max(nums) - min(nums) < 2:
return False
# f[i] = length of longest increasing subsequences that ends with nums[i]
f = [1 for i in range(n)]
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
f[i] = max(f[i], f[j] + 1)
if f[i] == 3:
return True # once we find a valid triplet, we stop finding and return to avoid TLE
return False | increasing-triplet-subsequence | [Python] DP solution, a variant of #300. Longest Increasing Subsequence | bbshark | 0 | 51 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,785 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2511558/Python-and-Go | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
smallest = sys.maxsize
second_smallest = sys.maxsize
for number in nums:
if number <= smallest:
# if smallest <= second_smallest:
# second_smallest = smallest
smallest = number
elif number <= second_smallest:
second_smallest = number
else:
return True
return False | increasing-triplet-subsequence | Python and Go答え | namashin | 0 | 46 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,786 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2389362/Simplest-and-Fastest-Python-Solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = second = float('inf')
for n in nums:
if n <= first:
first = n
elif n <= second:
second = n
else:
return True
return False | increasing-triplet-subsequence | Simplest and Fastest Python Solution | aman-senpai | 0 | 128 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,787 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/2271500/Python-Easy-Solution | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
# similar to the longest increasing subsequence
if len(set(nums)) <3:
return False
dp = [1]*len(nums)
flag = False
for i in range(1,len(dp)):
pre_max = 0
for j in range(0, i):
if nums[j]<nums[i]:
pre_max = max(pre_max,dp[j])
dp[i]+=pre_max
if dp[i] == 3:
return True
return False
print(dp) | increasing-triplet-subsequence | Python Easy Solution | Abhi_009 | 0 | 128 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,788 |
https://leetcode.com/problems/increasing-triplet-subsequence/discuss/1269768/Python-find-2nd-minimum-and-break-at-3-O(n)-and-O(1)-space | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
m1 = float("inf")
m2 = float("inf")
for i in nums:
if i<m1:
m1 = i
elif i<m2 and i>m1:
m2 = i
elif i>m2: return True
return False | increasing-triplet-subsequence | Python find 2nd minimum and break at 3 - O(n) and O(1) space | kiran21595 | 0 | 172 | increasing triplet subsequence | 334 | 0.427 | Medium | 5,789 |
https://leetcode.com/problems/self-crossing/discuss/710582/Python3-complex-number-solution-Self-Crossing | class Solution:
def isSelfCrossing(self, x: List[int]) -> bool:
def intersect(p1, p2, p3, p4):
v1 = p2 - p1
if v1.real == 0:
return p1.imag <= p3.imag <= p2.imag and p3.real <= p1.real <= p4.real
return p3.imag <= p1.imag <= p4.imag and p1.real <= p3.real <= p2.real
def overlap(p1, p2, p3, p4):
v1 = p2 - p1
if v1.real == 0:
return min(p2.imag, p4.imag) >= max(p1.imag, p3.imag) and p1.real == p3.real
return min(p2.real, p4.real) >= max(p1.real, p3.real) and p1.imag == p3.imag
uv = complex(0, 1)
p = complex(0, 0)
segments = deque()
for s in x:
segments.append(sorted([p, (np := p + uv * s)], key=lambda x:(x.real, x.imag)))
if len(segments) > 5 and intersect(*segments[-1], *segments[-6]):
return True
if len(segments) > 4 and overlap(*segments[-1], *segments[-5]):
return True
if len(segments) > 3 and intersect(*segments[-1], *segments[-4]):
return True
if len(segments) == 6:
segments.popleft()
p = np
uv *= complex(0, 1)
return False | self-crossing | Python3 complex number solution - Self Crossing | r0bertz | 0 | 221 | self crossing | 335 | 0.293 | Hard | 5,790 |
https://leetcode.com/problems/palindrome-pairs/discuss/2585442/Intuitive-Python3-or-HashMap-or-95-Time-and-Space-or-O(N*W2) | class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
backward, res = {}, []
for i, word in enumerate(words):
backward[word[::-1]] = i
for i, word in enumerate(words):
if word in backward and backward[word] != i:
res.append([i, backward[word]])
if word != "" and "" in backward and word == word[::-1]:
res.append([i, backward[""]])
res.append([backward[""], i])
for j in range(len(word)):
if word[j:] in backward and word[:j] == word[j-1::-1]:
res.append([backward[word[j:]], i])
if word[:j] in backward and word[j:] == word[:j-1:-1]:
res.append([i, backward[word[:j]]])
return res | palindrome-pairs | Intuitive Python3 | HashMap | 95% Time & Space | O(N*W^2) | ryangrayson | 54 | 3,000 | palindrome pairs | 336 | 0.352 | Hard | 5,791 |
https://leetcode.com/problems/palindrome-pairs/discuss/1235153/Python3-trie | class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
mp = {x: i for i, x in enumerate(words)} # val-to-pos mapping
ans = []
for i, word in enumerate(words):
for ii in range(len(word)+1):
prefix = word[:ii]
if prefix == prefix[::-1]: # palindromic prefix
key = word[ii:][::-1]
if key in mp and mp[key] != i: ans.append([mp[key], i])
suffix = word[~ii:]
if ii < len(word) and suffix == suffix[::-1]: # palindromic suffix
key = word[:~ii][::-1]
if key in mp and mp[key] != i: ans.append([i, mp[key]])
return ans | palindrome-pairs | [Python3] trie | ye15 | 4 | 362 | palindrome pairs | 336 | 0.352 | Hard | 5,792 |
https://leetcode.com/problems/palindrome-pairs/discuss/2846852/Python3-On-Site-coding-round-implementation | class Solution:
def palindromePairs(self, words):
@cache
def pal(string):
l, r = 0, len(string)-1
while l < r:
if string[l] != string[r]:
return False
l+=1
r-=1
return True
output = set()
words_idx = {w:idx for idx,w in enumerate(words)}
# Index of empty string
idx_empty = -1
if "" in words_idx:
idx_empty = words_idx[""]
for idx, word in enumerate(words):
# To handle cases with empty string
if pal(word) and word != "" and idx_empty != -1:
output.add((idx_empty, idx))
output.add((idx, idx_empty))
substring = ""
for i in range(len(word)):
substring += word[i]
# Where suffix is pal
if substring[::-1] in words_idx and pal(word[i+1:]) and idx != words_idx[substring[::-1]]:
output.add((idx, words_idx[substring[::-1]]))
# Where prefix is pal
if word[i+1:][::-1] in words_idx and pal(substring) and idx != words_idx[word[i+1:][::-1]]:
output.add((words_idx[word[i+1:][::-1]], idx))
return output | palindrome-pairs | Python3 - On-Site coding round implementation | thakurritesh19 | 1 | 7 | palindrome pairs | 336 | 0.352 | Hard | 5,793 |
https://leetcode.com/problems/palindrome-pairs/discuss/475402/Python3-simple-solutions | class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
ht = {}
for i in range(len(words)):
ht[words[i]]=i
res = []
for i,word in enumerate(words):
for j in range(len(word)+1):
left,right=word[:j],word[j:]
if self.isPalindrome(left) and right[::-1] in ht and i!=ht[right[::-1]]:
res.append([ht[right[::-1]],i])
if right and self.isPalindrome(right) and left[::-1] in ht and i!=ht[left[::-1]]:
res.append([i,ht[left[::-1]]])
return res
def palindromePairsBF(self, words: List[str]) -> List[List[int]]:
combs = [x for x in itertools.permutations([i for i in range(len(words))],2)]
res = []
for cm in combs:
if self.isPalindrome(words[cm[0]]+words[cm[1]]):
res.append(list(cm))
# print(combs)
return res
def isPalindrome(self,s)->bool:
return s==s[::-1] | palindrome-pairs | Python3 simple solutions | jb07 | 1 | 281 | palindrome pairs | 336 | 0.352 | Hard | 5,794 |
https://leetcode.com/problems/palindrome-pairs/discuss/2820563/python-hashing | class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
re_dict = {w[::-1]: idx for idx, w in enumerate(words)}
ret = []
for w_idx, w in enumerate(words):
for idx in range(0, len(w)+1):
prefix = w[:idx]
if prefix in re_dict:
if re_dict[prefix] != w_idx:
remaining = w[idx:]
if remaining == remaining[::-1]:
ret.append([w_idx, re_dict[prefix]])
for w_idx, w in enumerate(words):
for idx in range(0, len(w)+1):
suffix = w[idx:]
if suffix in re_dict:
if re_dict[suffix] != w_idx and len(words[re_dict[suffix]]) != len(words[w_idx]):
remaining = w[:idx]
if remaining == remaining[::-1]:
ret.append([re_dict[suffix], w_idx])
return ret | palindrome-pairs | python hashing | xsdnmg | 0 | 3 | palindrome pairs | 336 | 0.352 | Hard | 5,795 |
https://leetcode.com/problems/palindrome-pairs/discuss/2586871/Python-oror-Simple-Hash-map-oror-without-trie-oror-having-86-faster-oror-easy-to-understand | class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
mp={}
ans=[]
for i in range(0,len(words)):
mp[words[i]]=i
for j in range(0,len(words)):
##case 1: if the reverse of given word is present in words set
if (words[j][::-1]) in mp and mp[words[j][::-1]]!=j:
ans.append([j,mp[words[j][::-1]]])
## case2: if the given word is palindrome and the word set also contains the "" (empty) word
if words[j]!="" and "" in mp and words[j]==words[j][::-1]:
ans.append([mp[""],j])
ans.append([j,mp[""]])
## case3: if word from wordset after being adding to start or at last forms a palindromic pairs
for i in range(1,len(words[j])):
if words[j][i:][::-1] in mp and (words[j][:i]==words[j][:i][::-1] and mp[words[j][i:][::-1]]!=j):
ans.append([mp[words[j][i:][::-1]],j])
if words[j][:i][::-1] in mp and (words[j][i:]==words[j][i:][::-1] and mp[words[j][:i][::-1]]!=j):
ans.append([j,mp[words[j][:i][::-1]]])
return ans | palindrome-pairs | Python || Simple Hash map || without trie || having 86% faster || easy to understand | Mom94 | 0 | 78 | palindrome pairs | 336 | 0.352 | Hard | 5,796 |
https://leetcode.com/problems/palindrome-pairs/discuss/2586818/GolangPython-O(N*K2)-time-or-O(N)-space | class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
word_dict = {}
for i,word in enumerate(words):
word_dict[word] = i
answer = set()
for i,word in enumerate(words):
reverse_word = word[::-1]
length = len(word)
for idx in range(length+1):
if reverse_word[:idx] in word_dict and word_dict[reverse_word[:idx]] != word_dict[word] and is_palindrome(reverse_word[idx:]):
answer.add((word_dict[reverse_word[:idx]],i))
if reverse_word[idx:] in word_dict and word_dict[reverse_word[idx:]] != word_dict[word] and is_palindrome(reverse_word[:idx]):
answer.add((i,word_dict[reverse_word[idx:]]))
return answer
def is_palindrome(word):
left = 0
right = len(word)-1
while left < right:
if word[left] != word[right]:
return False
left+=1
right-=1
return True | palindrome-pairs | Golang/Python O(N*K^2) time | O(N) space | vtalantsev | 0 | 46 | palindrome pairs | 336 | 0.352 | Hard | 5,797 |
https://leetcode.com/problems/palindrome-pairs/discuss/2586239/Easy-Python-Solution-with-Dictionary | class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
ans = []
d = {}
for i,c in enumerate(words):
d[c] = i
if "" in d: # If sapces and pallindrome are present like as in example 3.
j = d[""]
for i in range(len(words)):
if i != j and words[i] == words[i][::-1]:
ans.append([i,j])
ans.append([j,i])
for i in range(len(words)): # Case for abcd and dcba like strings
s = words[i][::-1]
if s in d and d[s] != i:
ans.append([i,d[s]])
for i in range(len(words)): # General Case for all other strings.
for j in range(1,len(words[i])):
l = words[i][0:j]
r = words[i][j:]
if l == l[::-1]:
if r[::-1] in d and d[r[::-1]] != i:
ans.append([d[r[::-1]],i])
if r == r[::-1]:
if l[::-1] in d and d[l[::-1]] != i:
ans.append([i,d[l[::-1]]])
return ans | palindrome-pairs | Easy Python Solution with Dictionary | a_dityamishra | 0 | 68 | palindrome pairs | 336 | 0.352 | Hard | 5,798 |
https://leetcode.com/problems/palindrome-pairs/discuss/2586194/Python-Hashmap-Solution-oror-85-faster-runtime-oror-67-faster-memory-usage | class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
ans = []
dictionary = {}
n = len(words)
for i in range(n):
dictionary[words[i]] = i
for i in range(n):
w1 = words[i]
#CASE 1: When reverse of word is present in the list
if dictionary.get(w1[::-1], -1) != -1:
ind = dictionary.get(w1[::-1])
if i!=ind:
ans.append([i, ind])
#CASE 2: When "" is present in the list
if w1!="" and dictionary.get("", -1)!=-1 and w1==w1[::-1]:
ind = dictionary.get("")
ans.append([i, ind])
ans.append([ind, i])
#CASE 3:
#i) When w1[:j-1] is palindrome and w1[j:] = reverse(w2)
#ii) When w1[j:] is palindrome and w1[:j-1] = reverse(w2)
for j in range(1, len(w1)):
if dictionary.get(w1[j:][::-1], -1)!=-1 and w1[:j]==w1[:j][::-1]:
ind = dictionary.get(w1[j:][::-1])
if ind!=i:
ans.append([ind, i])
if dictionary.get(w1[:j][::-1], -1)!=-1 and w1[j:]==w1[j:][::-1]:
ind = dictionary.get(w1[:j][::-1])
if ind!=i:
ans.append([i, ind])
return ans | palindrome-pairs | ✔️✔️ Python Hashmap Solution || 85% faster runtime || 67% faster memory usage | harshsaini6979 | 0 | 91 | palindrome pairs | 336 | 0.352 | Hard | 5,799 |
Subsets and Splits