mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 21:22:43 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
987eb7ab5b | ||
|
|
e4118fccd3 | ||
|
|
95db4ca46c | ||
|
|
0cc7ca607e | ||
|
|
71ec39fe34 | ||
|
|
51decd23bd | ||
|
|
90082518a6 | ||
|
|
e10a913546 | ||
|
|
fec94ed636 | ||
|
|
30273d0030 | ||
|
|
50299defef | ||
|
|
c843be855e | ||
|
|
1e0e03daaa | ||
|
|
7b182206dd | ||
|
|
faaaf52f85 | ||
|
|
090f3d6719 | ||
|
|
a3ae16ad96 | ||
|
|
9faa0b0337 |
No files matched your search
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: '48. Rotate Image'
|
||||
description: You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise)
|
||||
sidebar:
|
||||
label: 'Rotate Image'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Matrix Index Math</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `matrix = [[1,2,3],[4,5,6],[7,8,9]]`
|
||||
- Output: `[[7,4,1],[8,5,2],[9,6,3]]`
|
||||
|
||||
### Example 2:
|
||||
- Input: `matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]`
|
||||
- Output: `[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- `n == matrix.length == matrix[i].length`
|
||||
- `1 <= n <= 20`
|
||||
- `-1000 <= matrix[i][j] <= 1000`
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
class Solution:
|
||||
def rotate(self, matrix: List[List[int]]) -> None:
|
||||
n = len(matrix)
|
||||
for r in range(n):
|
||||
for c in range(r + 1, n):
|
||||
matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
|
||||
|
||||
for r in range(n):
|
||||
matrix[r].reverse()
|
||||
```
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
title: '54. Spiral Matrix'
|
||||
description: Given an m x n matrix, return all elements of the matrix in spiral order
|
||||
sidebar:
|
||||
label: 'Spiral Matrix'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Matrix Index Math</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `matrix = [[1,2,3],[4,5,6],[7,8,9]]`
|
||||
- Output: `[1,2,3,6,9,8,7,4,5]`
|
||||
|
||||
### Example 2:
|
||||
- Input: `matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]`
|
||||
- Output: `[1,2,3,4,8,12,11,10,9,5,6,7]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- `m == matrix.length`
|
||||
- `n == matrix[i].length`
|
||||
- `1 <= m, n <= 10`
|
||||
- `-100 <= matrix[i][j] <= 100`
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
class Solution:
|
||||
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
|
||||
res = []
|
||||
top, bottom = 0, len(matrix) - 1
|
||||
left, right = 0, len(matrix[0]) - 1
|
||||
|
||||
while top <= bottom and left <= right:
|
||||
# 1. Top Row
|
||||
for c in range(left, right + 1):
|
||||
res.append(matrix[top][c])
|
||||
top += 1
|
||||
|
||||
# 2. Right Column
|
||||
for r in range(top, bottom + 1):
|
||||
res.append(matrix[r][right])
|
||||
right -= 1
|
||||
|
||||
# 3. Bottom Row
|
||||
if top <= bottom:
|
||||
for c in range(right, left - 1, -1):
|
||||
res.append(matrix[bottom][c])
|
||||
bottom -= 1
|
||||
|
||||
# 4. Left Column
|
||||
if left <= right:
|
||||
for r in range(bottom, top - 1, -1):
|
||||
res.append(matrix[r][left])
|
||||
left += 1
|
||||
|
||||
return res
|
||||
```
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
title: '73. Set Matrix Zeroes'
|
||||
description: Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's
|
||||
sidebar:
|
||||
label: 'Set Matrix Zeroes'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Matrix Index Math</Badge>
|
||||
|
||||
::::warning
|
||||
You must do it in place.
|
||||
::::
|
||||
|
||||
### Example 1:
|
||||
- Input: `matrix = [[1,1,1],[1,0,1],[1,1,1]]`
|
||||
- Output: `[[1,0,1],[0,0,0],[1,0,1]]`
|
||||
|
||||
### Example 2:
|
||||
- Input: `matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]`
|
||||
- Output: `[[0,0,0,0],[0,4,5,0],[0,3,1,0]]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- `m == matrix.length`
|
||||
- `n == matrix[0].length`
|
||||
- `1 <= m, n <= 200`
|
||||
- `-2^31 <= matrix[i][j] <= 2^31 - 1`
|
||||
- A straightforward solution using O(mn) space is probably a bad idea.
|
||||
- A simple improvement uses O(m + n) space, but still not the best solution.
|
||||
- Could you devise a constant space solution?
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
class Solution:
|
||||
def setZeroes(self, matrix: List[List[int]]) -> None:
|
||||
"""
|
||||
Do not return anything, modify matrix in-place instead.
|
||||
"""
|
||||
m, n = len(matrix), len(matrix[0])
|
||||
|
||||
# 1. remember if row 0 or column 0 have their own zeros
|
||||
row0_zero = any(matrix[0][c] == 0 for c in range(n))
|
||||
col0_zero = any(matrix[r][0] == 0 for r in range(m))
|
||||
|
||||
# 2. use row 0 and column 0 as marker lists
|
||||
for r in range(1, m):
|
||||
for c in range(1, n):
|
||||
if matrix[r][c] == 0:
|
||||
matrix[r][0] = 0
|
||||
matrix[0][c] = 0
|
||||
|
||||
# 3. zero the inner cells from the markers
|
||||
for r in range(1, m):
|
||||
for c in range(1, n):
|
||||
if matrix[r][0] == 0 or matrix[0][c] == 0:
|
||||
matrix[r][c] = 0
|
||||
|
||||
# 4. handle row 0 and column 0 last
|
||||
if row0_zero:
|
||||
for c in range(n):
|
||||
matrix[0][c] = 0
|
||||
if col0_zero:
|
||||
for r in range(m):
|
||||
matrix[r][0] = 0
|
||||
```
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
title: '2. Add Two Numbers'
|
||||
description: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list
|
||||
sidebar:
|
||||
label: 'Add Two Numbers'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Hybrid Structures</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `l1 = [2,4,3], l2 = [5,6,4]`
|
||||
- Output: `[7,0,8]`
|
||||
- Explanation: `342 + 465 = 807`.
|
||||
|
||||
### Example 2:
|
||||
- Input: `l1 = [0], l2 = [0]`
|
||||
- Output: `[0]`
|
||||
|
||||
### Example 3:
|
||||
- Input: `l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]`
|
||||
- Output: `[8,9,9,9,0,0,0,1]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in each linked list is in the range [1, 100].
|
||||
- `0 <= Node.val <= 9`
|
||||
- It is guaranteed that the list represents a number that does not have leading zeros.
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, val=0, next=None):
|
||||
# self.val = val
|
||||
# self.next = next
|
||||
class Solution:
|
||||
def addTwoNumbers(
|
||||
self, l1: Optional[ListNode], l2: Optional[ListNode]
|
||||
) -> Optional[ListNode]:
|
||||
|
||||
dummy = ListNode()
|
||||
carry = 0
|
||||
curr = dummy
|
||||
while l1 or l2 or carry:
|
||||
s = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
|
||||
carry, val = divmod(s, 10)
|
||||
|
||||
curr.next = ListNode(val)
|
||||
curr = curr.next
|
||||
|
||||
l1 = l1.next if l1 else None
|
||||
l2 = l2.next if l2 else None
|
||||
|
||||
return dummy.next
|
||||
```
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: '102. Binary Tree Level Order Traversal'
|
||||
description: Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level)
|
||||
sidebar:
|
||||
label: 'Binary Tree Level Order Traversal'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Tree BFS</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `root = [3,9,20,null,null,15,7]`
|
||||
- Output: `[[3],[9,20],[15,7]]`
|
||||
|
||||
### Example 2:
|
||||
- Input: `root = [1]`
|
||||
- Output: `[[1]]`
|
||||
|
||||
### Example 3:
|
||||
- Input: `root = []`
|
||||
- Output: `[]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in the tree is in the range [0, 2000].
|
||||
- `-1000 <= Node.val <= 1000`
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
from collections import deque
|
||||
|
||||
|
||||
class Solution:
|
||||
# T: O(n) S: O(n)
|
||||
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
|
||||
res = []
|
||||
|
||||
q = deque()
|
||||
q.append(root)
|
||||
|
||||
while q:
|
||||
qLen = len(q)
|
||||
level = []
|
||||
for i in range(qLen):
|
||||
node = q.popleft()
|
||||
if node:
|
||||
level.append(node.val)
|
||||
q.append(node.left)
|
||||
q.append(node.right)
|
||||
if level:
|
||||
res.append(level)
|
||||
|
||||
return res
|
||||
```
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: '104. Maximum Depth of Binary Tree'
|
||||
description: Given the root of a binary tree, return its maximum depth
|
||||
sidebar:
|
||||
label: 'Maximum Depth of Binary Tree'
|
||||
badge: 'Easy'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Tree DFS</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `root = [3,9,20,null,null,15,7]`
|
||||
- Output: `3`
|
||||
|
||||
### Example 2:
|
||||
- Input: `root = [1,null,2]`
|
||||
- Output: `2`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in the tree is in the range [0, 10^4].
|
||||
- `-100 <= Node.val <= 100`
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
class Solution:
|
||||
def maxDepth(self, root: Optional[TreeNode]) -> int:
|
||||
if not root:
|
||||
return 0
|
||||
|
||||
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
|
||||
```
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
title: '1448. Count Good Nodes in Binary Tree'
|
||||
description: Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X
|
||||
sidebar:
|
||||
label: 'Count Good Nodes in Binary Tree'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Tree BFS</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `root = [3,1,4,3,null,1,5]`
|
||||
- Output: `4`
|
||||
- Explanation: Nodes in blue are good. Root Node `(3`) is always a good node. Node `4` -> (3,4) is the maximum value in the path starting from the `root`. Node `5` -> (3,4,5) is the maximum value in the path Node `3` -> (3,1,3) is the maximum value in the path.
|
||||
|
||||
### Example 2:
|
||||
- Input: `root = [3,3,null,4,2]`
|
||||
- Output: `3`
|
||||
- Explanation: Node `2` -> `(3`, `3`, `2`) is not good, because `"3`" is higher than it.
|
||||
|
||||
### Example 3:
|
||||
- Input: `root = [1]`
|
||||
- Output: `1`
|
||||
- Explanation: Root is considered as good.
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in the binary tree is in the range [1, 10^5].
|
||||
- Each node's value is between [-10^4, 10^4].
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
class Solution:
|
||||
def goodNodes(self, root: TreeNode) -> int:
|
||||
def dfs(node, max_val):
|
||||
if not node:
|
||||
return 0
|
||||
|
||||
is_good = 1 if node.val >= max_val else 0
|
||||
new_max = max(max_val, node.val)
|
||||
|
||||
return is_good + dfs(node.left, new_max) + dfs(node.right, new_max)
|
||||
|
||||
return dfs(root, root.val)
|
||||
```
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
title: '199. Binary Tree Right Side View'
|
||||
description: Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom
|
||||
sidebar:
|
||||
label: 'Binary Tree Right Side View'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Tree BFS</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `root = [1,2,3,null,5,null,4]`
|
||||
- Output: `[1,3,4]`
|
||||
|
||||
### Example 2:
|
||||
- Input: `root = [1,2,3,4,null,null,null,5]`
|
||||
- Output: `[1,3,4,5]`
|
||||
|
||||
### Example 3:
|
||||
- Input: `root = [1,null,3]`
|
||||
- Output: `[1,3]`
|
||||
|
||||
### Example 4:
|
||||
- Input: `root = []`
|
||||
- Output: `[]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in the tree is in the range [0, 100].
|
||||
- `-100 <= Node.val <= 100`
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
from collections import deque
|
||||
|
||||
|
||||
class Solution:
|
||||
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
|
||||
res = []
|
||||
q = deque([root])
|
||||
|
||||
while q:
|
||||
rightSide = None
|
||||
qLen = len(q)
|
||||
|
||||
for i in range(qLen):
|
||||
node = q.popleft()
|
||||
if node:
|
||||
rightSide = node
|
||||
q.append(node.left)
|
||||
q.append(node.right)
|
||||
|
||||
if rightSide:
|
||||
res.append(rightSide.val)
|
||||
|
||||
return res
|
||||
```
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: '226. Invert Binary Tree'
|
||||
description: Given the root of a binary tree, invert the tree, and return its root
|
||||
sidebar:
|
||||
label: 'Invert Binary Tree'
|
||||
badge: 'Easy'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Tree DFS</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `root = [4,2,7,1,3,6,9]`
|
||||
- Output: `[4,7,2,9,6,3,1]`
|
||||
|
||||
### Example 2:
|
||||
- Input: `root = [2,1,3]`
|
||||
- Output: `[2,3,1]`
|
||||
|
||||
### Example 3:
|
||||
- Input: `root = []`
|
||||
- Output: `[]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in the tree is in the range [0, 100].
|
||||
- `-100 <= Node.val <= 100`
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
class Solution:
|
||||
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
|
||||
if not root:
|
||||
return None
|
||||
|
||||
left = self.invertTree(root.left)
|
||||
right = self.invertTree(root.right)
|
||||
|
||||
root.left = right
|
||||
root.right = left
|
||||
|
||||
return root
|
||||
```
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
title: '236. Lowest Common Ancestor of a Binary Tree'
|
||||
description: Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree
|
||||
sidebar:
|
||||
label: 'Lowest Common Ancestor of a Binary Tree'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Tree DFS</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1`
|
||||
- Output: `3`
|
||||
- Explanation: The LCA of nodes `5` and `1` is `3`.
|
||||
|
||||
### Example 2:
|
||||
- Input: `root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4`
|
||||
- Output: `5`
|
||||
- Explanation: The LCA of nodes `5` and `4` is `5`, since a node can be a descendant of itself according to the LCA definition.
|
||||
|
||||
### Example 3:
|
||||
- Input: `root = [1,2], p = 1, q = 2`
|
||||
- Output: `1`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in the tree is in the range [2, 10^5].
|
||||
- `-10^9 <= Node.val <= 10^9`
|
||||
- All Node.val are unique.
|
||||
- `p != q`
|
||||
- p and q will exist in the tree.
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, x):
|
||||
# self.val = x
|
||||
# self.left = None
|
||||
# self.right = None
|
||||
|
||||
|
||||
class Solution:
|
||||
def lowestCommonAncestor(
|
||||
self, root: "TreeNode", p: "TreeNode", q: "TreeNode"
|
||||
) -> "TreeNode":
|
||||
|
||||
if not root:
|
||||
return None
|
||||
|
||||
if root == p or root == q:
|
||||
return root
|
||||
|
||||
l = self.lowestCommonAncestor(root.left, p, q)
|
||||
r = self.lowestCommonAncestor(root.right, p, q)
|
||||
|
||||
if l and r:
|
||||
return root
|
||||
else:
|
||||
return l or r
|
||||
```
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
104. Maximum Depth of Binary Tree
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/maximum-depth-of-binary-tree/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given the root of a binary tree, return its maximum depth.
|
||||
|
||||
A binary tree's maximum depth is the number of nodes along the
|
||||
longest path from the root node down to the farthest leaf node.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: root = [3,9,20,null,null,15,7]
|
||||
Output: 3
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: root = [1,null,2]
|
||||
Output: 2
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• The number of nodes in the tree is in the range [0, 10^4].
|
||||
|
||||
• -100 <= Node.val <= 100
|
||||
"""
|
||||
|
||||
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
class Solution:
|
||||
def maxDepth(self, root: Optional[TreeNode]) -> int:
|
||||
if not root:
|
||||
return 0
|
||||
|
||||
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
|
||||
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
226. Invert Binary Tree
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/invert-binary-tree/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given the root of a binary tree, invert the tree, and return its root.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: root = [4,2,7,1,3,6,9]
|
||||
Output: [4,7,2,9,6,3,1]
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: root = [2,1,3]
|
||||
Output: [2,3,1]
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: root = []
|
||||
Output: []
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• The number of nodes in the tree is in the range [0, 100].
|
||||
|
||||
• -100 <= Node.val <= 100
|
||||
"""
|
||||
|
||||
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
class Solution:
|
||||
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
|
||||
if not root:
|
||||
return None
|
||||
|
||||
left = self.invertTree(root.left)
|
||||
right = self.invertTree(root.right)
|
||||
|
||||
root.left = right
|
||||
root.right = left
|
||||
|
||||
return root
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
48. Rotate Image
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/rotate-image/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
You are given an n x n 2D matrix representing an image, rotate the
|
||||
image by 90 degrees (clockwise).
|
||||
|
||||
You have to rotate the image in-place, which means you have to modify
|
||||
the input 2D matrix directly. DO NOT allocate another 2D matrix and do
|
||||
the rotation.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
|
||||
Output: [[7,4,1],[8,5,2],[9,6,3]]
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
|
||||
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• n == matrix.length == matrix[i].length
|
||||
|
||||
• 1 <= n <= 20
|
||||
|
||||
• -1000 <= matrix[i][j] <= 1000
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def rotate(self, matrix: List[List[int]]) -> None:
|
||||
n = len(matrix)
|
||||
for r in range(n):
|
||||
for c in range(r + 1, n):
|
||||
matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
|
||||
|
||||
for r in range(n):
|
||||
matrix[r].reverse()
|
||||
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
54. Spiral Matrix
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/spiral-matrix/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given an m x n matrix, return all elements of the matrix in spiral
|
||||
order.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
|
||||
Output: [1,2,3,6,9,8,7,4,5]
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
|
||||
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• m == matrix.length
|
||||
|
||||
• n == matrix[i].length
|
||||
|
||||
• 1 <= m, n <= 10
|
||||
|
||||
• -100 <= matrix[i][j] <= 100
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
|
||||
res = []
|
||||
top, bottom = 0, len(matrix) - 1
|
||||
left, right = 0, len(matrix[0]) - 1
|
||||
|
||||
while top <= bottom and left <= right:
|
||||
# 1. Top Row
|
||||
for c in range(left, right + 1):
|
||||
res.append(matrix[top][c])
|
||||
top += 1
|
||||
|
||||
# 2. Right Column
|
||||
for r in range(top, bottom + 1):
|
||||
res.append(matrix[r][right])
|
||||
right -= 1
|
||||
|
||||
# 3. Bottom Row
|
||||
if top <= bottom:
|
||||
for c in range(right, left - 1, -1):
|
||||
res.append(matrix[bottom][c])
|
||||
bottom -= 1
|
||||
|
||||
# 4. Left Column
|
||||
if left <= right:
|
||||
for r in range(bottom, top - 1, -1):
|
||||
res.append(matrix[r][left])
|
||||
left += 1
|
||||
|
||||
return res
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
73. Set Matrix Zeroes
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/set-matrix-zeroes/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given an m x n integer matrix matrix, if an element is 0, set its
|
||||
entire row and column to 0's.
|
||||
|
||||
You must do it in place.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
|
||||
Output: [[1,0,1],[0,0,0],[1,0,1]]
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
|
||||
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• m == matrix.length
|
||||
|
||||
• n == matrix[0].length
|
||||
|
||||
• 1 <= m, n <= 200
|
||||
|
||||
• -2^31 <= matrix[i][j] <= 2^31 - 1
|
||||
|
||||
|
||||
|
||||
Follow up:
|
||||
|
||||
• A straightforward solution using O(mn) space is probably a bad
|
||||
idea.
|
||||
|
||||
• A simple improvement uses O(m + n) space, but still not the best
|
||||
solution.
|
||||
|
||||
• Could you devise a constant space solution?
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def setZeroes(self, matrix: List[List[int]]) -> None:
|
||||
"""
|
||||
Do not return anything, modify matrix in-place instead.
|
||||
"""
|
||||
m, n = len(matrix), len(matrix[0])
|
||||
|
||||
# 1. remember if row 0 or column 0 have their own zeros
|
||||
row0_zero = any(matrix[0][c] == 0 for c in range(n))
|
||||
col0_zero = any(matrix[r][0] == 0 for r in range(m))
|
||||
|
||||
# 2. use row 0 and column 0 as marker lists
|
||||
for r in range(1, m):
|
||||
for c in range(1, n):
|
||||
if matrix[r][c] == 0:
|
||||
matrix[r][0] = 0
|
||||
matrix[0][c] = 0
|
||||
|
||||
# 3. zero the inner cells from the markers
|
||||
for r in range(1, m):
|
||||
for c in range(1, n):
|
||||
if matrix[r][0] == 0 or matrix[0][c] == 0:
|
||||
matrix[r][c] = 0
|
||||
|
||||
# 4. handle row 0 and column 0 last
|
||||
if row0_zero:
|
||||
for c in range(n):
|
||||
matrix[0][c] = 0
|
||||
if col0_zero:
|
||||
for r in range(m):
|
||||
matrix[r][0] = 0
|
||||
@@ -53,9 +53,18 @@ class Solution:
|
||||
def addTwoNumbers(
|
||||
self, l1: Optional[ListNode], l2: Optional[ListNode]
|
||||
) -> Optional[ListNode]:
|
||||
head = ListNode()
|
||||
|
||||
dummy = ListNode()
|
||||
carry = 0
|
||||
l1curr = head
|
||||
l2curr = head
|
||||
while head:
|
||||
l1.val + l2.val
|
||||
curr = dummy
|
||||
while l1 or l2 or carry:
|
||||
s = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
|
||||
carry, val = divmod(s, 10)
|
||||
|
||||
curr.next = ListNode(val)
|
||||
curr = curr.next
|
||||
|
||||
l1 = l1.next if l1 else None
|
||||
l2 = l2.next if l2 else None
|
||||
|
||||
return dummy.next
|
||||
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
102. Binary Tree Level Order Traversal
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/binary-tree-level-order-traversal/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given the root of a binary tree, return the level order traversal of
|
||||
its nodes' values. (i.e., from left to right, level by level).
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: root = [3,9,20,null,null,15,7]
|
||||
Output: [[3],[9,20],[15,7]]
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: root = [1]
|
||||
Output: [[1]]
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: root = []
|
||||
Output: []
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• The number of nodes in the tree is in the range [0, 2000].
|
||||
|
||||
• -1000 <= Node.val <= 1000
|
||||
"""
|
||||
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
from collections import deque
|
||||
|
||||
|
||||
class Solution:
|
||||
# T: O(n) S: O(n)
|
||||
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
|
||||
res = []
|
||||
|
||||
q = deque()
|
||||
q.append(root)
|
||||
|
||||
while q:
|
||||
qLen = len(q)
|
||||
level = []
|
||||
for i in range(qLen):
|
||||
node = q.popleft()
|
||||
if node:
|
||||
level.append(node.val)
|
||||
q.append(node.left)
|
||||
q.append(node.right)
|
||||
if level:
|
||||
res.append(level)
|
||||
|
||||
return res
|
||||
@@ -0,0 +1,94 @@
|
||||
"""
|
||||
1448. Count Good Nodes in Binary Tree
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/count-good-nodes-in-binary-tree/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given a binary tree root, a node X in the tree is named good if in
|
||||
the path from root to X there are no nodes with a value greater than
|
||||
X.
|
||||
|
||||
|
||||
|
||||
Return the number of good nodes in the binary tree.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Input: root = [3,1,4,3,null,1,5]
|
||||
Output: 4
|
||||
Explanation: Nodes in blue are good.
|
||||
Root Node (3) is always a good node.
|
||||
Node 4 -> (3,4) is the maximum value in the path starting from the
|
||||
root.
|
||||
Node 5 -> (3,4,5) is the maximum value in the path
|
||||
Node 3 -> (3,1,3) is the maximum value in the path.
|
||||
|
||||
|
||||
Example 2:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Input: root = [3,3,null,4,2]
|
||||
Output: 3
|
||||
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher
|
||||
than it.
|
||||
|
||||
|
||||
Example 3:
|
||||
|
||||
|
||||
|
||||
|
||||
Input: root = [1]
|
||||
Output: 1
|
||||
Explanation: Root is considered as good.
|
||||
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
|
||||
|
||||
|
||||
• The number of nodes in the binary tree is in the range [1, 10^5].
|
||||
|
||||
• Each node's value is between [-10^4, 10^4].
|
||||
"""
|
||||
|
||||
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
class Solution:
|
||||
def goodNodes(self, root: TreeNode) -> int:
|
||||
def dfs(node, max_val):
|
||||
if not node:
|
||||
return 0
|
||||
|
||||
is_good = 1 if node.val >= max_val else 0
|
||||
new_max = max(max_val, node.val)
|
||||
|
||||
return is_good + dfs(node.left, new_max) + dfs(node.right, new_max)
|
||||
|
||||
return dfs(root, root.val)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
199. Binary Tree Right Side View
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/binary-tree-right-side-view/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given the root of a binary tree, imagine yourself standing on the
|
||||
right side of it, return the values of the nodes you can see ordered
|
||||
from top to bottom.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: root = [1,2,3,null,5,null,4]
|
||||
|
||||
Output: [1,3,4]
|
||||
|
||||
Explanation:
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: root = [1,2,3,4,null,null,null,5]
|
||||
|
||||
Output: [1,3,4,5]
|
||||
|
||||
Explanation:
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: root = [1,null,3]
|
||||
|
||||
Output: [1,3]
|
||||
|
||||
Example 4:
|
||||
|
||||
Input: root = []
|
||||
|
||||
Output: []
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• The number of nodes in the tree is in the range [0, 100].
|
||||
|
||||
• -100 <= Node.val <= 100
|
||||
"""
|
||||
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
from collections import deque
|
||||
|
||||
|
||||
class Solution:
|
||||
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
|
||||
res = []
|
||||
q = deque([root])
|
||||
|
||||
while q:
|
||||
rightSide = None
|
||||
qLen = len(q)
|
||||
|
||||
for i in range(qLen):
|
||||
node = q.popleft()
|
||||
if node:
|
||||
rightSide = node
|
||||
q.append(node.left)
|
||||
q.append(node.right)
|
||||
|
||||
if rightSide:
|
||||
res.append(rightSide.val)
|
||||
|
||||
return res
|
||||
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
236. Lowest Common Ancestor of a Binary Tree
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given a binary tree, find the lowest common ancestor (LCA) of two
|
||||
given nodes in the tree.
|
||||
|
||||
According to the definition of LCA on Wikipedia: “The lowest
|
||||
common ancestor is defined between two nodes p and q as the lowest
|
||||
node in T that has both p and q as descendants (where we allow a node
|
||||
to be a descendant of itself).”
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
|
||||
Output: 3
|
||||
Explanation: The LCA of nodes 5 and 1 is 3.
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
|
||||
Output: 5
|
||||
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a
|
||||
descendant of itself according to the LCA definition.
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: root = [1,2], p = 1, q = 2
|
||||
Output: 1
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• The number of nodes in the tree is in the range [2, 10^5].
|
||||
|
||||
• -10^9 <= Node.val <= 10^9
|
||||
|
||||
• All Node.val are unique.
|
||||
|
||||
• p != q
|
||||
|
||||
• p and q will exist in the tree.
|
||||
"""
|
||||
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, x):
|
||||
# self.val = x
|
||||
# self.left = None
|
||||
# self.right = None
|
||||
|
||||
|
||||
class Solution:
|
||||
def lowestCommonAncestor(
|
||||
self, root: "TreeNode", p: "TreeNode", q: "TreeNode"
|
||||
) -> "TreeNode":
|
||||
|
||||
if not root:
|
||||
return None
|
||||
|
||||
if root == p or root == q:
|
||||
return root
|
||||
|
||||
l = self.lowestCommonAncestor(root.left, p, q)
|
||||
r = self.lowestCommonAncestor(root.right, p, q)
|
||||
|
||||
if l and r:
|
||||
return root
|
||||
else:
|
||||
return l or r
|
||||
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
49. Group Anagrams
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/group-anagrams/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given an array of strings strs, group the anagrams together. You can
|
||||
return the answer in any order.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: strs = ["eat","tea","tan","ate","nat","bat"]
|
||||
|
||||
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
|
||||
|
||||
Explanation:
|
||||
|
||||
• There is no string in strs that can be rearranged to form "bat".
|
||||
|
||||
• The strings "nat" and "tan" are anagrams as they can be rearranged
|
||||
to form each other.
|
||||
|
||||
• The strings "ate", "eat", and "tea" are anagrams as they can be
|
||||
rearranged to form each other.
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: strs = [""]
|
||||
|
||||
Output: [[""]]
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: strs = ["a"]
|
||||
|
||||
Output: [["a"]]
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 1 <= strs.length <= 10^4
|
||||
|
||||
• 0 <= strs[i].length <= 100
|
||||
|
||||
• strs[i] consists of lowercase English letters.
|
||||
"""
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
class Solution:
|
||||
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
|
||||
if not strs:
|
||||
return strs
|
||||
res = defaultdict(list)
|
||||
for s in strs:
|
||||
count = [0] * 26
|
||||
for c in s:
|
||||
count[ord(c) - ord("a")] += 1
|
||||
res[tuple(count)].append(s)
|
||||
|
||||
return res.values()
|
||||
Reference in new issue
Block a user