{"id":27093607,"url":"https://github.com/followb1ind1y/leetcode","last_synced_at":"2025-04-06T08:38:43.518Z","repository":{"id":171745618,"uuid":"558029075","full_name":"Followb1ind1y/LeetCode","owner":"Followb1ind1y","description":"LeetCode Problems' Python Solutions with Chinese Explanation. LeetCode 问题的 Python 解答和中文理解","archived":false,"fork":false,"pushed_at":"2024-12-04T16:02:19.000Z","size":520,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-12-04T17:19:19.818Z","etag":null,"topics":["algorithms","leetcode","leetcode-python","leetcode-solutions","python"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Followb1ind1y.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-10-26T19:03:28.000Z","updated_at":"2024-12-04T16:02:33.000Z","dependencies_parsed_at":null,"dependency_job_id":"93bffdbb-8f04-4442-b7cb-53118494cffe","html_url":"https://github.com/Followb1ind1y/LeetCode","commit_stats":null,"previous_names":["followb1ind1y/leetcode"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Followb1ind1y%2FLeetCode","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Followb1ind1y%2FLeetCode/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Followb1ind1y%2FLeetCode/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Followb1ind1y%2FLeetCode/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Followb1ind1y","download_url":"https://codeload.github.com/Followb1ind1y/LeetCode/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247457729,"owners_count":20941905,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithms","leetcode","leetcode-python","leetcode-solutions","python"],"created_at":"2025-04-06T08:38:42.869Z","updated_at":"2025-04-06T08:38:43.509Z","avatar_url":"https://github.com/Followb1ind1y.png","language":null,"readme":"\u003cp align=\"center\"\u003e\n\u003ca href=\"https://github.com/Followb1ind1y\"\u003e\u003cimg src=\"https://img.shields.io/static/v1?logo=github\u0026label=maintainer\u0026message=Followb1ind1y\u0026color=eb5334\" alt=\"Last Commit\"/\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/Followb1ind1y/LeetCode/graphs/commit-activity\"\u003e\u003cimg src=\"https://img.shields.io/github/last-commit/Followb1ind1y/LeetCode.svg?colorB=eb9f34\u0026style=flat\" alt=\"Last Commit\"/\u003e \u003c/a\u003e\n\u003cimg src=\"https://img.shields.io/github/repo-size/Followb1ind1y/LeetCode.svg?colorB=34ebae\u0026style=flat\" alt=\"Size\"/\u003e\n\u003cimg src=\"https://img.shields.io/github/languages/top/Followb1ind1y/LeetCode.svg?colorB=9f34eb\u0026style=flat\" alt=\"Language\"/\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://mybinder.org/v2/gh/Followb1ind1y/LeetCode/HEAD\"\u003e\u003cimg src=\"https://img.shields.io/badge/Open in-binder-579aca.svg?logo=data:image/png;base64,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\" alt=\"binder\"/\u003e\u003c/a\u003e     \n\u003ca href=\"https://githubtocolab.com/Followb1ind1y/LeetCode\"\u003e\u003cimg src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"colab\"/\u003e\u003c/a\u003e       \n\u003c/p\u003e\n\n# Leetcode Interview Preparation Plan\n\n- [Leetcode Interview Preparation Plan](#leetcode-interview-preparation-plan)\n  * [Basic Data Structures](#basic-data-structures)\n    + [Arrays](#arrays)\n    + [Strings](#strings)\n    + [Linked Lists](#linked-lists)\n    + [Stack](#stack)\n    + [Queue](#queue)\n    + [Deque](#deque)\n  * [Advanced Data Structures](#advanced-data-structures)\n    + [Heap](#heap)\n    + [Tree](#tree)\n    + [Hash Tables](#hash-tables)\n  * [Core Algorithms](#core-algorithms)\n    + [Overview](#overview-2)\n    + [Two Pointer](#two-pointer)\n    + [Prefix Sum and Suffix Sum](#prefix-sum-and-suffix-sum)\n    + [Practice](#practice-1)\n  * [Advanced Algorithms](#advanced-algorithms)\n    + [Overview](#overview-3)\n    + [Notes](#notes)\n    + [Practice](#practice-2)\n  * [练习记录](#练习记录)\n\n## Basic Data Structures\n\n### **Arrays**\nIn 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. \n\n【`Last Update: 2024-08-14`】\n```\narr = []          # O(1)\narr = [1, 2, 3]   # O(n), where n is the number of elements\nfirst_element = arr[0]  # O(1)\narr[1] = 10  # O(1)\narr.append(6)  # O(1) on average for appending\narr.insert(2, 15)  # O(n), where n is the number of elements after the insertion index\narr.remove(15)  # O(n), where n is the number of elements in the list [remove the first 15 in the array]\ndel arr[2]  # O(n), where n is the number of elements after the deleted index\nlast_element = arr.pop()  # O(1)\narr.sort()  # 原地排序\nsorted_arr = sorted(arr)  # 返回排序后的数组\narr[::-1] # arr 倒序\n```\n```\n## Counter() 的常用语法和使用情况\nfrom collections import Counter\narr = [1, 2, 2, 3, 3, 3]\ncounts = Counter(arr)  # 结果：Counter({3: 3, 2: 2, 1: 1})\n\n## 找到出现次数最多的元素\nmost_common_element = counts.most_common(1)[0]  # 结果：(3, 3)\n\n## 判断出现的元素是否相同\narr1 = [1, 2, 3]\narr2 = [3, 2, 1]\nis_anagram = Counter(arr1) == Counter(arr2)  # 结果：True\n```\n```\n## set() 的常用语法和使用情况\narr = [1, 2, 2, 3, 4, 4]\n\n## 快速查找\nseen = set(arr)\nif 3 in seen:\n    print(\"3 is in array\")\n\n## 去重\nunique_elements = list(set(arr))  # 结果：[1, 2, 3, 4]\n\n## 两个数组的交集\narr1 = [1, 2, 2, 3]\narr2 = [2, 3, 4]\nintersection = list(set(arr1) \u0026 set(arr2))  # 结果：[2, 3]\n```\n### **Strings**\nStrings in Python are immutable sequences of characters. You can perform various operations on strings using built-in methods and operators.\n\n【`Last Update: 2024-08-14`】\n```\ns = \"Hello, World!\"  # O(n), where n is the length of the string\nfirst_char = s[0]  # O(1)\nsubstring = s[7:12]  # O(k), where k is the length of the substring\ncombined = s + \" Python\"  # O(n + m), where n and m are the lengths of the two strings\nrepeated = s * 2  # O(n * k), where k is the number of repetitions\n\nupper_s = s.upper()  # O(n), where n is the length of the string\nlower_s = s.lower()  # O(n), where n is the length of the string\nstarts_with_hello = s.startswith(\"Hello\")  # O(n), where n is the length of the prefix\ncontains_world = \"World\" in s  # O(n * m), where n is the length of the string and m is the length of the substring\nreplaced_s = s.replace(\"World\", \"Python\")  # O(n * m), where n is the length of the string and m is the length of the substring\n\nwords = s.split(\", \")  # O(n), where n is the length of the string\njoined = \" - \".join(words)  # O(n), where n is the total length of the resulting string\n```\n\n### **Linked Lists**\nA Linked List is a linear data structure consisting of nodes, where each node contains:\n\n  * A data part that stores the actual data.\n  * A next part (or pointer) that points to the next node in the list.\n\n【`Last Update: 2024-11-14`】\n\n```\n## A node in a linked list can be represented as a class\n\nclass ListNode:\n    def __init__(self, data=0, next=None):\n        self.data = data  # Data of the node\n        self.next = next  # Pointer to the next node\n```\n```\n##  Inserting Nodes\n\ndef insert_at_beginning(head, data):\n    new_node = ListNode(data)  # Create a new node\n    new_node.next = head       # Link the new node to the current head\n    return new_node            # New node becomes the head\n```\n```\n## Deleting Nodes\n\ndef delete_from_beginning(head):\n    if not head:\n        return None\n    return head.next  # The second node becomes the new head\n```\n```\n## Searching for a Node\n\ndef search(head, key):\n    current = head\n    while current:\n        if current.data == key:\n            return True  # Found the data\n        current = current.next\n    return False  # Data not found\n```\n\n### **Stack**\nA 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.\n\n  * `push(a)` – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)\n  * `pop()` – Deletes the topmost element of the stack – Time Complexity: O(1)\n  * `Peek` - View the top element without removing it.\n  * `Empty` - Check if the stack is empty.\n\n【`Last Update: 2024-11-19`】\n\n```\nstack = []\n\n# Push elements onto the stack\nstack.append(1)\nstack.append(2)\n\n# Pop element from the stack\ntop = stack.pop()  # Removes and returns 2\n\n# Peek the top element\ntop = stack[-1] if stack else None  # Returns 1\n\n# Check if the stack is empty\nis_empty = len(stack) == 0\n```\n\n### **Queue**\nQueue 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. \n\n  * `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)\n  * `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)\n  * `Peek`: View the front element without removing it.\n  * `Empty`: Check if the queue is empty.\n\n【`Last Update: 2024-11-19`】\n\n```\nfrom collections import deque\n\n# Initialize a queue\nqueue = deque()\n\n# Enqueue elements\nqueue.append(1)\nqueue.append(2)\n\n# Dequeue element\nfront = queue.popleft()  # Removes and returns 1\n\n# Peek at the front element\nfront = queue[0] if queue else None\n\n# Check if the queue is empty\nis_empty = len(queue) == 0\n```\n\n### **Deque**\nA 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.\n\n【`Last Update: 2024-11-25`】\n\n```\nfrom collections import deque\n\n# Initialize a deque\ndq = deque()\n\n# Add elements\ndq.append(1)       # Add to the right\ndq.appendleft(2)   # Add to the left\n\n# Remove elements\ndq.pop()           # Remove from the right\ndq.popleft()       # Remove from the left\n\n# Access and manipulation\ndq.extend([3, 4])          # Add multiple elements to the right\ndq.extendleft([0, -1])     # Add multiple elements to the left (reversed order)\ndq.rotate(1)               # Rotate elements right\ndq.rotate(-1)              # Rotate elements left\ndq.clear()                 # Clear all elements\n```\n\n## Advanced Data Structures\n### **Overview**\n- **Trees**: Explore the concepts of binary trees, binary search trees, AVL trees, and tree traversals (in-order, pre-order, post-order, level-order).\n- **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.\n- **Hash Tables**: Study how hash tables work, including hashing functions, handling collisions, and applications in tasks like item counting or implementing dictionaries.\n\n### **Heap**\nA 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.\n\n  * Two main types:\n    * Min-Heap: The root node is the smallest, and every parent node is smaller than or equal to its children.\n    * Max-Heap: The root node is the largest, and every parent node is larger than or equal to its children.\n  * Root Node Access: \n    * Min-Heap: Root is the smallest element\n    * Max-Heap: Root is the largest element.\n  * Efficient Operations:\n    * Insert and delete both take O(log n).\n    * Maintains heap properties using adjustments (upward or downward shifts).\n\n\n【`Last Update: 2024-11-25`】\n\n```\nimport heapq\n\n# Initialize a heap\nheap = []\n\n# Add elements\nheapq.heappush(heap, 3)  # Push element into the heap\nheapq.heappush(heap, 1)\nheapq.heappush(heap, 4)\n\n# Access the smallest element\nsmallest = heap[0]\n\n# Remove elements\nmin_element = heapq.heappop(heap)  # Pop the smallest element\n\n# Heapify an existing list\nnums = [4, 1, 7, 3]\nheapq.heapify(nums)\n\n# Get n largest or smallest elements\nlargest = heapq.nlargest(2, nums)\nsmallest = heapq.nsmallest(2, nums)\n```\n\n### **Tree**\nA 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.\n\n  * **Binary Tree**: Each node has at most two children.\n  * **Binary Search Tree (BST)**: A binary tree where the left child contains values less than the parent, and the right child contains values greater.\n  * **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).\n  * **Tree Traversals**:\n    * Preorder Traversal (Root, Left, Right)\n    * Inorder Traversal (Left, Root, Right)\n    * Postorder Traversal (Left, Right, Root)\n\n```\n## Trees are often represented using classes. \n\nclass TreeNode:\n    def __init__(self, val=0, left=None, right=None):\n        self.val = val\n        self.left = left\n        self.right = right\n```\n\n  \u003cp align=\"center\"\u003e\n  \u003cimg src=\"Tree/img/LeetCode0094_Preorder-from-Inorder-and-Postorder-traversals.jpg\" width=\"500\"\u003e\n  \u003c/p\u003e\n\n```\n## Preorder Traversal (Root, Left, Right)\ndef preorder_traversal(root):\n    if root:\n        print(root.val)\n        preorder_traversal(root.left)\n        preorder_traversal(root.right)\n\n## Inorder Traversal (Left, Root, Right)\ndef inorder_traversal(root):\n    if root:\n        inorder_traversal(root.left)\n        print(root.val)\n        inorder_traversal(root.right)\n\n## Postorder Traversal (Left, Right, Root)\ndef postorder_traversal(root):\n    if root:\n        postorder_traversal(root.left)\n        postorder_traversal(root.right)\n        print(root.val)\n```\n\n```\n## Binary Search Tree (BST) Operations\n\n## 1. Insert a Node\ndef insert_into_bst(root, val):\n    if not root:\n        return TreeNode(val)\n    if val \u003c root.val:\n        root.left = insert_into_bst(root.left, val)\n    else:\n        root.right = insert_into_bst(root.right, val)\n    return root\n\n## \t2. Search for a Value\ndef search_bst(root, val):\n    if not root or root.val == val:\n        return root\n    if val \u003c root.val:\n        return search_bst(root.left, val)\n    return search_bst(root.right, val)\n\n## \t3. Delete a Node\ndef delete_node(root, key):\n    if not root:\n        return None\n    if key \u003c root.val:\n        root.left = delete_node(root.left, key)\n    elif key \u003e root.val:\n        root.right = delete_node(root.right, key)\n    else:\n        if not root.left:\n            return root.right\n        if not root.right:\n            return root.left\n        min_larger_node = root.right\n        while min_larger_node.left:\n            min_larger_node = min_larger_node.left\n        root.val = min_larger_node.val\n        root.right = delete_node(root.right, root.val)\n    return root\n```\n\n### **Hash Tables**\nIn 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.\n\n【`Last Update: 2024-11-06`】\n\n```\nmy_dict = {}  # Creating an empty dictionary\nmy_dict = {'key1': 'value1', 'key2': 'value2'}  # Creating a dictionary with initial values\nvalue = my_dict['key1']   # Accessing a value by key\nmy_dict['key3'] = 'value3'  # Adding a new key-value pair\nmy_dict['key2'] = 'new_value2'  # Updating an existing key-value pair\ndel my_dict['key1']   # Removing an entry by key\nvalue = my_dict.pop('key2')  # Popping an entry (removes and returns the value)\nexists = 'key3' in my_dict  # # Checking if a key is in the dictionary [True]\n\nfor key in my_dict:\n    print(key, my_dict[key]) # Iterating through keys\nfor key, value in my_dict.items(): # Iterating through key-value pairs\n    print(key, value)\nfor value in my_dict.values(): # Iterating through values\n    print(value)\n```\n\n```\n# defaultdict 使用方法，没见过的元素不会报错。适用于计数、分组和嵌套字典等应用。\n\nfrom collections import defaultdict\n\n# 使用 int 类型的 defaultdict\ndd = defaultdict(int)\nprint(dd['missing_key'])  # 输出：0，因为 int() 的默认值是 0\nprint(dd)  # 输出：defaultdict(\u003cclass 'int'\u003e, {'missing_key': 0})\n\n# 统计元素出现次数\ndata = \"abracadabra\"\ncounter = defaultdict(int)\nfor char in data:\n    counter[char] += 1\nprint(counter)  # 输出：defaultdict(\u003cclass 'int'\u003e, {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})\n\n# defaultdict(list)常用于将多个值归类到同一个键下。\ndata = [(\"apple\", 1), (\"banana\", 2), (\"apple\", 3), (\"banana\", 4)]\ngrouped_data = defaultdict(list)\nfor fruit, count in data:\n    grouped_data[fruit].append(count)\nprint(grouped_data)  # 输出：defaultdict(\u003cclass 'list'\u003e, {'apple': [1, 3], 'banana': [2, 4]})\n\n# 可以使用dict()将defaultdict转换为普通字典。\ndd = defaultdict(int)\ndd['a'] += 1\nprint(dict(dd))  # 输出：{'a': 1}\n\n```\n\n### Practice:\n- [ ] Trees:\n  - [Binary Tree Inorder Traversal - LeetCode 94](https://leetcode.com/problems/binary-tree-inorder-traversal/)\n  - [Lowest Common Ancestor of a Binary Search Tree - LeetCode 235](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)\n- [ ] Graphs:\n  - [Number of Islands - LeetCode 200](https://leetcode.com/problems/number-of-islands/)\n  - [Course Schedule - LeetCode 207](https://leetcode.com/problems/course-schedule/)\n- [ ] Hash Tables:\n  - [Group Anagrams - LeetCode 49](https://leetcode.com/problems/group-anagrams/)\n  - [Longest Consecutive Sequence - LeetCode 128](https://leetcode.com/problems/longest-consecutive-sequence/)\n\n## Core Algorithms\n### **Overview**\n- **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. \n- **Sorting Algorithms**: Review the mechanisms and use cases for quicksort, mergesort, and heapsort. Understand the trade-offs in terms of time and space complexity.\n- **Search Algorithms**: Study binary search on sorted arrays, and learn about its variations for finding the first or last position of an element.\n- **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.\n- **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.\n\n### **Two Pointer**\n  * Finding Pairs with a Given Sum: When looking for two numbers in a sorted array that add up to a specific target.\n  * Reversing a String or Array: Using two pointers to swap elements from the start and end until they meet in the middle.\n  * Merging Two Sorted Arrays: Traversing both arrays simultaneously to create a new sorted array.\n  * Removing Duplicates from a Sorted Array: Using two pointers to track unique elements.\n  * 设置 two pointers 的时候，left 一般会在最前面，但是 right 不一定在最后，可以设置在 left 后面。\n\n【`Last Update: 2024-11-07`】\n\n### **Prefix Sum and Suffix Sum**\n\t1.\tPrefix 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].\n\t2.\tSuffix 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].\n\n```\n## Input [1, 2, 3, 4] -\u003e Output [2x3x4, 1x3x4, 1x2x4, 1x2x3] = [24, 12, 8, 6]\n## Predix -\u003e [0, 1, 1x2, 1x2x3] = [0, 1, 2, 6]\n## Suffix -\u003e [2x3x4, 3x4, 4, 0] = [24, 12, 4, 0]\n\ndef productExceptSelf(self, nums: List[int]) -\u003e List[int]:\n  res = [1] * len(nums)\n  prefix, suffix = 1, 1\n\n  for i in range(len(nums)):\n    res[i] = prefix\n    prefix *= nums[i]\n\n  for j in range(len(nums)-1,-1,-1):\n    res[j] *= suffix\n    suffix *= nums[j]\n        \n  return res\n```\n【`Last Update: 2024-11-11`】\n\n### Practice:\n- [ ] Sorting and Searching:\n  - [Sort Colors - LeetCode 75](https://leetcode.com/problems/sort-colors/)\n  - [Search in Rotated Sorted Array - LeetCode 33](https://leetcode.com/problems/search-in-rotated-sorted-array/)\n- [ ] Recursion and Backtracking:\n  - [Permutations - LeetCode 46](https://leetcode.com/problems/permutations/)\n  - [N-Queens - LeetCode 51](https://leetcode.com/problems/n-queens/)\n\n## Advanced Algorithms\n### **Overview**:\n- **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.\n- **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.\n- **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.\n\n### Notes:\n-\n\n### Practice:\n- [ ] Dynamic Programming:\n  - [Coin Change - LeetCode 322](https://leetcode.com/problems/coin-change/)\n  - [Longest Increasing Subsequence - LeetCode 300](https://leetcode.com/problems/longest-increasing-subsequence/)\n- [ ] Graph Algorithms:\n  - [Network Delay Time (Dijkstra's Algorithm) - LeetCode 743](https://leetcode.com/problems/network-delay-time/)\n\n## **练习记录**\n* `Date: 2024-11-06`:\n  * [LeetCode 1 - Two Sum](https://leetcode.com/problems/two-sum/)【Array】【Hash Table】\n* `Date: 2024-11-07`:\n  * [LeetCode 15 - 3 Sum](https://leetcode.com/problems/3sum/)【Array】【Two Pointers】\n* `Date: 2024-11-08`:\n  * [LeetCode 121 - Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)【Array】【Dynamic Programming】\n  * [LeetCode 349 - Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)【Array】【Hash Table】\n  * [LeetCode 219 - Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)【Array】【Hash Table】\n* `Date: 2024-11-10`:\n  * [Leetcode 454 - 4Sum II](https://leetcode.com/problems/4sum-ii/description/)【Array】【Hash Table】\n* `Date: 2024-11-11`:\n  * [Leetcode 53 - Maximum Subarray](https://leetcode.com/problems/maximum-subarray/description/)【Array】\n  * [Leetcode 238 - Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/description)【Array】【Prefix Sum】\n* `Date: 2024-11-12`:\n  * [Leetcode 344 - Reverse String](https://leetcode.com/problems/reverse-string/description/)【String】【Two Pointers】\n  * [Leetcode 26 - Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)【Array】【Two Pointers】\n  * [Leetcode 27 - Remove Element](https://leetcode.com/problems/remove-element/description)【Array】【Two Pointers】\n* `Date: 2024-11-13`:\n  * [Leetcode 3 - Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)【String】【Hash Table】\n  * [Leetcode 5 - Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/description/)【String】【Two Pointers】\n  * [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】\n  * [Leetcode 49 - Group Anagrams](https://leetcode.com/problems/group-anagrams/description/)【String】【Hash Table】\n* `Date: 2024-11-14`:\n  * [Leetcode 206 - Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/description/)【Linked List】【Recursion】\n* `Date: 2024-11-15`:\n  * [Leetcode 21 - Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/)【Linked List】【Recursion】\n  * [Leetcode 141 - Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/description/)【Linked List】【Hash Table】\n  * [Leetcode 203 - Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/description/)【Linked List】【Recursion】\n  * [Leetcode 83 - Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/)【Linked List】\n  * [Leetcode 2 - Add Two Numbers](https://leetcode.com/problems/add-two-numbers/description)【Linked List】【Recursion】【Math】\n* `Date: 2024-11-17`:\n  * [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】\n  * [Leetcode 138 - Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/description/)【Linked List】【Hash Table】\n  * [Leetcode 234 - Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/description)【Linked List】\n  * [Leetcode 160 -  Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/description/)【Linked List】【Hash Table】\n* `Date: 2024-11-18`:\n  * [Leetcode 92 - Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/description/)【Linked List】\n  * [Leetcode 61 - Rotate List](https://leetcode.com/problems/rotate-list/description)【Linked List】【Two Pointers】\n* `Date: 2024-11-19`:\n  * [Leetcode 20 - Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)【Stack】【String】\n* `Date: 2024-11-21`:\n  * [Leetcode 155 - Min Stack](https://leetcode.com/problems/min-stack/description/)【Stack】\n  * [Leetcode 682 - Baseball Game](https://leetcode.com/problems/baseball-game/description/)【Stack】\n* `Date: 2024-11-22`:\n  * [Leetcode 739 - Daily Temperatures](https://leetcode.com/problems/daily-temperatures/description/)【Stack】【Monotonic Stack】\n  * [Leetcode 232 - Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/description/)【Queue】【Stack】\n  * [Leetcode 225 - Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/description/)【Stack】【Queue】\n  * [Leetcode 622 - Design Circular Queue](https://leetcode.com/problems/design-circular-queue/description/)【Queue】\n* `Date: 2024-11-24`:\n  * [Leetcode 933 - Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/description/)【Queue】\n* `Date: 2024-11-25`:\n  * [Leetcode 239 - Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/description/)【Deque】【Sliding Window】\n  * [Leetcode 641 - Design Circular Deque](https://leetcode.com/problems/design-circular-deque/description/)【Deque】\n  * [Leetcode 215 - Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/description/)【Heap】\n  * [Leetcode 23 - Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/description/)【Heap】\n* `Date: 2024-11-26`:\n  * [Leetcode 94 - Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/description/)【Tree】【Binary Tree】\n  * [Leetcode 144 - Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/description/)【Tree】【Binary Tree】\n  * [Leetcode 145 - Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/description/)【Tree】【Binary Tree】\n  * [Leetcode 104 - Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/)【Tree】【Binary Tree】【Depth-First Search】\n* `Date: 2024-11-27`:\n  * [Leetcode 111 - Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/description/)【Tree】【Binary Tree】【Depth-First Search】\n  * [Leetcode 112 - Path Sum](https://leetcode.com/problems/path-sum/description/)【Tree】【Binary Tree】【Depth-First Search】\n  * [Leetcode 101 - Symmetric Tree](https://leetcode.com/problems/symmetric-tree/description/)【Tree】【Binary Tree】【Depth-First Search】\n* `Date: 2024-11-28`:\n  * [Leetcode 98 - Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/description/)【Binary Search Tree】【Depth-First Search】\n* `Date: 2024-12-04`:\n  * [Leetcode 226 - Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/description/)【Binary Search Tree】【Depth-First Search】\n* `Date: 2024-12-05`:\n  * [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】\n  * [Leetcode 700 - Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/description/)【Binary Search Tree】\n\n# **LeetCode Problems' Solutions**\n## Cheet Sheet\n\u003cdetails\u003e\n\u003csummary\u003eNumbers\u003c/summary\u003e\n\n  * **Python Arithmetic Operators**\n\n  | Operator | Example |  Meaning |\n  | --- | --- | --- |\n  | `+` | 3 + 2 = 5 | Addition |\n  | `-` |\t3 - 2 = 1 | Subtraction |\n  | `*` |\t3 * 2 = 6 |\tMultiplication |\n  | `/` |\t3 / 2 = 1.5 | Division |\n  | `%` |\t3 % 2 = 1 | Modulus |\n  | `**` | 3 ** 2 = 9 | Exponentiation |\n  | `//` | 5 // 2 = 2 | Floor division |\n  | `math.sqrt()` | math.sqrt(4) = 2 | Square root |\n  | `math.inf` | x = math.inf | Infinity |\n\n  * **Python Bitwise Operators**\n\n  | Operator | Example |  Meaning |\n  | --- | --- | --- |\n  | `\u0026` | a \u0026 b | Bitwise AND |\n  | `｜` |\ta ｜ b |\tBitwise OR |\n  | `^` |\ta ^ b |\tBitwise XOR (exclusive OR) |\n  | `~` |\t~a |\tBitwise NOT |\n  | `\u003c\u003c` |\ta \u003c\u003c n |\tBitwise left shift |\n  | `\u003e\u003e` |\ta \u003e\u003e n |\tBitwise right shift |\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eList\u003c/summary\u003e\n\n```python\nList1 = [i for i in range(5)] # initialize list -\u003e [0, 1, 2, 3, 4]\nList2 = [0] * 5 # initialize list with 5 0's -\u003e [0, 0, 0, 0, 0]\nList1.append(-1) # -\u003e [0, 1, 2, 3, 4, -1]\nList1.sort() # -\u003e [-1, 0, 1, 2, 3, 4]\nList1.reverse() #-\u003e [4, 3, 2, 1, 0, -1]\nList3 = List1 + List2 # -\u003e [4, 3, 2, 1, 0, -1, 0, 0, 0, 0, 0]\nlen(List3) # -\u003e 11\nList3.insert(11, 100) # -\u003e [4, 3, 2, 1, 0, -1, 0, 0, 0, 0, 0, 100]\nList3.pop() # -\u003e [4, 3, 2, 1, 0, -1, 0, 0, 0, 0, 0]\nList3.pop(1) # -\u003e [4, 2, 1, 0, -1, 0, 0, 0, 0, 0]\nList3.index(1) # -\u003e 2\n```\n\n``` python\nnums = [5, 4, 3, 2, 1]\nnums.sort() # -\u003e [1, 2, 3, 4, 5]\nstrings = ['Ford', 'BMW', 'Volvo']\nstrings.sort(key=lambda x: len(x) ) # -\u003e ['BMW', 'Ford', 'Volvo']\nlists = [[4,3], [5,5], [1,3]]\nlists.sort(key=lambda x: x[0]) # -\u003e [[1, 3], [4, 3], [5, 5]]\n```\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eDictionary\u003c/summary\u003e\n\n```python\nd = {'key1': 'value1'} # Declare dict{'key1': 'value1'}\nd['key2'] = 'value2' # Add Key and Value -\u003e {'key1': 'value1', 'key2': 'value2'}\nd['key1'] # Access value -\u003e 'value1'\nd.keys() # -\u003e dict_keys(['key1', 'key2'])\nd.values() # -\u003e dict_values(['value1', 'value2'])\nd.items() # -\u003e dict_items([('key1', 'value1'), ('key2', 'value2')])\nfor k,v in d.items(): \n    print(k, v) # key1 value1 key2 value2\nd.pop('key1') # -\u003e 'value1'\nd # -\u003e {'key2': 'value2'}\n```\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eStrings\u003c/summary\u003e\n\n``` python\n(ord(\"A\"), ord(\"Z\"), ord(\"a\"), ord(\"z\")) # (65, 90, 97, 122)\n(chr(65), chr(90), chr(97), chr(122)) # ('A', 'Z', 'a', 'z')\n\"H/e/l/l/o\".split(\"/\") # ['H', 'e', 'l', 'l', 'o']\n\"/\".join(['H', 'e', 'l', 'l', 'o']) # H/e/l/l/o\n(\"a\".upper(), \"A\".lower()) # ('A', 'a')\n```\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eCollections\u003c/summary\u003e\n\n* **collections.Counter()**\n``` python\nfrom collections import Counter\n\nhashmap = collections.Counter(\"hello\") # Counter({'h': 1, 'e': 1, 'l': 2, 'o': 1})\nhashmap['l'] # 2\n```\n* **collections.deque()**\n``` python\nfrom collections import deque\n\ndeq = collections.deque([1, 2, 3]) # deque([1, 2, 3])\ndeq.appendleft(5) # deque([5, 1, 2, 3])\ndeq.append(6) # deque([5, 1, 2, 3, 6])\ndeq.popleft() # -\u003e 5\ndeq.pop() # -\u003e 6\n```\n\n* **collections.defaultdict()**\n``` python\nfrom collections import defaultdict\n\ns = 'mississippi'\nd = collections.defaultdict(int) # defaultdict(int, {})\nfor k in s:\n    d[k] += 1\nd # defaultdict(int, {'m': 1, 'i': 4, 's': 4, 'p': 2})\nd.items() # dict_items([('m', 1), ('i', 4), ('s', 4), ('p', 2)])\n```\n\n``` python\nfrom collections import defaultdict\n\ns = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]\nd = collections.defaultdict(list) # defaultdict(list, {})\nfor k, v in s:\n    d[k].append(v)\nd # defaultdict(list, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})\nd.items() # dict_items([('yellow', [1, 3]), ('blue', [2, 4]), ('red', [1])])\n```\n\n* **collections.OrderedDict()**\n``` python\nfrom collections import OrderedDict\n\nhashmap = collections.OrderedDict.fromkeys(\"hello\") \n# OrderedDict([('h', None), ('e', None), ('l', None), ('o', None)])\nhashmap.popitem(last=True) # Returned in LIFO order if last is True -\u003e ('o', None)\nhashmap.popitem(last=False) # Returned in FIFO order if last is False -\u003e ('h', None)\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eStack\u003c/summary\u003e\n\nA **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.\n\n* `push(a)` – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)\n* `pop()` – Deletes the topmost element of the stack – Time Complexity: O(1)\n\n\u003ccenter\u003e\u003cimg src=\"https://drive.google.com/uc?export=view\u0026id=12cKEW2XKl7tfO5ZH4FZ9-4TlFh3ST7ek\" width=450px /\u003e\u003c/center\u003e\n\n```python\nstack = []\n\nstack.append('a') # append() function to push\nstack.append('b') # element in the stack\nstack.append('c') # -\u003e ['a', 'b', 'c']\n\nstack.pop() # -\u003e 'c'\nstack # -\u003e ['a', 'b']\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eQueue\u003c/summary\u003e\n\n**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. \n\n* `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)\n* `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)\n\n\u003ccenter\u003e\u003cimg src=\"https://drive.google.com/uc?export=view\u0026id=1QAw5MSmH_1DzY2wSKte6bLVKmWyUN0xF\" width=450px /\u003e\u003c/center\u003e\n\n```python\nqueue = []\n\nqueue.append('a') # append() function to push\nqueue.append('b') # element in the stack\nqueue.append('c') # -\u003e ['a', 'b', 'c']\n\nqueue.pop(0) # -\u003e 'a'\nqueue # -\u003e ['b', 'c']\n```\n* **Queue using Deque**\n\n```python\nfrom collections import deque\n\nqueue = deque([\"Ram\", \"Tarun\", \"Asif\", \"John\"])\nqueue.append(\"Akbar\") # -\u003e deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])\nqueue.popleft() # -\u003e 'Ram'\nqueue # -\u003e deque(['Tarun', 'Asif', 'John', 'Akbar'])                         \n```\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eDeque\u003c/summary\u003e\n\n**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).\n\n\u003ccenter\u003e\u003cimg src=\"https://drive.google.com/uc?export=view\u0026id=1tnjr9gTLRVcQ0d1tnMEMuXQYOwMqlTWw\" width=450px /\u003e\u003c/center\u003e\n\n``` python\nfrom collections import deque\n\ndeq = collections.deque([1, 2, 3]) # deque([1, 2, 3])\ndeq.appendleft(5) # deque([5, 1, 2, 3])\ndeq.append(6) # deque([5, 1, 2, 3, 6])\ndeq.popleft() # -\u003e 5\ndeq.pop() # -\u003e 6\n```\n\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eBinary Tree\u003c/summary\u003e\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"Tree/img/LeetCode0094_Preorder-from-Inorder-and-Postorder-traversals.jpg\" width=\"500\"\u003e\n\u003c/p\u003e\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eGraph\u003c/summary\u003e\n\n``` python\nN = 6\nedges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\ngraph = [[] for _ in range(N)]\nfor u,v in edges:\n    graph[u].append(v)\n    graph[v].append(u)\ngraph # -\u003e [[1, 2], [0], [0, 3, 4, 5], [2], [2], [2]]\n```\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eAlgorithms\u003c/summary\u003e\n\n* **Binary Search**\n``` python\n# Runtime complexity : O(log n)\n\ndef binary_search(self, nums: List[int], target: int) -\u003e int:\n    left, right = 0, len(nums) - 1\n    \n    while(left \u003c= right):\n        center = (left + right) // 2\n        if nums[center] == target:\n            return center\n        elif nums[center] \u003c target:\n            left = center + 1\n        else:\n            right = center - 1\n    \n    return -1\n```\n\u003c/details\u003e\n\n## **Array**\n* [11. Container With Most Water [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0011_Container_With_Most_Water.md)\n* [31. Next Permutation [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0031_Next_Permutation.md) 🔥\n* [42. Trapping Rain Water [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0042_Trapping_Rain_Water.md)\n* [134. Gas Station [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0134_Gas_Station.md)\n* [150. Evaluate Reverse Polish Notation [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Array/0150_Evaluate_Reverse_Polish_Notation.md)\n\n## **Backtracking**\n* [39. Combination Sum [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Backtracking/0039_Combination_Sum.md)\n* [46. Permutations [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Backtracking/0046_Permutations.md) 🔥\n* [51. N-Queens [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Backtracking/0051_N-Queens.md)\n* [79. Word Search [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Backtracking/0079_Word_Search.md)\n\n## **Binary Search**\n* [33. Search in Rotated Sorted Array [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Binary_Search/0033_Search_in_Rotated_Sorted_Array.md) 🔥\n* [74. Search a 2D Matrix [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Binary_Search/0074_Search_a_2D_Matrix.md)\n* [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)\n\n## **Bit Manipulation**\n* [89. Gray Code [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Bit_Manipulation/0089_Gray_Code.md)\n* [191. Number of 1 Bits [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Bit_Manipulation/0191_Number_of_1_Bits.md)\n* [461. Hamming Distance [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Bit_Manipulation/0461_Hamming_Distance.md) 🔥\n\n## **Dynamic Programming**\n* [22. Generate Parentheses [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Dynamic_Programming/0022_Generate_Parentheses.md) 🔥\n* [45. Jump Game II [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Dynamic_Programming/0045_Jump_Game_II.md)\n* [62. Unique Paths [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Dynamic_Programming/0062_Unique_Paths.md) 🔥\n* [91. Decode Ways [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Dynamic_Programming/0091_Decode_Ways.md) 🔥\n* [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)\n\n## **Graph**\n* [133. Clone Graph [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Graph/0133_Clone_Graph.md)\n* [138. Copy List with Random Pointer [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Graph/0138_Copy_List_with_Random_Pointer.md)\n* [207. Course Schedule [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Graph/0207_Course_Schedule.md)\n\n## **Linked List**\n* [2. Add Two Numbers [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0002_Add_Two_Numbers.md)\n* [21. Merge Two Sorted Lists [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0021_Merge_Two_Sorted_Lists.md)\n* [23. Merge k Sorted Lists [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0023_Merge_k_Sorted_Lists.md) 🔥\n* [24. Swap Nodes in Pairs [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0024_Swap_Nodes_in_Pairs.md)\n* [86. Partition List [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0086_Partition_List.md)\n* [143. Reorder List [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0143_Reorder_List.md)\n* [146. LRU Cache [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0146_LRU_Cache.md) 🔥\n* [148. Sort List [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0148_Sort_List.md)\n* [206. Reverse Linked List [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0206_Reverse_Linked_List.md) 🔥\n* [445. Add Two Numbers II [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Linked_List/0445_Add_Two_Numbers_II.md)\n\n## **Math**\n* [7. Reverse Integer [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Math/0007_Reverse_Integer.md)\n* [149. Max Points on a Line [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Math/0149_Max_Points_on_a_Line.md)\n\n## **Matrix**\n* [36. Valid Sudoku [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Matrix/0036_Valid_Sudoku.md)\n* [48. Rotate Image [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Matrix/0048_Rotate_Image.md) 🔥\n\n## **Sorting**\n* [15. 3Sum [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0015_3Sum.md)\n* [16. 3Sum Closest [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0016_3Sum_Closest.md)\n* [56. Merge Intervals [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0056_Merge_Intervals.md) 🔥\n* [75. Sort Colors [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0075_Sort_Colors.md) 🔥\n* [169. Majority Element [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Sorting/0169_Majority_Element.md)\n\n## **String**\n* [3. Longest Substring Without Repeating Characters [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0003_Longest_Substring_Without_Repeating_Characters.md)\n* [5. Longest Palindromic Substring [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0005_Longest_Palindromic_Substring.md) 🔥\n* [68. Text Justification [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0068_Text_Justification.md)\n* [71. Simplify Path [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0071_Simplify_Path.md) 🔥\n* [76. Minimum Window Substring [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0076_Minimum_Window_Substring.md) 🔥\n* [139. Word Break [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/String/0139_Word_Break.md)\n\n## **Tree**\n* [94. Binary Tree Inorder Traversal [Easy]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0094_Binary_Tree_Inorder_Traversal.md) 🔥\n* [95. Unique Binary Search Trees II [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0095_Unique_Binary_Search_Trees_II.md) 🔥\n* [98. Validate Binary Search Tree [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0098_Validate_Binary_Search_Tree.md)\n* [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)\n* [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) 🔥\n* [114. Flatten Binary Tree to Linked List [Medium]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0114_Flatten_Binary_Tree_to_Linked_List.md)\n* [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)\n* [124. Binary Tree Maximum Path Sum [Hard]](https://github.com/Followb1ind1y/LeetCode/blob/main/Tree/0124_Binary_Tree_Maximum_Path_Sum.md) 🔥\n\n## **To-do List**\n* [10. Regular Expression Matching [Hard]](https://leetcode.com/problems/regular-expression-matching/)\n* [25. Reverse Nodes in k-Group [Hard]](https://leetcode.com/problems/reverse-nodes-in-k-group/)\n* [44. Wildcard Matching [Hard]](https://leetcode.com/problems/wildcard-matching/)\n* [84. Largest Rectangle in Histogram [Hard]](https://leetcode.com/problems/largest-rectangle-in-histogram/)\n* [115. Distinct Subsequences [Hard]](https://leetcode.com/problems/distinct-subsequences/)\n* [126. Word Ladder II [Hard]](https://leetcode.com/problems/word-ladder-ii/)\n* [132. Palindrome Partitioning II [Hard]](https://leetcode.com/problems/palindrome-partitioning-ii/)","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffollowb1ind1y%2Fleetcode","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffollowb1ind1y%2Fleetcode","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffollowb1ind1y%2Fleetcode/lists"}