An open API service indexing awesome lists of open source software.

https://github.com/followb1ind1y/leetcode

LeetCode Problems' Python Solutions with Chinese Explanation. LeetCode 问题的 Python 解答和中文理解
https://github.com/followb1ind1y/leetcode

algorithms leetcode leetcode-python leetcode-solutions python

Last synced: 3 months ago
JSON representation

LeetCode Problems' Python Solutions with Chinese Explanation. LeetCode 问题的 Python 解答和中文理解

Awesome Lists containing this project

README

        


Last Commit
Last Commit
Size
Language


binder
colab

# Leetcode Interview Preparation Plan

- [Leetcode Interview Preparation Plan](#leetcode-interview-preparation-plan)
* [Basic Data Structures](#basic-data-structures)
+ [Arrays](#arrays)
+ [Strings](#strings)
+ [Linked Lists](#linked-lists)
+ [Stack](#stack)
+ [Queue](#queue)
+ [Deque](#deque)
* [Advanced Data Structures](#advanced-data-structures)
+ [Heap](#heap)
+ [Tree](#tree)
+ [Hash Tables](#hash-tables)
* [Core Algorithms](#core-algorithms)
+ [Overview](#overview-2)
+ [Two Pointer](#two-pointer)
+ [Prefix Sum and Suffix Sum](#prefix-sum-and-suffix-sum)
+ [Practice](#practice-1)
* [Advanced Algorithms](#advanced-algorithms)
+ [Overview](#overview-3)
+ [Notes](#notes)
+ [Practice](#practice-2)
* [练习记录](#练习记录)

## Basic Data Structures

### **Arrays**
In Python, arrays are typically represented using lists. While Python doesn't have a native array type as seen in other languages like Java or C++, lists are versatile and can be used similarly to arrays.

【`Last Update: 2024-08-14`】
```
arr = [] # O(1)
arr = [1, 2, 3] # O(n), where n is the number of elements
first_element = arr[0] # O(1)
arr[1] = 10 # O(1)
arr.append(6) # O(1) on average for appending
arr.insert(2, 15) # O(n), where n is the number of elements after the insertion index
arr.remove(15) # O(n), where n is the number of elements in the list [remove the first 15 in the array]
del arr[2] # O(n), where n is the number of elements after the deleted index
last_element = arr.pop() # O(1)
arr.sort() # 原地排序
sorted_arr = sorted(arr) # 返回排序后的数组
arr[::-1] # arr 倒序
```
```
## Counter() 的常用语法和使用情况
from collections import Counter
arr = [1, 2, 2, 3, 3, 3]
counts = Counter(arr) # 结果:Counter({3: 3, 2: 2, 1: 1})

## 找到出现次数最多的元素
most_common_element = counts.most_common(1)[0] # 结果:(3, 3)

## 判断出现的元素是否相同
arr1 = [1, 2, 3]
arr2 = [3, 2, 1]
is_anagram = Counter(arr1) == Counter(arr2) # 结果:True
```
```
## set() 的常用语法和使用情况
arr = [1, 2, 2, 3, 4, 4]

## 快速查找
seen = set(arr)
if 3 in seen:
print("3 is in array")

## 去重
unique_elements = list(set(arr)) # 结果:[1, 2, 3, 4]

## 两个数组的交集
arr1 = [1, 2, 2, 3]
arr2 = [2, 3, 4]
intersection = list(set(arr1) & set(arr2)) # 结果:[2, 3]
```
### **Strings**
Strings in Python are immutable sequences of characters. You can perform various operations on strings using built-in methods and operators.

【`Last Update: 2024-08-14`】
```
s = "Hello, World!" # O(n), where n is the length of the string
first_char = s[0] # O(1)
substring = s[7:12] # O(k), where k is the length of the substring
combined = s + " Python" # O(n + m), where n and m are the lengths of the two strings
repeated = s * 2 # O(n * k), where k is the number of repetitions

upper_s = s.upper() # O(n), where n is the length of the string
lower_s = s.lower() # O(n), where n is the length of the string
starts_with_hello = s.startswith("Hello") # O(n), where n is the length of the prefix
contains_world = "World" in s # O(n * m), where n is the length of the string and m is the length of the substring
replaced_s = s.replace("World", "Python") # O(n * m), where n is the length of the string and m is the length of the substring

words = s.split(", ") # O(n), where n is the length of the string
joined = " - ".join(words) # O(n), where n is the total length of the resulting string
```

### **Linked Lists**
A Linked List is a linear data structure consisting of nodes, where each node contains:

* A data part that stores the actual data.
* A next part (or pointer) that points to the next node in the list.

【`Last Update: 2024-11-14`】

```
## A node in a linked list can be represented as a class

class ListNode:
def __init__(self, data=0, next=None):
self.data = data # Data of the node
self.next = next # Pointer to the next node
```
```
## Inserting Nodes

def insert_at_beginning(head, data):
new_node = ListNode(data) # Create a new node
new_node.next = head # Link the new node to the current head
return new_node # New node becomes the head
```
```
## Deleting Nodes

def delete_from_beginning(head):
if not head:
return None
return head.next # The second node becomes the new head
```
```
## Searching for a Node

def search(head, key):
current = head
while current:
if current.data == key:
return True # Found the data
current = current.next
return False # Data not found
```

### **Stack**
A Stack is a linear data structure that stores items in a **Last-In/First-Out (LIFO)** or **First-In/Last-Out (FILO)** manner. In stack, a new element is added at one end and an element is removed from that end only.

* `push(a)` – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
* `pop()` – Deletes the topmost element of the stack – Time Complexity: O(1)
* `Peek` - View the top element without removing it.
* `Empty` - Check if the stack is empty.

【`Last Update: 2024-11-19`】

```
stack = []

# Push elements onto the stack
stack.append(1)
stack.append(2)

# Pop element from the stack
top = stack.pop() # Removes and returns 2

# Peek the top element
top = stack[-1] if stack else None # Returns 1

# Check if the stack is empty
is_empty = len(stack) == 0
```

### **Queue**
Queue is a linear data structure that stores items in **First In First Out (FIFO)** manner. With a queue the least recently added item is removed first.

* `Enqueue`: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity : O(1)
* `Dequeue`: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity : O(1)
* `Peek`: View the front element without removing it.
* `Empty`: Check if the queue is empty.

【`Last Update: 2024-11-19`】

```
from collections import deque

# Initialize a queue
queue = deque()

# Enqueue elements
queue.append(1)
queue.append(2)

# Dequeue element
front = queue.popleft() # Removes and returns 1

# Peek at the front element
front = queue[0] if queue else None

# Check if the queue is empty
is_empty = len(queue) == 0
```

### **Deque**
A deque is a generalized queue that allows insertion and deletion from both ends with O(1) complexity. Internally, it is implemented as a doubly linked list or a circular buffer.

【`Last Update: 2024-11-25`】

```
from collections import deque

# Initialize a deque
dq = deque()

# Add elements
dq.append(1) # Add to the right
dq.appendleft(2) # Add to the left

# Remove elements
dq.pop() # Remove from the right
dq.popleft() # Remove from the left

# Access and manipulation
dq.extend([3, 4]) # Add multiple elements to the right
dq.extendleft([0, -1]) # Add multiple elements to the left (reversed order)
dq.rotate(1) # Rotate elements right
dq.rotate(-1) # Rotate elements left
dq.clear() # Clear all elements
```

## Advanced Data Structures
### **Overview**
- **Trees**: Explore the concepts of binary trees, binary search trees, AVL trees, and tree traversals (in-order, pre-order, post-order, level-order).
- **Graphs**: Learn about different graph representations (adjacency list, adjacency matrix), and traversal algorithms (Depth-First Search, Breadth-First Search) to solve problems like finding connected components or checking cycles.
- **Hash Tables**: Study how hash tables work, including hashing functions, handling collisions, and applications in tasks like item counting or implementing dictionaries.

### **Heap**
A heap is a complete binary tree stored as an array. It maintains the heap property: in a min-heap, **the parent is less than or equal to its children**. Insertions and deletions are **O(log n)** due to the need to maintain the heap property.

* Two main types:
* Min-Heap: The root node is the smallest, and every parent node is smaller than or equal to its children.
* Max-Heap: The root node is the largest, and every parent node is larger than or equal to its children.
* Root Node Access:
* Min-Heap: Root is the smallest element
* Max-Heap: Root is the largest element.
* Efficient Operations:
* Insert and delete both take O(log n).
* Maintains heap properties using adjustments (upward or downward shifts).

【`Last Update: 2024-11-25`】

```
import heapq

# Initialize a heap
heap = []

# Add elements
heapq.heappush(heap, 3) # Push element into the heap
heapq.heappush(heap, 1)
heapq.heappush(heap, 4)

# Access the smallest element
smallest = heap[0]

# Remove elements
min_element = heapq.heappop(heap) # Pop the smallest element

# Heapify an existing list
nums = [4, 1, 7, 3]
heapq.heapify(nums)

# Get n largest or smallest elements
largest = heapq.nlargest(2, nums)
smallest = heapq.nsmallest(2, nums)
```

### **Tree**
A tree is a hierarchical data structure with nodes connected by edges. The topmost node is the root, and nodes with no children are called leaves.

* **Binary Tree**: Each node has at most two children.
* **Binary Search Tree (BST)**: A binary tree where the left child contains values less than the parent, and the right child contains values greater.
* **Balanced Tree**: A tree where the height difference between left and right subtrees of any node is minimal (e.g., AVL tree, Red-Black tree).
* **Tree Traversals**:
* Preorder Traversal (Root, Left, Right)
* Inorder Traversal (Left, Root, Right)
* Postorder Traversal (Left, Right, Root)

```
## Trees are often represented using classes.

class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
```



```
## Preorder Traversal (Root, Left, Right)
def preorder_traversal(root):
if root:
print(root.val)
preorder_traversal(root.left)
preorder_traversal(root.right)

## Inorder Traversal (Left, Root, Right)
def inorder_traversal(root):
if root:
inorder_traversal(root.left)
print(root.val)
inorder_traversal(root.right)

## Postorder Traversal (Left, Right, Root)
def postorder_traversal(root):
if root:
postorder_traversal(root.left)
postorder_traversal(root.right)
print(root.val)
```

```
## Binary Search Tree (BST) Operations

## 1. Insert a Node
def insert_into_bst(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:
root.right = insert_into_bst(root.right, val)
return root

## 2. Search for a Value
def search_bst(root, val):
if not root or root.val == val:
return root
if val < root.val:
return search_bst(root.left, val)
return search_bst(root.right, val)

## 3. Delete a Node
def delete_node(root, key):
if not root:
return None
if key < root.val:
root.left = delete_node(root.left, key)
elif key > root.val:
root.right = delete_node(root.right, key)
else:
if not root.left:
return root.right
if not root.right:
return root.left
min_larger_node = root.right
while min_larger_node.left:
min_larger_node = min_larger_node.left
root.val = min_larger_node.val
root.right = delete_node(root.right, root.val)
return root
```

### **Hash Tables**
In Python, the built-in dict type (short for dictionary) functions as a hash table. Hash tables are a key data structure used for efficient data retrieval and storage, providing average time complexities of O(1) for insertion, deletion, and lookup operations due to their underlying hashing mechanism.

【`Last Update: 2024-11-06`】

```
my_dict = {} # Creating an empty dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'} # Creating a dictionary with initial values
value = my_dict['key1'] # Accessing a value by key
my_dict['key3'] = 'value3' # Adding a new key-value pair
my_dict['key2'] = 'new_value2' # Updating an existing key-value pair
del my_dict['key1'] # Removing an entry by key
value = my_dict.pop('key2') # Popping an entry (removes and returns the value)
exists = 'key3' in my_dict # # Checking if a key is in the dictionary [True]

for key in my_dict:
print(key, my_dict[key]) # Iterating through keys
for key, value in my_dict.items(): # Iterating through key-value pairs
print(key, value)
for value in my_dict.values(): # Iterating through values
print(value)
```

```
# defaultdict 使用方法,没见过的元素不会报错。适用于计数、分组和嵌套字典等应用。

from collections import defaultdict

# 使用 int 类型的 defaultdict
dd = defaultdict(int)
print(dd['missing_key']) # 输出:0,因为 int() 的默认值是 0
print(dd) # 输出:defaultdict(, {'missing_key': 0})

# 统计元素出现次数
data = "abracadabra"
counter = defaultdict(int)
for char in data:
counter[char] += 1
print(counter) # 输出:defaultdict(, {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})

# defaultdict(list)常用于将多个值归类到同一个键下。
data = [("apple", 1), ("banana", 2), ("apple", 3), ("banana", 4)]
grouped_data = defaultdict(list)
for fruit, count in data:
grouped_data[fruit].append(count)
print(grouped_data) # 输出:defaultdict(, {'apple': [1, 3], 'banana': [2, 4]})

# 可以使用dict()将defaultdict转换为普通字典。
dd = defaultdict(int)
dd['a'] += 1
print(dict(dd)) # 输出:{'a': 1}

```

### Practice:
- [ ] Trees:
- [Binary Tree Inorder Traversal - LeetCode 94](https://leetcode.com/problems/binary-tree-inorder-traversal/)
- [Lowest Common Ancestor of a Binary Search Tree - LeetCode 235](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
- [ ] Graphs:
- [Number of Islands - LeetCode 200](https://leetcode.com/problems/number-of-islands/)
- [Course Schedule - LeetCode 207](https://leetcode.com/problems/course-schedule/)
- [ ] Hash Tables:
- [Group Anagrams - LeetCode 49](https://leetcode.com/problems/group-anagrams/)
- [Longest Consecutive Sequence - LeetCode 128](https://leetcode.com/problems/longest-consecutive-sequence/)

## Core Algorithms
### **Overview**
- **Two Pointer**: The two-pointer technique is used primarily in solving array and linked list problems. It involves using two pointers to traverse the data structure, allowing for efficient searching and processing of elements.
- **Sorting Algorithms**: Review the mechanisms and use cases for quicksort, mergesort, and heapsort. Understand the trade-offs in terms of time and space complexity.
- **Search Algorithms**: Study binary search on sorted arrays, and learn about its variations for finding the first or last position of an element.
- **Recursion and Backtracking**: Understand how to apply recursion for solving problems involving permutations, combinations, and other backtrack-required scenarios. Study the call stack mechanism and how to optimize recursion through memoization.
- **Prefix Sum and Suffix Sum**: Prefix Sum and Suffix Sum are techniques used to compute the sum of elements in a subarray quickly by precomputing cumulative sums.

### **Two Pointer**
* Finding Pairs with a Given Sum: When looking for two numbers in a sorted array that add up to a specific target.
* Reversing a String or Array: Using two pointers to swap elements from the start and end until they meet in the middle.
* Merging Two Sorted Arrays: Traversing both arrays simultaneously to create a new sorted array.
* Removing Duplicates from a Sorted Array: Using two pointers to track unique elements.
* 设置 two pointers 的时候,left 一般会在最前面,但是 right 不一定在最后,可以设置在 left 后面。

【`Last Update: 2024-11-07`】

### **Prefix Sum and Suffix Sum**
1. Prefix Sum: For an array nums, the prefix sum at each index i is the sum of all elements from the start of the array up to i. This allows you to find the sum of any subarray [i, j] in constant time by calculating prefix[j+1] - prefix[i].
2. Suffix Sum: For the same array nums, the suffix sum at index i is the sum of all elements from i to the end of the array. It enables efficient queries for sums of subarrays that start from any index i to a given end by using suffix[i] - suffix[j+1].

```
## Input [1, 2, 3, 4] -> Output [2x3x4, 1x3x4, 1x2x4, 1x2x3] = [24, 12, 8, 6]
## Predix -> [0, 1, 1x2, 1x2x3] = [0, 1, 2, 6]
## Suffix -> [2x3x4, 3x4, 4, 0] = [24, 12, 4, 0]

def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1] * len(nums)
prefix, suffix = 1, 1

for i in range(len(nums)):
res[i] = prefix
prefix *= nums[i]

for j in range(len(nums)-1,-1,-1):
res[j] *= suffix
suffix *= nums[j]

return res
```
【`Last Update: 2024-11-11`】

### Practice:
- [ ] Sorting and Searching:
- [Sort Colors - LeetCode 75](https://leetcode.com/problems/sort-colors/)
- [Search in Rotated Sorted Array - LeetCode 33](https://leetcode.com/problems/search-in-rotated-sorted-array/)
- [ ] Recursion and Backtracking:
- [Permutations - LeetCode 46](https://leetcode.com/problems/permutations/)
- [N-Queens - LeetCode 51](https://leetcode.com/problems/n-queens/)

## Advanced Algorithms
### **Overview**:
- **Dynamic Programming**: Explore the methodology of solving problems by breaking them down into smaller subproblems, storing results, and combining them to solve larger problems. Focus on understanding the concepts of overlapping subproblems and optimal substructure.
- **Greedy Algorithms**: Learn how greedy choices can lead to globally optimized solutions and their applications in problems like scheduling, graph based problems (like minimum spanning trees), and currency denomination.
- **Graph Algorithms**: Study shortest path algorithms (Dijkstra’s, Bellman-Ford) and minimum spanning tree algorithms (Prim’s, Kruskal’s). Understand their use cases and limitations.

### Notes:
-

### Practice:
- [ ] Dynamic Programming:
- [Coin Change - LeetCode 322](https://leetcode.com/problems/coin-change/)
- [Longest Increasing Subsequence - LeetCode 300](https://leetcode.com/problems/longest-increasing-subsequence/)
- [ ] Graph Algorithms:
- [Network Delay Time (Dijkstra's Algorithm) - LeetCode 743](https://leetcode.com/problems/network-delay-time/)

## **练习记录**
* `Date: 2024-11-06`:
* [LeetCode 1 - Two Sum](https://leetcode.com/problems/two-sum/)【Array】【Hash Table】
* `Date: 2024-11-07`:
* [LeetCode 15 - 3 Sum](https://leetcode.com/problems/3sum/)【Array】【Two Pointers】
* `Date: 2024-11-08`:
* [LeetCode 121 - Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)【Array】【Dynamic Programming】
* [LeetCode 349 - Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)【Array】【Hash Table】
* [LeetCode 219 - Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)【Array】【Hash Table】
* `Date: 2024-11-10`:
* [Leetcode 454 - 4Sum II](https://leetcode.com/problems/4sum-ii/description/)【Array】【Hash Table】
* `Date: 2024-11-11`:
* [Leetcode 53 - Maximum Subarray](https://leetcode.com/problems/maximum-subarray/description/)【Array】
* [Leetcode 238 - Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/description)【Array】【Prefix Sum】
* `Date: 2024-11-12`:
* [Leetcode 344 - Reverse String](https://leetcode.com/problems/reverse-string/description/)【String】【Two Pointers】
* [Leetcode 26 - Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)【Array】【Two Pointers】
* [Leetcode 27 - Remove Element](https://leetcode.com/problems/remove-element/description)【Array】【Two Pointers】
* `Date: 2024-11-13`:
* [Leetcode 3 - Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)【String】【Hash Table】
* [Leetcode 5 - Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/description/)【String】【Two Pointers】
* [Leetcode 28 - Find the Index of the First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/)【String】【Two Pointers】
* [Leetcode 49 - Group Anagrams](https://leetcode.com/problems/group-anagrams/description/)【String】【Hash Table】
* `Date: 2024-11-14`:
* [Leetcode 206 - Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/description/)【Linked List】【Recursion】
* `Date: 2024-11-15`:
* [Leetcode 21 - Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/)【Linked List】【Recursion】
* [Leetcode 141 - Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/description/)【Linked List】【Hash Table】
* [Leetcode 203 - Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/description/)【Linked List】【Recursion】
* [Leetcode 83 - Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/)【Linked List】
* [Leetcode 2 - Add Two Numbers](https://leetcode.com/problems/add-two-numbers/description)【Linked List】【Recursion】【Math】
* `Date: 2024-11-17`:
* [Leetcode 19 - Remove N-th Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/)【Linked List】【Two Pointers】
* [Leetcode 138 - Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/description/)【Linked List】【Hash Table】
* [Leetcode 234 - Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/description)【Linked List】
* [Leetcode 160 - Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/description/)【Linked List】【Hash Table】
* `Date: 2024-11-18`:
* [Leetcode 92 - Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/description/)【Linked List】
* [Leetcode 61 - Rotate List](https://leetcode.com/problems/rotate-list/description)【Linked List】【Two Pointers】
* `Date: 2024-11-19`:
* [Leetcode 20 - Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)【Stack】【String】
* `Date: 2024-11-21`:
* [Leetcode 155 - Min Stack](https://leetcode.com/problems/min-stack/description/)【Stack】
* [Leetcode 682 - Baseball Game](https://leetcode.com/problems/baseball-game/description/)【Stack】
* `Date: 2024-11-22`:
* [Leetcode 739 - Daily Temperatures](https://leetcode.com/problems/daily-temperatures/description/)【Stack】【Monotonic Stack】
* [Leetcode 232 - Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/description/)【Queue】【Stack】
* [Leetcode 225 - Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/description/)【Stack】【Queue】
* [Leetcode 622 - Design Circular Queue](https://leetcode.com/problems/design-circular-queue/description/)【Queue】
* `Date: 2024-11-24`:
* [Leetcode 933 - Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/description/)【Queue】
* `Date: 2024-11-25`:
* [Leetcode 239 - Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/description/)【Deque】【Sliding Window】
* [Leetcode 641 - Design Circular Deque](https://leetcode.com/problems/design-circular-deque/description/)【Deque】
* [Leetcode 215 - Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/description/)【Heap】
* [Leetcode 23 - Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/description/)【Heap】
* `Date: 2024-11-26`:
* [Leetcode 94 - Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/description/)【Tree】【Binary Tree】
* [Leetcode 144 - Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/description/)【Tree】【Binary Tree】
* [Leetcode 145 - Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/description/)【Tree】【Binary Tree】
* [Leetcode 104 - Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/)【Tree】【Binary Tree】【Depth-First Search】
* `Date: 2024-11-27`:
* [Leetcode 111 - Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/description/)【Tree】【Binary Tree】【Depth-First Search】
* [Leetcode 112 - Path Sum](https://leetcode.com/problems/path-sum/description/)【Tree】【Binary Tree】【Depth-First Search】
* [Leetcode 101 - Symmetric Tree](https://leetcode.com/problems/symmetric-tree/description/)【Tree】【Binary Tree】【Depth-First Search】
* `Date: 2024-11-28`:
* [Leetcode 98 - Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/description/)【Binary Search Tree】【Depth-First Search】
* `Date: 2024-12-04`:
* [Leetcode 226 - Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/description/)【Binary Search Tree】【Depth-First Search】
* `Date: 2024-12-05`:
* [Leetcode 235 - Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/)【Binary Search Tree】【Depth-First Search】
* [Leetcode 700 - Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/description/)【Binary Search Tree】

# **LeetCode Problems' Solutions**
## Cheet Sheet

Numbers

* **Python Arithmetic Operators**

| Operator | Example | Meaning |
| --- | --- | --- |
| `+` | 3 + 2 = 5 | Addition |
| `-` | 3 - 2 = 1 | Subtraction |
| `*` | 3 * 2 = 6 | Multiplication |
| `/` | 3 / 2 = 1.5 | Division |
| `%` | 3 % 2 = 1 | Modulus |
| `**` | 3 ** 2 = 9 | Exponentiation |
| `//` | 5 // 2 = 2 | Floor division |
| `math.sqrt()` | math.sqrt(4) = 2 | Square root |
| `math.inf` | x = math.inf | Infinity |

* **Python Bitwise Operators**

| Operator | Example | Meaning |
| --- | --- | --- |
| `&` | a & b | Bitwise AND |
| `|` | a | b | Bitwise OR |
| `^` | a ^ b | Bitwise XOR (exclusive OR) |
| `~` | ~a | Bitwise NOT |
| `<<` | a << n | Bitwise left shift |
| `>>` | a >> n | Bitwise right shift |

List

```python
List1 = [i for i in range(5)] # initialize list -> [0, 1, 2, 3, 4]
List2 = [0] * 5 # initialize list with 5 0's -> [0, 0, 0, 0, 0]
List1.append(-1) # -> [0, 1, 2, 3, 4, -1]
List1.sort() # -> [-1, 0, 1, 2, 3, 4]
List1.reverse() #-> [4, 3, 2, 1, 0, -1]
List3 = List1 + List2 # -> [4, 3, 2, 1, 0, -1, 0, 0, 0, 0, 0]
len(List3) # -> 11
List3.insert(11, 100) # -> [4, 3, 2, 1, 0, -1, 0, 0, 0, 0, 0, 100]
List3.pop() # -> [4, 3, 2, 1, 0, -1, 0, 0, 0, 0, 0]
List3.pop(1) # -> [4, 2, 1, 0, -1, 0, 0, 0, 0, 0]
List3.index(1) # -> 2
```

``` python
nums = [5, 4, 3, 2, 1]
nums.sort() # -> [1, 2, 3, 4, 5]
strings = ['Ford', 'BMW', 'Volvo']
strings.sort(key=lambda x: len(x) ) # -> ['BMW', 'Ford', 'Volvo']
lists = [[4,3], [5,5], [1,3]]
lists.sort(key=lambda x: x[0]) # -> [[1, 3], [4, 3], [5, 5]]
```

Dictionary

```python
d = {'key1': 'value1'} # Declare dict{'key1': 'value1'}
d['key2'] = 'value2' # Add Key and Value -> {'key1': 'value1', 'key2': 'value2'}
d['key1'] # Access value -> 'value1'
d.keys() # -> dict_keys(['key1', 'key2'])
d.values() # -> dict_values(['value1', 'value2'])
d.items() # -> dict_items([('key1', 'value1'), ('key2', 'value2')])
for k,v in d.items():
print(k, v) # key1 value1 key2 value2
d.pop('key1') # -> 'value1'
d # -> {'key2': 'value2'}
```

Strings

``` python
(ord("A"), ord("Z"), ord("a"), ord("z")) # (65, 90, 97, 122)
(chr(65), chr(90), chr(97), chr(122)) # ('A', 'Z', 'a', 'z')
"H/e/l/l/o".split("/") # ['H', 'e', 'l', 'l', 'o']
"/".join(['H', 'e', 'l', 'l', 'o']) # H/e/l/l/o
("a".upper(), "A".lower()) # ('A', 'a')
```

Collections

* **collections.Counter()**
``` python
from collections import Counter

hashmap = collections.Counter("hello") # Counter({'h': 1, 'e': 1, 'l': 2, 'o': 1})
hashmap['l'] # 2
```
* **collections.deque()**
``` python
from collections import deque

deq = collections.deque([1, 2, 3]) # deque([1, 2, 3])
deq.appendleft(5) # deque([5, 1, 2, 3])
deq.append(6) # deque([5, 1, 2, 3, 6])
deq.popleft() # -> 5
deq.pop() # -> 6
```

* **collections.defaultdict()**
``` python
from collections import defaultdict

s = 'mississippi'
d = collections.defaultdict(int) # defaultdict(int, {})
for k in s:
d[k] += 1
d # defaultdict(int, {'m': 1, 'i': 4, 's': 4, 'p': 2})
d.items() # dict_items([('m', 1), ('i', 4), ('s', 4), ('p', 2)])
```

``` python
from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list) # defaultdict(list, {})
for k, v in s:
d[k].append(v)
d # defaultdict(list, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
d.items() # dict_items([('yellow', [1, 3]), ('blue', [2, 4]), ('red', [1])])
```

* **collections.OrderedDict()**
``` python
from collections import OrderedDict

hashmap = collections.OrderedDict.fromkeys("hello")
# OrderedDict([('h', None), ('e', None), ('l', None), ('o', None)])
hashmap.popitem(last=True) # Returned in LIFO order if last is True -> ('o', None)
hashmap.popitem(last=False) # Returned in FIFO order if last is False -> ('h', None)
```

Stack

A **Stack** is a linear data structure that stores items in a **Last-In/First-Out (LIFO)** or **First-In/Last-Out (FILO)** manner. In stack, a new element is added at one end and an element is removed from that end only.

* `push(a)` – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
* `pop()` – Deletes the topmost element of the stack – Time Complexity: O(1)

```python
stack = []

stack.append('a') # append() function to push
stack.append('b') # element in the stack
stack.append('c') # -> ['a', 'b', 'c']

stack.pop() # -> 'c'
stack # -> ['a', 'b']
```

Queue

**Queue** is a linear data structure that stores items in **First In First Out (FIFO)** manner. With a queue the least recently added item is removed first.

* `Enqueue`: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity : O(1)
* `Dequeue`: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity : O(1)

```python
queue = []

queue.append('a') # append() function to push
queue.append('b') # element in the stack
queue.append('c') # -> ['a', 'b', 'c']

queue.pop(0) # -> 'a'
queue # -> ['b', 'c']
```
* **Queue using Deque**

```python
from collections import deque

queue = deque(["Ram", "Tarun", "Asif", "John"])
queue.append("Akbar") # -> deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])
queue.popleft() # -> 'Ram'
queue # -> deque(['Tarun', 'Asif', 'John', 'Akbar'])
```

Deque

**Deque** or **Double Ended Queue** is a type of queue in which insertion and removal of elements can either be performed from the front or the rear. Thus, it does not follow FIFO rule (First In First Out).

``` python
from collections import deque

deq = collections.deque([1, 2, 3]) # deque([1, 2, 3])
deq.appendleft(5) # deque([5, 1, 2, 3])
deq.append(6) # deque([5, 1, 2, 3, 6])
deq.popleft() # -> 5
deq.pop() # -> 6
```

Binary Tree



Graph

``` python
N = 6
edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
graph = [[] for _ in range(N)]
for u,v in edges:
graph[u].append(v)
graph[v].append(u)
graph # -> [[1, 2], [0], [0, 3, 4, 5], [2], [2], [2]]
```

Algorithms

* **Binary Search**
``` python
# Runtime complexity : O(log n)

def binary_search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1

while(left <= right):
center = (left + right) // 2
if nums[center] == target:
return center
elif nums[center] < target:
left = center + 1
else:
right = center - 1

return -1
```

## **Array**
* [11. Container With Most Water [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0011_Container_With_Most_Water.md)
* [31. Next Permutation [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0031_Next_Permutation.md) 🔥
* [42. Trapping Rain Water [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0042_Trapping_Rain_Water.md)
* [134. Gas Station [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0134_Gas_Station.md)
* [150. Evaluate Reverse Polish Notation [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0150_Evaluate_Reverse_Polish_Notation.md)

## **Backtracking**
* [39. Combination Sum [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Backtracking/0039_Combination_Sum.md)
* [46. Permutations [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Backtracking/0046_Permutations.md) 🔥
* [51. N-Queens [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Backtracking/0051_N-Queens.md)
* [79. Word Search [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Backtracking/0079_Word_Search.md)

## **Binary Search**
* [33. Search in Rotated Sorted Array [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Binary_Search/0033_Search_in_Rotated_Sorted_Array.md) 🔥
* [74. Search a 2D Matrix [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Binary_Search/0074_Search_a_2D_Matrix.md)
* [153. Find Minimum in Rotated Sorted Array [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Binary_Search/0153_Find_Minimum_in_Rotated_Sorted_Array.md)

## **Bit Manipulation**
* [89. Gray Code [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Bit_Manipulation/0089_Gray_Code.md)
* [191. Number of 1 Bits [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Bit_Manipulation/0191_Number_of_1_Bits.md)
* [461. Hamming Distance [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Bit_Manipulation/0461_Hamming_Distance.md) 🔥

## **Dynamic Programming**
* [22. Generate Parentheses [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Dynamic_Programming/0022_Generate_Parentheses.md) 🔥
* [45. Jump Game II [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Dynamic_Programming/0045_Jump_Game_II.md)
* [62. Unique Paths [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Dynamic_Programming/0062_Unique_Paths.md) 🔥
* [91. Decode Ways [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Dynamic_Programming/0091_Decode_Ways.md) 🔥
* [122. Best Time to Buy and Sell Stock II [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Dynamic_Programming/0122_Best_Time_to_Buy_and_Sell_Stock_II.md)

## **Graph**
* [133. Clone Graph [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Graph/0133_Clone_Graph.md)
* [138. Copy List with Random Pointer [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Graph/0138_Copy_List_with_Random_Pointer.md)
* [207. Course Schedule [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Graph/0207_Course_Schedule.md)

## **Linked List**
* [2. Add Two Numbers [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0002_Add_Two_Numbers.md)
* [21. Merge Two Sorted Lists [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0021_Merge_Two_Sorted_Lists.md)
* [23. Merge k Sorted Lists [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0023_Merge_k_Sorted_Lists.md) 🔥
* [24. Swap Nodes in Pairs [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0024_Swap_Nodes_in_Pairs.md)
* [86. Partition List [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0086_Partition_List.md)
* [143. Reorder List [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0143_Reorder_List.md)
* [146. LRU Cache [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0146_LRU_Cache.md) 🔥
* [148. Sort List [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0148_Sort_List.md)
* [206. Reverse Linked List [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0206_Reverse_Linked_List.md) 🔥
* [445. Add Two Numbers II [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0445_Add_Two_Numbers_II.md)

## **Math**
* [7. Reverse Integer [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Math/0007_Reverse_Integer.md)
* [149. Max Points on a Line [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Math/0149_Max_Points_on_a_Line.md)

## **Matrix**
* [36. Valid Sudoku [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Matrix/0036_Valid_Sudoku.md)
* [48. Rotate Image [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Matrix/0048_Rotate_Image.md) 🔥

## **Sorting**
* [15. 3Sum [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0015_3Sum.md)
* [16. 3Sum Closest [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0016_3Sum_Closest.md)
* [56. Merge Intervals [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0056_Merge_Intervals.md) 🔥
* [75. Sort Colors [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0075_Sort_Colors.md) 🔥
* [169. Majority Element [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0169_Majority_Element.md)

## **String**
* [3. Longest Substring Without Repeating Characters [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0003_Longest_Substring_Without_Repeating_Characters.md)
* [5. Longest Palindromic Substring [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0005_Longest_Palindromic_Substring.md) 🔥
* [68. Text Justification [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0068_Text_Justification.md)
* [71. Simplify Path [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0071_Simplify_Path.md) 🔥
* [76. Minimum Window Substring [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0076_Minimum_Window_Substring.md) 🔥
* [139. Word Break [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0139_Word_Break.md)

## **Tree**
* [94. Binary Tree Inorder Traversal [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0094_Binary_Tree_Inorder_Traversal.md) 🔥
* [95. Unique Binary Search Trees II [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0095_Unique_Binary_Search_Trees_II.md) 🔥
* [98. Validate Binary Search Tree [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0098_Validate_Binary_Search_Tree.md)
* [105. Construct Binary Tree from Preorder and Inorder Traversal [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.md)
* [109. Convert Sorted List to Binary Search Tree [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0109_Convert_Sorted_List_to_Binary_Search_Tree.md) 🔥
* [114. Flatten Binary Tree to Linked List [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0114_Flatten_Binary_Tree_to_Linked_List.md)
* [116. Populating Next Right Pointers in Each Node [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0116_Populating_Next_Right_Pointers_in_Each_Node.md)
* [124. Binary Tree Maximum Path Sum [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0124_Binary_Tree_Maximum_Path_Sum.md) 🔥

## **To-do List**
* [10. Regular Expression Matching [Hard]](https://leetcode.com/problems/regular-expression-matching/)
* [25. Reverse Nodes in k-Group [Hard]](https://leetcode.com/problems/reverse-nodes-in-k-group/)
* [44. Wildcard Matching [Hard]](https://leetcode.com/problems/wildcard-matching/)
* [84. Largest Rectangle in Histogram [Hard]](https://leetcode.com/problems/largest-rectangle-in-histogram/)
* [115. Distinct Subsequences [Hard]](https://leetcode.com/problems/distinct-subsequences/)
* [126. Word Ladder II [Hard]](https://leetcode.com/problems/word-ladder-ii/)
* [132. Palindrome Partitioning II [Hard]](https://leetcode.com/problems/palindrome-partitioning-ii/)