mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 21:22:43 +00:00
feat: refactored docs structure
This commit is contained in:
1 parent
d388b3000e
commit
9de25fecff
212 files changed
+641
-4169
No files matched your search
+77
@@ -0,0 +1,77 @@
|
||||
---
|
||||
title: '230. Kth Smallest Element in a BST'
|
||||
description: Given the root of a binary search tree, and an integer k, return the k^th smallest value (1-indexed) of all the values of the nodes in the tree
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Tree", slug: "tree" }
|
||||
- { name: "Depth-First Search", slug: "depth-first-search" }
|
||||
- { name: "Binary Search Tree", slug: "binary-search-tree" }
|
||||
- { name: "Binary Tree", slug: "binary-tree" }
|
||||
video: "5LUXSvjmGCw"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/112"
|
||||
sidebar:
|
||||
label: 'Kth Smallest Element in a BST'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
::::warning
|
||||
If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
|
||||
::::
|
||||
|
||||
### Example 1:
|
||||
- Input: `root = [3,1,4,null,2], k = 1`
|
||||
- Output: `1`
|
||||
|
||||
### Example 2:
|
||||
- Input: `root = [5,3,6,2,4,null,null,1], k = 3`
|
||||
- Output: `3`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in the tree is n.
|
||||
- `1 <= k <= n <= 10^4`
|
||||
- `0 <= Node.val <= 10^4`
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["kthSmallest(root, k)"]) --> I["n = 0, stack = [], cur = root"]
|
||||
I --> W{"cur or stack?"}
|
||||
W -- no --> E(["fall off the loop — unreachable, k <= n"])
|
||||
W -- yes --> L{"cur?"}
|
||||
L -- yes --> P["stack.append(cur), cur = cur.left — push the whole left spine"]
|
||||
P --> L
|
||||
L -- no --> O["cur = stack.pop(), n += 1 — nodes pop in ascending order"]
|
||||
O --> K{"n == k?"}
|
||||
K -- yes --> R(["return cur.val"])
|
||||
K -- no --> N["cur = cur.right"]
|
||||
N --> W
|
||||
```
|
||||
|
||||
## 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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
|
||||
n = 0
|
||||
stack = []
|
||||
cur = root
|
||||
|
||||
while cur or stack:
|
||||
while cur:
|
||||
stack.append(cur)
|
||||
cur = cur.left
|
||||
|
||||
cur = stack.pop()
|
||||
n += 1
|
||||
if n == k:
|
||||
return cur.val
|
||||
cur = cur.right
|
||||
```
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: '235. Lowest Common Ancestor of a Binary Search Tree'
|
||||
description: Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Tree", slug: "tree" }
|
||||
- { name: "Depth-First Search", slug: "depth-first-search" }
|
||||
- { name: "Binary Search Tree", slug: "binary-search-tree" }
|
||||
- { name: "Binary Tree", slug: "binary-tree" }
|
||||
- { name: "Binary Lifting", slug: "binary-lifting" }
|
||||
- { name: "Lowest Common Ancestor", slug: "lowest-common-ancestor" }
|
||||
video: "gs2LMfuOR9k"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/113"
|
||||
sidebar:
|
||||
label: 'Lowest Common Ancestor of a Binary Search Tree'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### Example 1:
|
||||
- Input: `root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8`
|
||||
- Output: `6`
|
||||
- Explanation: The LCA of nodes `2` and `8` is `6`.
|
||||
|
||||
### Example 2:
|
||||
- Input: `root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4`
|
||||
- Output: `2`
|
||||
- Explanation: The LCA of nodes `2` and `4` is `2`, since a node can be a descendant of itself according to the LCA definition.
|
||||
|
||||
### Example 3:
|
||||
- Input: `root = [2,1], p = 2, q = 1`
|
||||
- Output: `2`
|
||||
|
||||
### 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 BST.
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["lowestCommonAncestor(root, p, q)"]) --> I["cur = root"]
|
||||
I --> W{"cur?"}
|
||||
W -- no --> E(["fall off the loop — unreachable, p and q exist in the BST"])
|
||||
W -- yes --> A{"p.val < cur.val and q.val < cur.val?"}
|
||||
A -- yes --> L["cur = cur.left — both sit in the left subtree"]
|
||||
L --> W
|
||||
A -- no --> B{"p.val > cur.val and q.val > cur.val?"}
|
||||
B -- yes --> R["cur = cur.right — both sit in the right subtree"]
|
||||
R --> W
|
||||
B -- no --> C(["return cur — the paths to p and q split here"])
|
||||
```
|
||||
|
||||
## 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":
|
||||
cur = root
|
||||
while cur:
|
||||
if p.val < cur.val and q.val < cur.val:
|
||||
cur = cur.left
|
||||
elif p.val > cur.val and q.val > cur.val:
|
||||
cur = cur.right
|
||||
else:
|
||||
return cur
|
||||
```
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
---
|
||||
title: '98. Validate Binary Search Tree'
|
||||
description: Given the root of a binary tree, determine if it is a valid binary search tree (BST)
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Tree", slug: "tree" }
|
||||
- { name: "Depth-First Search", slug: "depth-first-search" }
|
||||
- { name: "Binary Search Tree", slug: "binary-search-tree" }
|
||||
- { name: "Binary Tree", slug: "binary-tree" }
|
||||
video: "s6ATEkipzow"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/111"
|
||||
sidebar:
|
||||
label: 'Validate Binary Search Tree'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### Example 1:
|
||||
- Input: `root = [2,1,3]`
|
||||
- Output: `true`
|
||||
|
||||
### Example 2:
|
||||
- Input: `root = [5,1,4,null,null,3,6]`
|
||||
- Output: `false`
|
||||
- Explanation: The `root` node's value is `5` but its right child's value is `4`.
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in the tree is in the range [1, 10^4].
|
||||
- `-2^31 <= Node.val <= 2^31 - 1`
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["isValidBST(root)"]) --> C["valid(root, float('-inf'), float('inf')) — the root may hold any value"]
|
||||
C --> E(["return that result"])
|
||||
subgraph valid["valid(node, low, high)"]
|
||||
V1{"not node?"}
|
||||
V1 -- yes --> V2(["return True"])
|
||||
V1 -- no --> V3{"not (low < node.val < high)?"}
|
||||
V3 -- yes --> V4(["return False — node breaks a bound set by an ancestor"])
|
||||
V3 -- no --> V5["valid(node.left, low, node.val) and valid(node.right, node.val, high) — each child tightens one bound"]
|
||||
V5 --> V6(["return that result"])
|
||||
end
|
||||
C --> V1
|
||||
```
|
||||
|
||||
## 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 isValidBST(self, root: Optional[TreeNode]) -> bool:
|
||||
def valid(node, low, high):
|
||||
if not node:
|
||||
return True
|
||||
|
||||
if not (low < node.val < high):
|
||||
return False
|
||||
|
||||
return valid(node.left, low, node.val) and valid(node.right, node.val, high)
|
||||
|
||||
return valid(root, float("-inf"), float("inf"))
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: Binary Search Tree
|
||||
description: 'Each node holds a value that is larger than its left subtree and smaller than its right subtree.'
|
||||
hidden: true
|
||||
---
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
---
|
||||
title: '215. Kth Largest Element in an Array'
|
||||
description: Given an integer array nums and an integer k, return the k^th largest element in the array
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Array", slug: "array" }
|
||||
- { name: "Divide and Conquer", slug: "divide-and-conquer" }
|
||||
- { name: "Sorting", slug: "sorting" }
|
||||
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
|
||||
- { name: "Quickselect", slug: "quickselect" }
|
||||
video: "XEmy13g1Qxc"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/118"
|
||||
sidebar:
|
||||
label: 'Kth Largest Element in an Array'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### Example 1:
|
||||
- Input: `nums = [3,2,1,5,6,4], k = 2`
|
||||
- Output: `5`
|
||||
|
||||
### Example 2:
|
||||
- Input: `nums = [3,2,3,1,2,4,5,5,6], k = 4`
|
||||
- Output: `4`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- `1 <= k <= nums.length <= 10^5`
|
||||
- `-10^4 <= nums[i] <= 10^4`
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["findKthLargest(nums, k)"]) --> F{"more i in range(len(nums))?"}
|
||||
F -- yes --> N["nums[i] = -nums[i] — negate so the min-heap acts as a max-heap"]
|
||||
N --> F
|
||||
F -- no --> H["heapq.heapify(nums)"]
|
||||
H --> W{"more _ in range(k - 1)?"}
|
||||
W -- yes --> P["heapq.heappop(nums) — discard the k-1 largest"]
|
||||
P --> W
|
||||
W -- no --> E(["return -heapq.heappop(nums)"])
|
||||
```
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
import heapq
|
||||
|
||||
|
||||
class Solution:
|
||||
def findKthLargest(self, nums: List[int], k: int) -> int:
|
||||
for i in range(len(nums)):
|
||||
nums[i] = -nums[i]
|
||||
|
||||
heapq.heapify(nums)
|
||||
|
||||
for _ in range(k - 1):
|
||||
heapq.heappop(nums)
|
||||
|
||||
return -heapq.heappop(nums)
|
||||
```
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
title: '23. Merge k Sorted Lists'
|
||||
description: You are given an array of k linked-lists lists, each linked-list is sorted in ascending order
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Linked List", slug: "linked-list" }
|
||||
- { name: "Divide and Conquer", slug: "divide-and-conquer" }
|
||||
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
|
||||
- { name: "Merge Sort", slug: "merge-sort" }
|
||||
- { name: "Tournament Sort", slug: "tournament-sort" }
|
||||
video: "q5a5OiGbT6Q"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/120"
|
||||
sidebar:
|
||||
label: 'Merge k Sorted Lists'
|
||||
badge: 'Hard'
|
||||
---
|
||||
|
||||
### Example 1:
|
||||
- Input: `lists = [[1,4,5],[1,3,4],[2,6]]`
|
||||
- Output: `[1,1,2,3,4,4,5,6]`
|
||||
- Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted linked list: 1->1->2->3->4->4->5->6
|
||||
|
||||
### Example 2:
|
||||
- Input: `lists = []`
|
||||
- Output: `[]`
|
||||
|
||||
### Example 3:
|
||||
- Input: `lists = [[]]`
|
||||
- Output: `[]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- `k == lists.length`
|
||||
- `0 <= k <= 10^4`
|
||||
- `0 <= lists[i].length <= 500`
|
||||
- `-10^4 <= lists[i][j] <= 10^4`
|
||||
- `lists[i]` is sorted in ascending order.
|
||||
- The sum of lists[i].length will not exceed 10^4.
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["mergeKLists(lists)"]) --> I["heap = []"]
|
||||
I --> F{"more i, node in enumerate(lists)?"}
|
||||
F -- yes --> C{"node?"}
|
||||
C -- yes --> P["heapq.heappush(heap, (node.val, i, node)) — i breaks ties so nodes are never compared"]
|
||||
P --> F
|
||||
C -- no --> F
|
||||
F -- no --> D["D = ListNode(), cur = D"]
|
||||
D --> W{"heap?"}
|
||||
W -- no --> E(["return D.next"])
|
||||
W -- yes --> O["val, i, node = heapq.heappop(heap) — the smallest head across all lists"]
|
||||
O --> L["cur.next = node, cur = node, node = node.next"]
|
||||
L --> N{"node?"}
|
||||
N -- yes --> Q["heapq.heappush(heap, (node.val, i, node))"]
|
||||
Q --> W
|
||||
N -- no --> W
|
||||
```
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, val=0, next=None):
|
||||
# self.val = val
|
||||
# self.next = next
|
||||
import heapq
|
||||
|
||||
|
||||
class Solution:
|
||||
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
|
||||
heap = []
|
||||
|
||||
# K log K
|
||||
for i, node in enumerate(lists):
|
||||
if node:
|
||||
heapq.heappush(heap, (node.val, i, node))
|
||||
|
||||
D = ListNode()
|
||||
cur = D
|
||||
|
||||
# n log k
|
||||
while heap:
|
||||
val, i, node = heapq.heappop(heap)
|
||||
cur.next = node
|
||||
cur = node
|
||||
node = node.next
|
||||
|
||||
if node:
|
||||
heapq.heappush(heap, (node.val, i, node))
|
||||
|
||||
# Time: O(N log k)
|
||||
# Space: O(n)
|
||||
return D.next
|
||||
```
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
---
|
||||
title: '973. K Closest Points to Origin'
|
||||
description: Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0)
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Array", slug: "array" }
|
||||
- { name: "Math", slug: "math" }
|
||||
- { name: "Divide and Conquer", slug: "divide-and-conquer" }
|
||||
- { name: "Geometry", slug: "geometry" }
|
||||
- { name: "Sorting", slug: "sorting" }
|
||||
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
|
||||
- { name: "Quickselect", slug: "quickselect" }
|
||||
- { name: "K-D Tree", slug: "k-d-tree" }
|
||||
video: "rI2EBUEMfTk"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/119"
|
||||
sidebar:
|
||||
label: 'K Closest Points to Origin'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### Example 1:
|
||||
- Input: `points = [[1,3],[-2,2]], k = 1`
|
||||
- Output: `[[-2,2]]`
|
||||
- Explanation: The distance between `(1`, `3`) and the origin is sqrt(10). The distance between `(-2`, `2`) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), `(-2`, `2`) is closer to the origin. We only want the closest `k = 1 points` from the origin, so the answer is just [[-2,2]].
|
||||
|
||||
### Example 2:
|
||||
- Input: `points = [[3,3],[5,-1],[-2,4]], k = 2`
|
||||
- Output: `[[3,3],[-2,4]]`
|
||||
- Explanation: The answer [[-2,4],[3,3]] would also be accepted.
|
||||
|
||||
### Constraints:
|
||||
|
||||
- `1 <= k <= points.length <= 10^4`
|
||||
- `-10^4 <= xi, yi <= 10^4`
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["kClosest(points, k)"]) --> I["minHeap = []"]
|
||||
I --> F{"more x, y in points?"}
|
||||
F -- yes --> D["dist = x**2 + y**2 — squared distance orders the same as sqrt"]
|
||||
D --> A["minHeap.append([dist, x, y])"]
|
||||
A --> F
|
||||
F -- no --> H["heapq.heapify(minHeap), res = [] — O(n) build, smallest dist on top"]
|
||||
H --> W{"k > 0?"}
|
||||
W -- yes --> P["dist, x, y = heapq.heappop(minHeap)"]
|
||||
P --> R["res.append([x, y]), k -= 1"]
|
||||
R --> W
|
||||
W -- no --> E(["return res"])
|
||||
```
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
import heapq
|
||||
|
||||
|
||||
class Solution:
|
||||
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
|
||||
minHeap = []
|
||||
for x, y in points:
|
||||
dist = (x**2) + (y**2)
|
||||
minHeap.append([dist, x, y])
|
||||
|
||||
heapq.heapify(minHeap)
|
||||
res = []
|
||||
|
||||
while k > 0:
|
||||
dist, x, y = heapq.heappop(minHeap)
|
||||
res.append([x, y])
|
||||
k -= 1
|
||||
|
||||
return res
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: Heap / Priority Queue
|
||||
description: 'The largest or smallest item is always at the top, and it is removed in logarithmic time.'
|
||||
hidden: true
|
||||
---
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
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)
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Tree", slug: "tree" }
|
||||
- { name: "Breadth-First Search", slug: "breadth-first-search" }
|
||||
- { name: "Binary Tree", slug: "binary-tree" }
|
||||
video: "6ZnyEApgFYg"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/106"
|
||||
sidebar:
|
||||
label: 'Binary Tree Level Order Traversal'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### 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`
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["levelOrder(root)"]) --> I["res = [], q = deque(), q.append(root)"]
|
||||
I --> W{"q non-empty?"}
|
||||
W -- no --> E(["return res"])
|
||||
W -- yes --> L["qLen = len(q), level = [] — qLen freezes the current level's size"]
|
||||
L --> F{"more i in range(qLen)?"}
|
||||
F -- no --> V{"level non-empty?"}
|
||||
V -- yes --> A["res.append(level)"]
|
||||
A --> W
|
||||
V -- no --> W
|
||||
F -- yes --> P["node = q.popleft()"]
|
||||
P --> N{"node is not None?"}
|
||||
N -- no --> F
|
||||
N -- yes --> C["level.append(node.val), q.append(node.left), q.append(node.right) — None children are filtered on the next level"]
|
||||
C --> F
|
||||
```
|
||||
|
||||
## 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,74 @@
|
||||
---
|
||||
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
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Tree", slug: "tree" }
|
||||
- { name: "Depth-First Search", slug: "depth-first-search" }
|
||||
- { name: "Breadth-First Search", slug: "breadth-first-search" }
|
||||
- { name: "Binary Tree", slug: "binary-tree" }
|
||||
video: "7cp5imvDzl4"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/108"
|
||||
sidebar:
|
||||
label: 'Count Good Nodes in Binary Tree'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### 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].
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["goodNodes(root)"]) --> C["dfs(root, root.val) — the root is always good"]
|
||||
C --> E(["return that count"])
|
||||
subgraph dfs["dfs(node, max_val)"]
|
||||
D1{"node is None?"} -- yes --> D2(["return 0"])
|
||||
D1 -- no --> D3["is_good = 1 if node.val >= max_val else 0 — max_val is the largest value on the path so far"]
|
||||
D3 --> D4["new_max = max(max_val, node.val)"]
|
||||
D4 --> D5["l = dfs(node.left, new_max), r = dfs(node.right, new_max)"]
|
||||
D5 --> D6(["return is_good + l + r"])
|
||||
end
|
||||
C --> dfs
|
||||
```
|
||||
|
||||
## 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,90 @@
|
||||
---
|
||||
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
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Tree", slug: "tree" }
|
||||
- { name: "Depth-First Search", slug: "depth-first-search" }
|
||||
- { name: "Breadth-First Search", slug: "breadth-first-search" }
|
||||
- { name: "Binary Tree", slug: "binary-tree" }
|
||||
video: "d4zLyf32e3I"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/107"
|
||||
sidebar:
|
||||
label: 'Binary Tree Right Side View'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### 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`
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["rightSideView(root)"]) --> I["res = [], q = deque([root])"]
|
||||
I --> W{"q non-empty?"}
|
||||
W -- no --> E(["return res"])
|
||||
W -- yes --> L["rightSide = None, qLen = len(q) — qLen freezes the current level's size"]
|
||||
L --> F{"more i in range(qLen)?"}
|
||||
F -- no --> V{"rightSide is not None?"}
|
||||
V -- yes --> A["res.append(rightSide.val) — the last real node popped on this level is the rightmost"]
|
||||
A --> W
|
||||
V -- no --> W
|
||||
F -- yes --> P["node = q.popleft()"]
|
||||
P --> N{"node is not None?"}
|
||||
N -- no --> F
|
||||
N -- yes --> C["rightSide = node, q.append(node.left), q.append(node.right)"]
|
||||
C --> F
|
||||
```
|
||||
|
||||
## 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,5 @@
|
||||
---
|
||||
title: Tree BFS
|
||||
description: 'All nodes at one level are visited before the nodes at the next level.'
|
||||
hidden: true
|
||||
---
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: '104. Maximum Depth of Binary Tree'
|
||||
description: Given the root of a binary tree, return its maximum depth
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Tree", slug: "tree" }
|
||||
- { name: "Depth-First Search", slug: "depth-first-search" }
|
||||
- { name: "Breadth-First Search", slug: "breadth-first-search" }
|
||||
- { name: "Binary Tree", slug: "binary-tree" }
|
||||
video: "hTM3phVI6YQ"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/97"
|
||||
sidebar:
|
||||
label: 'Maximum Depth of Binary Tree'
|
||||
badge: 'Easy'
|
||||
---
|
||||
|
||||
### 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`
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["maxDepth(root)"]) --> B{"root is None?"}
|
||||
B -- yes --> Z(["return 0"])
|
||||
B -- no --> L["l = maxDepth(root.left), r = maxDepth(root.right)"]
|
||||
L --> E(["return 1 + max(l, r) — this node adds one level above its deeper subtree"])
|
||||
```
|
||||
|
||||
## 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,66 @@
|
||||
---
|
||||
title: '226. Invert Binary Tree'
|
||||
description: Given the root of a binary tree, invert the tree, and return its root
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Tree", slug: "tree" }
|
||||
- { name: "Depth-First Search", slug: "depth-first-search" }
|
||||
- { name: "Breadth-First Search", slug: "breadth-first-search" }
|
||||
- { name: "Binary Tree", slug: "binary-tree" }
|
||||
video: "OnSn2XEQ4MY"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/96"
|
||||
sidebar:
|
||||
label: 'Invert Binary Tree'
|
||||
badge: 'Easy'
|
||||
---
|
||||
|
||||
### 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`
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["invertTree(root)"]) --> B{"root is None?"}
|
||||
B -- yes --> Z(["return None"])
|
||||
B -- no --> L["left = invertTree(root.left), right = invertTree(root.right) — both subtrees are already inverted"]
|
||||
L --> X["root.left = right, root.right = left"]
|
||||
X --> E(["return root"])
|
||||
```
|
||||
|
||||
## 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
|
||||
```
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
---
|
||||
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
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Tree", slug: "tree" }
|
||||
- { name: "Depth-First Search", slug: "depth-first-search" }
|
||||
- { name: "Binary Tree", slug: "binary-tree" }
|
||||
- { name: "Binary Lifting", slug: "binary-lifting" }
|
||||
- { name: "Lowest Common Ancestor", slug: "lowest-common-ancestor" }
|
||||
issue: "https://github.com/prdlk/leetcode/issues/98"
|
||||
sidebar:
|
||||
label: 'Lowest Common Ancestor of a Binary Tree'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### 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.
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S(["lowestCommonAncestor(root, p, q)"]) --> B{"not root?"}
|
||||
B -- yes --> N(["return None"])
|
||||
B -- no --> M{"root == p or root == q?"}
|
||||
M -- yes --> R(["return root — a node is its own ancestor"])
|
||||
M -- no --> L["l = self.lowestCommonAncestor(root.left, p, q)"]
|
||||
L --> Q["r = self.lowestCommonAncestor(root.right, p, q)"]
|
||||
Q --> D{"l and r?"}
|
||||
D -- yes --> A(["return root — p and q were found on different sides"])
|
||||
D -- no --> E(["return l or r — pass up whichever side found something"])
|
||||
```
|
||||
|
||||
## 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,5 @@
|
||||
---
|
||||
title: Tree DFS
|
||||
description: 'Each branch is followed to its end before the next branch is examined.'
|
||||
hidden: true
|
||||
---
|
||||
@@ -0,0 +1,114 @@
|
||||
---
|
||||
title: '208. Implement Trie (Prefix Tree)'
|
||||
description: A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "Hash Table", slug: "hash-table" }
|
||||
- { name: "String", slug: "string" }
|
||||
- { name: "Design", slug: "design" }
|
||||
- { name: "Trie", slug: "trie" }
|
||||
video: "oobqoCJlHA0"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/127"
|
||||
sidebar:
|
||||
label: 'Implement Trie (Prefix Tree)'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### Example 1:
|
||||
- Input: ``
|
||||
- Output: ``
|
||||
- Explanation: Input ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] `[[]`, `["apple"]`, `["apple"]`, `["app"]`, `["app"]`, `["app"]`, ["app"]] Output [null, null, true, false, true, null, true] Explanation Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // return True trie.search("app"); // return False trie.startsWith("app"); // return True trie.insert("app"); trie.search("app"); // return True
|
||||
|
||||
### Constraints:
|
||||
|
||||
- `1 <= word.length, prefix.length <= 2000`
|
||||
- `word` and `prefix` consist only of lowercase English letters.
|
||||
- At most 3 * 10^4 calls in total will be made to insert, search, and startsWith.
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph state["state — root TrieNode; every node holds a children dict and an endOfWord flag"]
|
||||
R["root"] --- C["... children[c] ..."] --- L["endOfWord = True — a word ends here"]
|
||||
end
|
||||
subgraph insert["insert(word)"]
|
||||
I1["cur = root"] --> I2{"more c in word?"}
|
||||
I2 -- yes --> I3{"c not in cur.children?"}
|
||||
I3 -- yes --> I4["cur.children[c] = TrieNode()"]
|
||||
I4 --> I5["cur = cur.children[c]"]
|
||||
I3 -- no --> I5
|
||||
I5 --> I2
|
||||
I2 -- no --> I6["cur.endOfWord = True"]
|
||||
I6 --> I7(["done"])
|
||||
end
|
||||
subgraph search["search(word)"]
|
||||
S1["cur = root"] --> S2{"more c in word?"}
|
||||
S2 -- yes --> S3{"c not in cur.children?"}
|
||||
S3 -- yes --> S4(["return False"])
|
||||
S3 -- no --> S5["cur = cur.children[c]"]
|
||||
S5 --> S2
|
||||
S2 -- no --> S6(["return cur.endOfWord — the path exists, but is it a whole word?"])
|
||||
end
|
||||
subgraph startsWith["startsWith(prefix)"]
|
||||
P1["cur = root"] --> P2{"more c in prefix?"}
|
||||
P2 -- yes --> P3{"c not in cur.children?"}
|
||||
P3 -- yes --> P4(["return False"])
|
||||
P3 -- no --> P5["cur = cur.children[c]"]
|
||||
P5 --> P2
|
||||
P2 -- no --> P6(["return True — every prefix char had a path"])
|
||||
end
|
||||
state --> insert
|
||||
state --> search
|
||||
state --> startsWith
|
||||
```
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
class TrieNode:
|
||||
def __init__(self):
|
||||
self.children = {}
|
||||
self.endOfWord = False
|
||||
|
||||
|
||||
class Trie:
|
||||
def __init__(self):
|
||||
self.root = TrieNode()
|
||||
|
||||
def insert(self, word: str) -> None:
|
||||
cur = self.root
|
||||
|
||||
for c in word:
|
||||
if c not in cur.children:
|
||||
cur.children[c] = TrieNode()
|
||||
cur = cur.children[c]
|
||||
cur.endOfWord = True
|
||||
|
||||
def search(self, word: str) -> bool:
|
||||
cur = self.root
|
||||
|
||||
for c in word:
|
||||
if c not in cur.children:
|
||||
return False
|
||||
cur = cur.children[c]
|
||||
|
||||
return cur.endOfWord
|
||||
|
||||
def startsWith(self, prefix: str) -> bool:
|
||||
cur = self.root
|
||||
|
||||
for c in prefix:
|
||||
if c not in cur.children:
|
||||
return False
|
||||
cur = cur.children[c]
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# Your Trie object will be instantiated and called as such:
|
||||
# obj = Trie()
|
||||
# obj.insert(word)
|
||||
# param_2 = obj.search(word)
|
||||
# param_3 = obj.startsWith(prefix)
|
||||
```
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
---
|
||||
title: '211. Design Add and Search Words Data Structure'
|
||||
description: Design a data structure that supports adding new words and finding if a string matches any previously added string
|
||||
icon: dot
|
||||
topics:
|
||||
- { name: "String", slug: "string" }
|
||||
- { name: "Depth-First Search", slug: "depth-first-search" }
|
||||
- { name: "Design", slug: "design" }
|
||||
- { name: "Trie", slug: "trie" }
|
||||
video: "BTf05gs_8iU"
|
||||
issue: "https://github.com/prdlk/leetcode/issues/128"
|
||||
sidebar:
|
||||
label: 'Design Add and Search Words Data Structure'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
### Constraints:
|
||||
|
||||
- `1 <= word.length <= 25`
|
||||
- `word` in addWord consists of lowercase English letters.
|
||||
- `word` in search consist of '.' or lowercase English letters.
|
||||
- There will be at most 2 dots in `word` for search queries.
|
||||
- At most 10^4 calls will be made to addWord and search.
|
||||
|
||||
## Approach
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph state["state — root TrieNode; every node holds a children dict and an endOfWord flag"]
|
||||
R["root"] --- C["... children[c] ..."] --- L["endOfWord = True — a word ends here"]
|
||||
end
|
||||
subgraph addWord["addWord(word)"]
|
||||
A1["cur = root"] --> A2{"more c in word?"}
|
||||
A2 -- yes --> A3{"c not in cur.children?"}
|
||||
A3 -- yes --> A4["cur.children[c] = TrieNode()"]
|
||||
A4 --> A5["cur = cur.children[c]"]
|
||||
A3 -- no --> A5
|
||||
A5 --> A2
|
||||
A2 -- no --> A6["cur.endOfWord = True"]
|
||||
A6 --> A7(["done"])
|
||||
end
|
||||
subgraph search["search(word)"]
|
||||
S1["dfs(0, root) — match from index 0 at the root"] --> S2["cur = root"]
|
||||
S2 --> S3{"more i in range(j, len(word))?"}
|
||||
S3 -- no --> S4(["return cur.endOfWord"])
|
||||
S3 -- yes --> S5["c = word[i]"]
|
||||
S5 --> S6{"c == '.'?"}
|
||||
S6 -- yes --> S7{"more child in cur.children.values()?"}
|
||||
S7 -- yes --> S8{"dfs(i + 1, child)? — try the rest of the word from this child"}
|
||||
S8 -- yes --> S9(["return True"])
|
||||
S8 -- no --> S7
|
||||
S7 -- no --> S10(["return False — no child matched the wildcard"])
|
||||
S6 -- no --> S11{"c not in cur.children?"}
|
||||
S11 -- yes --> S12(["return False"])
|
||||
S11 -- no --> S13["cur = cur.children[c]"]
|
||||
S13 --> S3
|
||||
end
|
||||
state --> addWord
|
||||
state --> search
|
||||
```
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
class TrieNode:
|
||||
def __init__(self):
|
||||
self.children = {}
|
||||
self.endOfWord = False
|
||||
|
||||
|
||||
class WordDictionary:
|
||||
def __init__(self):
|
||||
self.root = TrieNode()
|
||||
|
||||
def addWord(self, word: str) -> None:
|
||||
cur = self.root
|
||||
for c in word:
|
||||
if c not in cur.children:
|
||||
cur.children[c] = TrieNode()
|
||||
cur = cur.children[c]
|
||||
cur.endOfWord = True
|
||||
|
||||
# Leverage Recursion
|
||||
def search(self, word: str) -> bool:
|
||||
def dfs(j, root):
|
||||
cur = root
|
||||
for i in range(j, len(word)):
|
||||
c = word[i]
|
||||
|
||||
if c == ".":
|
||||
for child in cur.children.values():
|
||||
if dfs(i + 1, child):
|
||||
return True
|
||||
return False
|
||||
else:
|
||||
if c not in cur.children:
|
||||
return False
|
||||
cur = cur.children[c]
|
||||
return cur.endOfWord
|
||||
|
||||
return dfs(0, self.root)
|
||||
|
||||
|
||||
# Your WordDictionary object will be instantiated and called as such:
|
||||
# obj = WordDictionary()
|
||||
# obj.addWord(word)
|
||||
# param_3 = obj.search(word)
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: Trie
|
||||
description: 'Each node holds one character, and a path from the root spells a word.'
|
||||
hidden: true
|
||||
---
|
||||
Reference in new issue
Block a user