├── Common ├── Combinatorics │ └── Readme.md ├── Coding Templates │ ├── Binary Search.md │ ├── Sliding Window.md │ └── Two Pointers.md └── Math │ ├── Extract Digits │ ├── extract_digit.cpp │ └── README.md │ ├── Count Digits │ ├── README.md │ └── count.cpp │ ├── Odd │ ├── README.md │ └── odd_number.cpp │ ├── Even │ ├── README.md │ └── even_number.cpp │ ├── GCD_HCF_Calculation │ └── README.md │ ├── Reverse Number │ └── README.md │ └── Prime │ └── README.md ├── Level 1 ├── Week 13 │ ├── Tries │ │ └── README.md │ └── Topological Sort │ │ └── README.md ├── Week 14 │ ├── Maths │ │ └── README.md │ ├── probability │ │ └── README.md │ └── combinatorics │ │ └── README.md ├── Week 16 │ └── Bitwise │ │ └── README.md ├── Week 15 │ └── Prefix Sum │ │ └── README.md ├── README.md ├── Week 08 │ └── Top k elements & Merge Intervals [Heaps] │ │ └── README.md ├── Week 04 │ ├── Recursion │ │ ├── Print Numbers from 1 to N │ │ │ ├── README.md │ │ │ └── code.cpp │ │ ├── Sum of First N Natural Numbers │ │ │ ├── README.md │ │ │ └── code.cpp │ │ ├── Print Numbers from N to 1 │ │ │ ├── README.md │ │ │ └── code.cpp │ │ ├── Factorial of a Number │ │ │ ├── README.md │ │ │ └── code.cpp │ │ ├── Fibonacci Number (Nth Term) │ │ │ ├── README.md │ │ │ └── code.cpp │ │ ├── Calculate Power (a^b) │ │ │ ├── README.md │ │ │ └── code.cpp │ │ └── Check if a Number is a Palindrome │ │ │ └── README.md │ └── Trees │ │ ├── 104. Maximum Depth of Binary Tree │ │ ├── README.md │ │ └── code.cpp │ │ ├── 111. Minimum Depth of Binary Tree │ │ └── README.md │ │ ├── 102. Binary Tree Level Order Traversal │ │ └── README.md │ │ ├── 226. Invert Binary Tree │ │ ├── README.md │ │ └── code.cpp │ │ ├── 110. Balanced Binary Tree │ │ └── README.md │ │ └── 230. Kth Smallest Element in a BST │ │ └── README.md ├── Week 06 │ ├── Stack │ │ ├── 22. Generate Parentheses │ │ │ └── README.md │ │ ├── 739. Daily Temperatures │ │ │ └── README.md │ │ ├── 84. Largest Rectangle in Histogram │ │ │ └── README.md │ │ └── 20. Valid Parentheses │ │ │ ├── README.md │ │ │ └── code.cpp │ └── Queue │ │ ├── 862. Shortest Subarray with Sum at Least K │ │ └── README.md │ │ └── 239. Sliding Window Maximum │ │ └── README.md ├── Week 09 │ └── Greedy │ │ ├── 53. Maximum Subarray │ │ ├── README.md │ │ └── code.cpp │ │ ├── 678. Valid Parenthesis String │ │ └── README.md │ │ ├── 763. Partition Labels │ │ └── README.md │ │ ├── 45. Jump Game II │ │ ├── README.md │ │ └── code.cpp │ │ ├── 134. Gas Station │ │ └── code.cpp │ │ └── 1899. Merge Triplets to Form Target Triplet │ │ └── code.cpp ├── Week 07 │ └── K way merge [Heaps] │ │ ├── 253. Meeting Rooms II │ │ └── README.md │ │ ├── Meeting Rooms III │ │ └── README.md │ │ ├── Find Median from Data Stream │ │ ├── README.md │ │ └── code.cpp │ │ ├── 414. Third Maximum Number │ │ └── README.md │ │ ├── IPO │ │ ├── README.md │ │ └── code.cpp │ │ ├── 1046. Last Stone Weight │ │ └── README.md │ │ └── 703. Kth Largest Element in a Stream │ │ └── README.md ├── Week 02 │ ├── 2 pointers │ │ ├── 18. 4Sum │ │ │ └── README.md │ │ ├── 15. 3Sum │ │ │ └── README.md │ │ ├── 42. Trapping Rain Water │ │ │ └── README.md │ │ ├── 680. Valid Palindrome II │ │ │ └── README.md │ │ ├── 287. Find the Duplicate Number │ │ │ ├── README.md │ │ │ └── code.cpp │ │ ├── 2824. Count Pairs Whose Sum is Less than Target │ │ │ ├── README.md │ │ │ └── code.cpp │ │ └── 26. Remove Duplicates from Sorted Array │ │ │ ├── README.md │ │ │ └── code.cpp │ └── Sliding windows │ │ ├── 643. Maximum Average Subarray I │ │ ├── README.md │ │ └── code.cpp │ │ ├── 219. Contains Duplicate II │ │ ├── code.cpp │ │ └── README.md │ │ ├── 567. Permutation in String │ │ └── README.md │ │ ├── 3. Longest Substring Without Repeating Characters │ │ ├── code.cpp │ │ └── README.md │ │ └── 424. Longest Repeating Character Replacement │ │ ├── code.cpp │ │ └── README.md ├── Week 01 │ └── Arrays & Hashing │ │ ├── 217. Contains Duplicate │ │ ├── code.cpp │ │ └── README.md │ │ ├── 1. Two Sum │ │ ├── README.md │ │ └── code.cpp │ │ ├── 347. Top K Frequent Elements │ │ └── README.md │ │ ├── 49. Group Anagrams │ │ ├── README.md │ │ └── code.cpp │ │ ├── 242. Valid Anagram │ │ ├── README.md │ │ └── code.cpp │ │ └── 128. Longest Consecutive Sequence │ │ └── README.md ├── Week 10 │ ├── Recursion │ │ ├── 148. Sort List │ │ │ └── README.md │ │ ├── 206. Reverse Linked List │ │ │ ├── README.md │ │ │ └── code.cpp │ │ ├── 24. Swap Nodes in Pairs │ │ │ ├── README.md │ │ │ └── code.cpp │ │ ├── 92. Reverse Linked List II │ │ │ └── README.md │ │ ├── 23. Merge k Sorted Lists │ │ │ └── README.md │ │ ├── 21. Merge Two Sorted Lists │ │ │ └── README.md │ │ ├── 25. Reverse Nodes in k-Group │ │ │ └── README.md │ │ ├── 445. Add Two Numbers II │ │ │ └── README.md │ │ └── 2. Add Two Numbers │ │ │ └── README.md │ └── Backtracking │ │ ├── 78. Subsets │ │ ├── README.md │ │ └── code.cpp │ │ ├── 90. Subsets II │ │ └── README.md │ │ ├── 131. Palindrome Partitioning │ │ └── README.md │ │ ├── 46. Permutations │ │ └── README.md │ │ ├── 40. Combination Sum II │ │ └── README.md │ │ ├── 51. N-Queens │ │ └── README.md │ │ ├── 17. Letter Combinations of a Phone Number │ │ └── README.md │ │ └── 79. Word Search │ │ └── README.md ├── Week 11 │ └── Dynamic Programming │ │ ├── 70. Climbing Stairs │ │ └── README.md │ │ ├── 509. Fibonacci Number │ │ └── README.md │ │ ├── 322. Coin Change │ │ └── README.md │ │ ├── 62. Unique Paths │ │ └── README.md │ │ ├── 198. House Robber │ │ └── README.md │ │ └── 518. Coin Change II │ │ └── README.md ├── Week 03 │ └── LinkedList │ │ ├── 206. Reverse Linked List │ │ ├── code.cpp │ │ └── README.md │ │ ├── 141. Linked List Cycle │ │ └── code.cpp │ │ ├── 21. Merge Two Sorted Lists │ │ ├── code.cpp │ │ └── README.md │ │ ├── 19. Remove Nth Node From End of List │ │ └── README.md │ │ ├── 25. Reverse Nodes in k-Group │ │ └── code.cpp │ │ ├── 143. Reorder List │ │ └── README.md │ │ └── 2. Add Two Numbers │ │ └── README.md ├── Week 12 │ └── Graph │ │ ├── 130. Surrounded Regions │ │ └── README.md │ │ ├── 200. Number of Islands │ │ └── README.md │ │ ├── 994. Rotting Oranges │ │ └── README.md │ │ ├── 133. Clone Graph │ │ └── README.md │ │ └── 207. Course Schedule │ │ └── README.md └── Week 05 │ └── Modified Binary Search │ ├── 4. Median of Two Sorted Arrays │ └── README.md │ └── 704. Binary Search │ ├── README.md │ └── code.cpp ├── Level 0 ├── 0 Simulation - Arrays │ ├── 1480. Running Sum of 1d Array │ │ └── code.cpp │ ├── Arrays_Session_Notes.pdf │ └── README.md ├── 2 Hashmaps │ └── Hashmap_Session_Notes.pdf ├── 1 Simulation - Strings │ ├── String_Session_Notes.pdf.pdf │ └── README.md ├── 9 Modified Binary Search │ ├── 01. 0792-binary-search │ │ ├── 0792-binary-search.cpp │ │ └── README.md │ ├── 03. 0153-find-minimum-in-rotated-sorted-array │ │ └── 0153-find-minimum-in-rotated-sorted-array.cpp │ ├── 08. 0907-koko-eating-bananas │ │ └── 0907-koko-eating-bananas.cpp │ ├── 05. 0081-search-in-rotated-sorted-array-ii │ │ └── 0081-search-in-rotated-sorted-array-ii.cpp │ ├── 07. 0074-search-a-2d-matrix │ │ └── 0074-search-a-2d-matrix.cpp │ └── 02. 0034-find-first-and-last-position-of-element-in-sorted-array │ │ ├── 0034-find-first-and-last-position-of-element-in-sorted-array.cpp │ │ └── README.md ├── 10 Backtracking │ ├── 06. 0131-palindrome-partitioning │ │ └── README.md │ ├── 05. 090-subsets-ii │ │ ├── README.md │ │ └── code.cpp │ ├── 04. 046-permutations │ │ ├── README.md │ │ └── code.cpp │ ├── 01. 078-subsets │ │ ├── README.md │ │ └── code.cpp │ ├── 08. 0051-n-queens │ │ └── README.md │ ├── 07. 0017-letter-combinations-of-a-phone-number │ │ ├── README.md │ │ └── code.cpp │ ├── 03. 040-combination-sum-ii │ │ └── README.md │ └── 02. 039-combination-sum │ │ ├── README.md │ │ └── code.cpp ├── 8 Trees │ ├── 04. 0102-binary-tree-level-order-traversal │ │ └── README.md │ ├── 05. 0199-binary-tree-right-side-view │ │ └── README.md │ ├── 08. 0230-kth-smallest-element-in-a-bst │ │ └── README.md │ ├── 01. 0543-diameter-of-binary-tree │ │ └── README.md │ ├── 07. 0098-validate-binary-search-tree │ │ └── README.md │ ├── 09. 0105-construct-binary-tree-from-preorder-and-inorder-traversal │ │ └── README.md │ ├── 02. 0572-subtree-of-another-tree │ │ └── README.md │ ├── 10. 0124-binary-tree-maximum-path-sum │ │ └── README.md │ ├── 06. 1448-count-good-nodes-in-binary-tree │ │ └── README.md │ └── 11. 0297-serialize-and-deserialize-binary-tree │ │ └── README.md └── 7 Sliding Window │ ├── 11. 0713-subarray-product-less-than-k │ └── README.md │ ├── 07. 0567-permutation-in-string │ └── README.md │ ├── 02. 0643-maximum-average-subarray-i │ └── README.md │ ├── 03. 0219-contains-duplicate-ii │ └── README.md │ ├── 08. 0003-longest-substring-without-repeating-characters │ └── README.md │ └── 09. 0424-longest-repeating-character-replacement │ └── README.md └── Pre-Requisites └── ReadME.md /Common/Combinatorics/Readme.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 1/Week 13/Tries/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 1/Week 14/Maths/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 1/Week 16/Bitwise/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 1/Week 14/probability/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 1/Week 15/Prefix Sum/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Common/Coding Templates/Binary Search.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Common/Coding Templates/Sliding Window.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Common/Coding Templates/Two Pointers.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 1/Week 13/Topological Sort/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 1/Week 14/combinatorics/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 1/README.md: -------------------------------------------------------------------------------- 1 | All Level 0 resources here -------------------------------------------------------------------------------- /Level 0/0 Simulation - Arrays/1480. Running Sum of 1d Array/code.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 1/Week 08/Top k elements & Merge Intervals [Heaps]/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Level 0/2 Hashmaps/Hashmap_Session_Notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devweekends/DW-Fellowship-DSA-Roadmap/HEAD/Level 0/2 Hashmaps/Hashmap_Session_Notes.pdf -------------------------------------------------------------------------------- /Level 0/0 Simulation - Arrays/Arrays_Session_Notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devweekends/DW-Fellowship-DSA-Roadmap/HEAD/Level 0/0 Simulation - Arrays/Arrays_Session_Notes.pdf -------------------------------------------------------------------------------- /Level 0/1 Simulation - Strings/String_Session_Notes.pdf.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devweekends/DW-Fellowship-DSA-Roadmap/HEAD/Level 0/1 Simulation - Strings/String_Session_Notes.pdf.pdf -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Print Numbers from 1 to N/README.md: -------------------------------------------------------------------------------- 1 | ## 📘 Print Numbers from 1 to N 2 | 3 | ### 📝 Description 4 | 5 | Print all natural numbers from **1 to N** using **recursion**. 6 | 7 | ### 🔢 Input 8 | 9 | An integer `N` 10 | **Constraints:** `1 ≤ N ≤ 10⁴` 11 | 12 | ### 📤 Output 13 | 14 | Space-separated integers from 1 to N. 15 | 16 | ### 📌 Example 17 | Input: 5 18 | Output: 1 2 3 4 5 -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Sum of First N Natural Numbers/README.md: -------------------------------------------------------------------------------- 1 | ## 📘 Sum of First N Natural Numbers 2 | 3 | ### 📝 Description 4 | Compute the **sum of the first N natural numbers** recursively. 5 | 6 | ### 🔢 Input 7 | A single integer `N` 8 | **Constraints:** `1 ≤ N ≤ 10⁵` 9 | 10 | ### 📤 Output 11 | An integer representing the sum from 1 to N. 12 | 13 | ### 📌 Example 14 | Input: 5 15 | Output: 15 -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Print Numbers from N to 1/README.md: -------------------------------------------------------------------------------- 1 | ## 📘 Print Numbers from N to 1 2 | 3 | ### 📝 Description 4 | 5 | Print all natural numbers from **N to 1** in reverse order using **recursion**. 6 | 7 | ### 🔢 Input 8 | 9 | An integer `N` 10 | **Constraints:** `1 ≤ N ≤ 10⁴` 11 | 12 | ### 📤 Output 13 | 14 | Space-separated integers from N to 1. 15 | 16 | ### 📌 Example 17 | 18 | Input: 4 19 | Output: 4 3 2 1 -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Factorial of a Number/README.md: -------------------------------------------------------------------------------- 1 | ## 📘 Factorial of a Number 2 | 3 | ### 📝 Description 4 | Calculate the **factorial of N** using recursion. 5 | Definition: 6 | `N! = N × (N - 1) × ... × 1` 7 | Base Case: `0! = 1` 8 | 9 | ### 🔢 Input 10 | A single integer `N` 11 | **Constraints:** `0 ≤ N ≤ 20` 12 | 13 | ### 📤 Output 14 | An integer representing `N!` 15 | 16 | ### 📌 Example 17 | Input: 4 18 | Output: 24 -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Fibonacci Number (Nth Term)/README.md: -------------------------------------------------------------------------------- 1 | ## 📘 7. Fibonacci Number (Nth Term) 2 | 3 | ### 📝 Description 4 | Find the **Nth term** of the Fibonacci sequence using recursion. 5 | 6 | Definition: 7 | fib(0) = 0 8 | fib(1) = 1 9 | fib(n) = fib(n-1) + fib(n-2) 10 | 11 | ### 🔢 Input 12 | A single integer `n` 13 | **Constraints:** `0 ≤ n ≤ 30` 14 | 15 | ### 📤 Output 16 | An integer representing the `n`th Fibonacci number. 17 | 18 | ### 📌 Example 19 | Input: 6 20 | Output: 8 -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Calculate Power (a^b)/README.md: -------------------------------------------------------------------------------- 1 | ## 📘 Calculate Power (a^b) 2 |

50. Pow(x, n) 3 |

4 | 5 | 6 | 7 | ### 📝 Description 8 | Compute **a^b** using recursion. 9 | Assume `a ≥ 1` and `b ≥ 0`. 10 | 11 | ### 🔢 Input 12 | Two integers `a` and `b` 13 | **Constraints:** `1 ≤ a ≤ 10⁴`, `0 ≤ b ≤ 10³` 14 | 15 | ### 📤 Output 16 | An integer representing `a^b` 17 | 18 | ### 📌 Example 19 | Input: 2 5 20 | Output: 32 -------------------------------------------------------------------------------- /Level 0/9 Modified Binary Search/01. 0792-binary-search/0792-binary-search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int left = 0; 5 | int right = nums.size() - 1; 6 | 7 | while(left <= right){ 8 | int mid = left + (right - left) / 2; 9 | 10 | if(nums[mid] == target) return mid; 11 | else if(nums[mid] > target) right = mid - 1; 12 | else left = mid + 1; 13 | } 14 | 15 | return -1; 16 | } 17 | }; -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Check if a Number is a Palindrome/README.md: -------------------------------------------------------------------------------- 1 | ## 📘 Check if a Number is a Palindrome 2 | 3 | ### 📝 Description 4 | Check whether a number is a **palindrome** using recursion. 5 | A palindrome reads the same forward and backward. 6 | 7 | ### 🔢 Input 8 | A non-negative integer `N` 9 | **Constraints:** `0 ≤ N ≤ 10⁶` 10 | 11 | ### 📤 Output 12 | `true` if the number is a palindrome, otherwise `false`. 13 | 14 | ### 📌 Examples 15 | Input: 121 16 | Output: true 17 | 18 | Input: 123 19 | Output: false -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Factorial of a Number/code.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Approach: Recursive Factorial 4 | 5 | The factorial of a number n is: 6 | n! = n * (n - 1)! 7 | 8 | We use recursion to multiply n with the factorial of (n - 1), 9 | until we reach the base case: 10 | 0! = 1 11 | 12 | Time Complexity: O(N) 13 | 14 | Space Complexity: O(N) 15 | - Due to the function call stack. 16 | */ 17 | 18 | #include 19 | using namespace std; 20 | 21 | int factorial(int n) { 22 | if (n == 0) return 1; 23 | return n * factorial(n - 1); 24 | } 25 | -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Sum of First N Natural Numbers/code.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Approach: Recursive Summation 4 | 5 | We recursively add the current number to the result of the sum of numbers before it. 6 | sum(n) = n + sum(n - 1) 7 | 8 | Base Case: 9 | - sum(0) = 0 10 | 11 | Time Complexity: O(N) 12 | - One call per number from N down to 0. 13 | 14 | Space Complexity: O(N) 15 | - Due to call stack depth. 16 | */ 17 | 18 | #include 19 | using namespace std; 20 | 21 | int sum(int n) { 22 | if (n == 0) return 0; 23 | return n + sum(n - 1); 24 | } 25 | -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Print Numbers from N to 1/code.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Approach: Recursive (Simple Reverse Counting) 4 | 5 | This function prints numbers from N to 1 using recursion. 6 | It starts from N and decreases the number by one at each step. 7 | 8 | Base Case: 9 | - If the current number becomes less than 1, we stop recursion. 10 | 11 | Time Complexity: O(N) 12 | - We print N numbers once. 13 | 14 | Space Complexity: O(N) 15 | - Due to recursive calls up to N levels deep. 16 | */ 17 | 18 | #include 19 | using namespace std; 20 | 21 | void printNTo1(int n) { 22 | if (n < 1) return; 23 | cout << n << " "; 24 | printNTo1(n - 1); 25 | } -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Calculate Power (a^b)/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: Optimized Recursive Power Function (Exponentiation by Squaring) 3 | 4 | We use: 5 | power(a, b) = power(a * a, b / 2) if b is even 6 | power(a, b) = a * power(a * a, b / 2) if b is odd 7 | Base Case: 8 | power(a, 0) = 1 9 | 10 | Time Complexity: O(log b) 11 | Space Complexity: O(log b) 12 | */ 13 | 14 | #include 15 | using namespace std; 16 | 17 | int power(int a, int b) { 18 | if (b == 0) return 1; 19 | 20 | int half = power(a, b / 2); 21 | 22 | if (b % 2 == 0) 23 | return half * half; 24 | else 25 | return a * half * half; 26 | } 27 | -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Print Numbers from 1 to N/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: Recursive (Simple Forward Counting) 3 | 4 | This function prints numbers from 1 to N using recursion. 5 | It starts from 1 and goes up by one until it reaches N. 6 | 7 | Base Case: 8 | - If the current number exceeds N, we stop the recursion. 9 | 10 | Time Complexity: O(N) 11 | - Each number from 1 to N is printed once. 12 | 13 | Space Complexity: O(N) 14 | - Due to N recursive calls on the stack. 15 | */ 16 | 17 | #include 18 | using namespace std; 19 | 20 | void print1ToN(int i, int n) { 21 | if (i > n) return; 22 | cout << i << " "; 23 | print1ToN(i + 1, n); 24 | } 25 | -------------------------------------------------------------------------------- /Level 0/10 Backtracking/06. 0131-palindrome-partitioning/README.md: -------------------------------------------------------------------------------- 1 | # 131. Palindrome Partitioning 2 | 3 | ## Problem Description 4 | 5 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return *all possible palindrome partitioning of `s`*. 6 | 7 | ## Examples 8 | 9 | ### Example 1: 10 | 11 | **Input:** `s = "aab"` 12 | 13 | **Output:** `[["a","a","b"],["aa","b"]]` 14 | 15 | ### Example 2: 16 | 17 | **Input:** `s = "a"` 18 | 19 | **Output:** `[["a"]]` 20 | 21 | ## Constraints 22 | 23 | - `1 <= s.length <= 16` 24 | - `s` contains only lowercase English letters. 25 | 26 | ## Related Topics 27 | 28 | - String 29 | - Dynamic Programming 30 | - Backtracking 31 | 32 | ## Difficulty 33 | 34 | Medium -------------------------------------------------------------------------------- /Level 1/Week 06/Stack/22. Generate Parentheses/README.md: -------------------------------------------------------------------------------- 1 |

22. Generate Parentheses

Medium


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

2 | 3 |

 

4 |

Example 1:

5 |
Input: n = 3
 6 | Output: ["((()))","(()())","(())()","()(())","()()()"]
 7 | 

Example 2:

8 |
Input: n = 1
 9 | Output: ["()"]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= n <= 8
  • 16 |
17 | -------------------------------------------------------------------------------- /Level 0/10 Backtracking/05. 090-subsets-ii/README.md: -------------------------------------------------------------------------------- 1 | # 90. Subsets II 2 | 3 | ## Problem Description 4 | 5 | Given an integer array `nums` that may contain **duplicates**, return *all possible subsets (the power set)*. 6 | 7 | The solution set **must not** contain duplicate subsets. Return the solution in **any order**. 8 | 9 | ## Examples 10 | 11 | ### Example 1: 12 | 13 | **Input:** `nums = [1,2,2]` 14 | 15 | **Output:** `[[],[1],[1,2],[1,2,2],[2],[2,2]]` 16 | 17 | ### Example 2: 18 | 19 | **Input:** `nums = [0]` 20 | 21 | **Output:** `[[],[0]]` 22 | 23 | ## Constraints 24 | 25 | - `1 <= nums.length <= 10` 26 | - `-10 <= nums[i] <= 10` 27 | 28 | ## Related Topics 29 | 30 | - Array 31 | - Backtracking 32 | - Bit Manipulation 33 | 34 | ## Difficulty 35 | 36 | Medium -------------------------------------------------------------------------------- /Level 1/Week 09/Greedy/53. Maximum Subarray/README.md: -------------------------------------------------------------------------------- 1 | # Maximum Subarray 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given an integer array `nums`, find the subarray with the largest sum, and return its sum. 8 | 9 | --- 10 | 11 | ## Examples 12 | 13 | ### Example 1 14 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 15 | Output: 6 16 | Explanation: The subarray [4,-1,2,1] has the largest sum 6. 17 | 18 | ### Example 2 19 | Input: nums = [1] 20 | Output: 1 21 | Explanation: The subarray [1] has the largest sum 1. 22 | 23 | ### Example 3 24 | Input: nums = [5,4,-1,7,8] 25 | Output: 23 26 | Explanation: The subarray [5,4,-1,7,8] has the largest sum 23. 27 | 28 | --- 29 | 30 | ## Constraints 31 | 32 | - `1 <= nums.length <= 10^5` 33 | - `-10^4 <= nums[i] <= 10^4` 34 | 35 | --- 36 | -------------------------------------------------------------------------------- /Level 1/Week 07/K way merge [Heaps]/253. Meeting Rooms II/README.md: -------------------------------------------------------------------------------- 1 | # Meeting Rooms II 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return the **minimum number of conference rooms** required. 8 | 9 | --- 10 | 11 | ## Examples 12 | 13 | ### Example 1 14 | Input: intervals = [[0,30],[5,10],[15,20]] 15 | Output: 2 16 | Explanation: We need two meeting rooms: 17 | - Room 1: [0,30] 18 | - Room 2: [5,10],[15,20] 19 | 20 | ### Example 2 21 | Input: intervals = [[7,10],[2,4]] 22 | Output: 1 23 | Explanation: We need one meeting room: 24 | - Room 1: [2,4],[7,10] 25 | 26 | --- 27 | 28 | ## Constraints 29 | 30 | - `1 <= intervals.length <= 10^4` 31 | - `0 <= starti < endi <= 10^6` 32 | 33 | --- -------------------------------------------------------------------------------- /Level 0/10 Backtracking/04. 046-permutations/README.md: -------------------------------------------------------------------------------- 1 | # 46. Permutations 2 | 3 | ## Problem Description 4 | 5 | Given an array `nums` of distinct integers, return *all the possible permutations*. You can return the answer in **any order**. 6 | 7 | ## Examples 8 | 9 | ### Example 1: 10 | 11 | **Input:** `nums = [1,2,3]` 12 | 13 | **Output:** `[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]` 14 | 15 | ### Example 2: 16 | 17 | **Input:** `nums = [0,1]` 18 | 19 | **Output:** `[[0,1],[1,0]]` 20 | 21 | ### Example 3: 22 | 23 | **Input:** `nums = [1]` 24 | 25 | **Output:** `[[1]]` 26 | 27 | ## Constraints 28 | 29 | - `1 <= nums.length <= 6` 30 | - `-10 <= nums[i] <= 10` 31 | - All the integers of `nums` are **unique**. 32 | 33 | ## Related Topics 34 | 35 | - Array 36 | - Backtracking 37 | 38 | ## Difficulty 39 | 40 | Medium -------------------------------------------------------------------------------- /Level 0/10 Backtracking/01. 078-subsets/README.md: -------------------------------------------------------------------------------- 1 | # 78. Subsets 2 | 3 | ## Problem Description 4 | 5 | Given an integer array `nums` of **unique** elements, return *all possible subsets (the power set)*. 6 | 7 | The solution set **must not** contain duplicate subsets. Return the solution in **any order**. 8 | 9 | ## Examples 10 | 11 | ### Example 1: 12 | 13 | **Input:** `nums = [1,2,3]` 14 | 15 | **Output:** `[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]` 16 | 17 | ### Example 2: 18 | 19 | **Input:** `nums = [0]` 20 | 21 | **Output:** `[[],[0]]` 22 | 23 | ## Constraints 24 | 25 | - `1 <= nums.length <= 10` 26 | - `-10 <= nums[i] <= 10` 27 | - All the numbers of `nums` are **unique**. 28 | 29 | ## Follow-up 30 | 31 | Can you solve this problem using **bit manipulation**? 32 | 33 | ## Related Topics 34 | 35 | - Array 36 | - Backtracking 37 | - Bit Manipulation 38 | 39 | ## Difficulty 40 | 41 | Medium -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/18. 4Sum/README.md: -------------------------------------------------------------------------------- 1 | # 🧮 18. 4Sum 2 | 3 | **Difficulty:** Medium 4 | **Link:** [LeetCode 18 - 4Sum](https://leetcode.com/problems/4sum) 5 | 6 | --- 7 | 8 | ## 🧠 Problem Statement 9 | 10 | Given an array `nums` of `n` integers, return all **unique quadruplets** `[nums[a], nums[b], nums[c], nums[d]]` such that: 11 | 12 | - `0 <= a, b, c, d < n` 13 | - `a`, `b`, `c`, and `d` are **distinct** 14 | - `nums[a] + nums[b] + nums[c] + nums[d] == target` 15 | 16 | The answer can be returned in **any order**, but **must not contain duplicate quadruplets**. 17 | 18 | --- 19 | 20 | ## 📥 Example 21 | 22 | ### Example 1: 23 | Input: nums = [1,0,-1,0,-2,2], target = 0 24 | Output: [[-2,-1,1,2], [-2,0,0,2], [-1,0,0,1]] 25 | 26 | ### Example 2: 27 | Input: nums = [2,2,2,2,2], target = 8 28 | Output: [[2,2,2,2]] 29 | 30 | 31 | --- 32 | 33 | ## 📌 Constraints 34 | - `1 <= nums.length <= 200 -------------------------------------------------------------------------------- /Level 0/8 Trees/04. 0102-binary-tree-level-order-traversal/README.md: -------------------------------------------------------------------------------- 1 | # 102. Binary Tree Level Order Traversal 2 | 3 | ## Problem Description 4 | 5 | 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). 6 | 7 | ## Examples 8 | 9 | ### Example 1: 10 | ![Example 1](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg) 11 | 12 | **Input:** `root = [3,9,20,null,null,15,7]` 13 | 14 | **Output:** `[[3],[9,20],[15,7]]` 15 | 16 | ### Example 2: 17 | 18 | **Input:** `root = [1]` 19 | 20 | **Output:** `[[1]]` 21 | 22 | ### Example 3: 23 | 24 | **Input:** `root = []` 25 | 26 | **Output:** `[]` 27 | 28 | ## Constraints 29 | 30 | - The number of nodes in the tree is in the range `[0, 2000]`. 31 | - `-1000 <= Node.val <= 1000` 32 | 33 | ## Related Topics 34 | 35 | - Tree 36 | - Breadth-First Search 37 | - Binary Tree 38 | 39 | ## Difficulty 40 | 41 | Medium 42 | -------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/217. Contains Duplicate/code.cpp: -------------------------------------------------------------------------------- 1 | // Approach: 2 | // We use an unordered_set to keep track of the numbers we have seen so far. 3 | // As we iterate through the array, for each number: 4 | // - If it already exists in the set, it means we've seen a duplicate, so we return true. 5 | // - Otherwise, we insert the number into the set. 6 | // If we finish iterating through the array without finding any duplicates, we return false. 7 | // Time Complexity: O(n) where n is the number of elements in nums. 8 | // Space Complexity: O(n) for storing elements in the set. 9 | 10 | class Solution { 11 | public: 12 | bool containsDuplicate(vector& nums) { 13 | unordered_set seen; 14 | 15 | for (int num : nums) { 16 | if (seen.count(num)) { 17 | return true; 18 | } 19 | seen.insert(num); 20 | } 21 | return false; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Level 1/Week 07/K way merge [Heaps]/Meeting Rooms III/README.md: -------------------------------------------------------------------------------- 1 | # Meeting Rooms III 2 | 3 | **Difficulty:** Hard 4 | 5 | ## Problem Description 6 | 7 | You are given an integer n. There are n rooms numbered from 0 to n - 1. 8 | 9 | You are given a 2D integer array meetings where meetings[i] = [starti, endi, roomi] describes a meeting that starts at time starti and ends at time endi in room roomi. 10 | 11 | All the meetings are non-overlapping. 12 | 13 | Return the number of the room that held the most meetings. If there are multiple rooms, return the one with the smallest number. 14 | 15 | --- 16 | 17 | ## Examples 18 | 19 | ### Example 1 20 | Input: n = 2, meetings = [[0,10,0],[5,15,1]] 21 | Output: 0 22 | 23 | ### Example 2 24 | Input: n = 3, meetings = [[0,10,0],[5,15,1],[10,20,2]] 25 | Output: 0 26 | 27 | --- 28 | 29 | ## Constraints 30 | 31 | - 1 <= n <= 100 32 | - 1 <= meetings.length <= 10^4 33 | - 0 <= starti < endi <= 10^9 34 | - 0 <= roomi < n -------------------------------------------------------------------------------- /Level 0/8 Trees/05. 0199-binary-tree-right-side-view/README.md: -------------------------------------------------------------------------------- 1 | # 199. Binary Tree Right Side View 2 | 3 | ## Problem Description 4 | 5 | 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. 6 | 7 | ## Examples 8 | 9 | ### Example 1: 10 | ![Example 1](https://assets.leetcode.com/uploads/2021/02/14/tree.jpg) 11 | 12 | **Input:** `root = [1,2,3,null,5,null,4]` 13 | 14 | **Output:** `[1,3,4]` 15 | 16 | ### Example 2: 17 | 18 | **Input:** `root = [1,null,3]` 19 | 20 | **Output:** `[1,3]` 21 | 22 | ### Example 3: 23 | 24 | **Input:** `root = []` 25 | 26 | **Output:** `[]` 27 | 28 | ## Constraints 29 | 30 | - The number of nodes in the tree is in the range `[0, 100]`. 31 | - `-100 <= Node.val <= 100` 32 | 33 | ## Related Topics 34 | 35 | - Tree 36 | - Depth-First Search 37 | - Breadth-First Search 38 | - Binary Tree 39 | 40 | ## Difficulty 41 | 42 | Medium 43 | -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/15. 3Sum/README.md: -------------------------------------------------------------------------------- 1 | # 15. 3Sum 2 | 3 | **Difficulty:** Medium 4 | **Link:** [LeetCode - 3Sum](https://leetcode.com/problems/3sum/) 5 | 6 | --- 7 | 8 | ## 🧠 Problem Statement 9 | 10 | Given an integer array `nums`, return **all unique triplets** `[nums[i], nums[j], nums[k]]` such that: 11 | 12 | - `i != j`, `i != k`, and `j != k` 13 | - `nums[i] + nums[j] + nums[k] == 0` 14 | 15 | The solution set must **not contain duplicate triplets**. 16 | 17 | --- 18 | 19 | ## 🧪 Examples 20 | 21 | ### Example 1: 22 | Input: nums = [-1,0,1,2,-1,-4] 23 | Output: [[-1,-1,2],[-1,0,1]] 24 | 25 | Explanation: 26 | - Triplet 1: (-1) + (-1) + 2 = 0 27 | - Triplet 2: (-1) + 0 + 1 = 0 28 | 29 | ### Example 2: 30 | Input: nums = [0,1,1] 31 | Output: [] 32 | 33 | ### Example 3: 34 | Input: nums = [0,0,0] 35 | Output: [[0,0,0]] 36 | 37 | 38 | --- 39 | 40 | ## 🔍 Constraints 41 | 42 | - `3 <= nums.length <= 3000` 43 | - `-10⁵ <= nums[i] <= 10⁵` 44 | 45 | --- -------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/1. Two Sum/README.md: -------------------------------------------------------------------------------- 1 | # Two Sum 2 | 3 | **Difficulty:** Easy 4 | 5 | ## Problem Description 6 | 7 | Given an array of integers `nums` and an integer `target`, return **indices of the two numbers** such that they add up to `target`. 8 | 9 | You may assume that each input would have **exactly one solution**, and you **may not use the same element twice**. 10 | 11 | You can return the answer in **any order**. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: nums = [2,7,11,15], target = 9 19 | Output: [0,1] 20 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 21 | 22 | 23 | ### Example 2 24 | Input: nums = [3,2,4], target = 6 25 | Output: [1,2] 26 | 27 | ### Example 3 28 | Input: nums = [3,3], target = 6 29 | Output: [0,1] 30 | 31 | --- 32 | 33 | ## Constraints 34 | 35 | - `2 <= nums.length <= 10^4` 36 | - `-10^9 <= nums[i] <= 10^9` 37 | - `-10^9 <= target <= 10^9` 38 | - Only one valid answer exists. 39 | 40 | --- -------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/347. Top K Frequent Elements/README.md: -------------------------------------------------------------------------------- 1 | # 347. Top K Frequent Elements 2 | 3 | **Difficulty:** Medium 4 | **Tag(s):** Hash Map, Heap, Sorting, Bucket Sort 5 | 6 | --- 7 | 8 | ## Problem Description 9 | 10 | Given an integer array `nums` and an integer `k`, return the `k` most frequent elements. 11 | You may return the answer in **any order**. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | **Input:** 19 | ```text 20 | nums = [1,1,1,2,2,3], k = 2 21 | Output: 22 | [1,2] 23 | Explanation: 24 | 25 | 1 appears 3 times 26 | 2 appears 2 times 27 | 3 appears once 28 | → The top 2 frequent elements are [1,2] 29 | ``` 30 | 31 | ### Example 2: 32 | Input: 33 | 34 | nums = [1], k = 1 35 | Output: 36 | 37 | [1] 38 | 39 | ### Constraints: 40 | 1 <= nums.length <= 10⁵ 41 | 42 | -10⁴ <= nums[i] <= 10⁴ 43 | 44 | k is in the range [1, the number of unique elements in the array] 45 | 46 | It is guaranteed that the answer is unique 47 | 48 | -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/42. Trapping Rain Water/README.md: -------------------------------------------------------------------------------- 1 | # 🧩 42. Trapping Rain Water 2 | 3 | **Difficulty:** Hard 4 | **Link:** [Leetcode - Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water) 5 | 6 | --- 7 | 8 | ## 📝 Problem Statement 9 | 10 | Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining. 11 | 12 | --- 13 | 14 | ## 📊 Examples 15 | 16 | ### Example 1: 17 | Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] 18 | Output: 6 19 | 20 | **Explanation:** 21 | In this case, 6 units of rain water are trapped between the elevations. 22 | 23 | --- 24 | 25 | ### Example 2: 26 | Input: height = [4,2,0,3,2,5] 27 | Output: 9 28 | 29 | **Explanation:** 30 | Multiple dips in the terrain allow water to be trapped, resulting in 9 units in total. 31 | 32 | --- 33 | 34 | ## ✅ Constraints 35 | 36 | - `1 <= height.length <= 2 * 10⁴` 37 | - `0 <= height[i] <= 10⁵` 38 | 39 | --- -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/680. Valid Palindrome II/README.md: -------------------------------------------------------------------------------- 1 | # 680. Valid Palindrome II 2 | 3 | **Difficulty:** Easy 4 | **Link:** [LeetCode Problem](https://leetcode.com/problems/valid-palindrome-ii) 5 | 6 | --- 7 | 8 | ## 🧠 Problem Statement 9 | 10 | Given a string `s`, return `true` if the string can be a palindrome **after deleting at most one character** from it. 11 | 12 | --- 13 | 14 | ## 📌 Examples 15 | 16 | ### ✅ Example 1: 17 | ```txt 18 | Input: s = "aba" 19 | Output: true 20 | Explanation: Already a palindrome. No character needs to be removed. 21 | 22 | ``` 23 | 24 | ### ✅ Example 2: 25 | 26 | Input: s = "abca" 27 | Output: true 28 | Explanation: Removing 'c' makes it "aba", which is a palindrome. 29 | 30 | ### ❌ Example 3: 31 | 32 | Input: s = "abc" 33 | Output: false 34 | Explanation: No way to make this a palindrome by removing just one character. 35 | 36 | 37 | ### Constraints 38 | 39 | 1 <= s.length <= 10^5 40 | 41 | s consists of lowercase English letters only. -------------------------------------------------------------------------------- /Level 0/7 Sliding Window/11. 0713-subarray-product-less-than-k/README.md: -------------------------------------------------------------------------------- 1 | ## [713. Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k) 2 | 3 | **Difficulty:** Medium 4 | **Tags:** Two Pointers, Sliding Window, Array 5 | 6 | --- 7 | 8 | ### Problem Statement 9 | 10 | Given an array of integers `nums` and an integer `k`, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than `k`. 11 | 12 | --- 13 | 14 | ### Test Cases 15 | 16 | **Test Case 1:** 17 | ```text 18 | Input: nums = [10, 5, 2, 6], k = 100 19 | Output: 8 20 | Explanation: The 8 subarrays that have product less than 100 are: 21 | [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] 22 | ``` 23 | 24 | **Test Case 2:** 25 | ```text 26 | Input: nums = [1, 2, 3], k = 0 27 | Output: 0 28 | ``` 29 | 30 | --- 31 | 32 | ## Constraints 33 | 34 | - `1 <= nums.length <= 3 * 10^4` 35 | - `1 <= nums[i] <= 1000` 36 | - `0 <= k <= 10^6` 37 | 38 | --- -------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/49. Group Anagrams/README.md: -------------------------------------------------------------------------------- 1 | # 49. Group Anagrams 2 | 3 | **Difficulty:** Medium 4 | 5 | --- 6 | 7 | ## Problem Description 8 | 9 | Given an array of strings `strs`, group the anagrams together. You can return the answer in **any order**. 10 | 11 | Two strings are **anagrams** if they contain the same characters with the same frequency, but possibly in a different order. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | 19 | **Input:** 20 | ```txt 21 | strs = ["eat","tea","tan","ate","nat","bat"] 22 | 23 | 24 | [["bat"],["nat","tan"],["ate","eat","tea"]] 25 | 26 | ``` 27 | ### Explanation: 28 | 29 | "eat", "tea", and "ate" are anagrams. 30 | "tan" and "nat" are anagrams. 31 | "bat" has no anagram pair. 32 | 33 | ### Example 2 34 | 35 | **Input:** 36 | ```txt 37 | strs = [""] 38 | 39 | 40 | [[""]] 41 | ``` 42 | ### Explanation: 43 | 44 | "eat", "tea", and "ate" are anagrams. 45 | "tan" and "nat" are anagrams. 46 | "bat" has no anagram pair. 47 | -------------------------------------------------------------------------------- /Level 0/10 Backtracking/08. 0051-n-queens/README.md: -------------------------------------------------------------------------------- 1 | # 51. N-Queens 2 | 3 | ## Problem Description 4 | 5 | The **n-queens puzzle** is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. 6 | 7 | Given an integer `n`, return *all distinct solutions to the **n-queens puzzle***. You may return the answer in **any order**. 8 | 9 | Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. 10 | 11 | ## Examples 12 | 13 | ### Example 1: 14 | 15 | **Input:** `n = 4` 16 | 17 | **Output:** `[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]` 18 | 19 | **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above. 20 | 21 | ### Example 2: 22 | 23 | **Input:** `n = 1` 24 | 25 | **Output:** `[["Q"]]` 26 | 27 | ## Constraints 28 | 29 | - `1 <= n <= 9` 30 | 31 | ## Related Topics 32 | 33 | - Array 34 | - Backtracking 35 | 36 | ## Difficulty 37 | 38 | Hard -------------------------------------------------------------------------------- /Level 1/Week 02/Sliding windows/643. Maximum Average Subarray I/README.md: -------------------------------------------------------------------------------- 1 |

643. Maximum Average Subarray I

Easy


You are given an integer array nums consisting of n elements, and an integer k.

2 | 3 |

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [1,12,-5,-6,50,3], k = 4
10 | Output: 12.75000
11 | Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums = [5], k = 1
18 | Output: 5.00000
19 | 
-------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/242. Valid Anagram/README.md: -------------------------------------------------------------------------------- 1 | # 🔤 242. Valid Anagram 2 | 3 | **Difficulty:** Easy 4 | **Tags:** Hash Table, String, Sorting 5 | 6 | --- 7 | 8 | ## 📝 Problem Statement 9 | 10 | Given two strings `s` and `t`, return `true` if `t` is an anagram of `s`, and `false` otherwise. 11 | 12 | 📌 **Definition:** 13 | An **anagram** is a word or phrase formed by rearranging the letters of another word, using **all the original letters exactly once**. 14 | 15 | --- 16 | 17 | ## 📥 Input 18 | 19 | - Two strings `s` and `t`, both consisting of lowercase English letters. 20 | 21 | ## 📤 Output 22 | 23 | - A boolean value: `true` if `t` is an anagram of `s`, `false` otherwise. 24 | 25 | --- 26 | 27 | ## 🧪 Examples 28 | 29 | ### Example 1: 30 | ```txt 31 | Input: s = "anagram", t = "nagaram" 32 | Output: true 33 | ``` 34 | ### Example 2: 35 | 36 | Input: s = "rat", t = "car" 37 | Output: false 38 | 39 | ### Constraints: 40 | 1 <= s.length, t.length <= 5 * 10⁴ 41 | 42 | s and t consist of lowercase English letters only. -------------------------------------------------------------------------------- /Level 0/10 Backtracking/01. 078-subsets/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vector> result; 4 | 5 | void backtrack(vector& nums, vector& current, int start) { 6 | // Add current subset to result 7 | result.push_back(current); 8 | 9 | // Try all possible elements starting from 'start' 10 | for (int i = start; i < nums.size(); i++) { 11 | // Make choice: include nums[i] 12 | current.push_back(nums[i]); 13 | 14 | // Recurse with next element 15 | backtrack(nums, current, i + 1); 16 | 17 | // Backtrack: remove nums[i] 18 | current.pop_back(); 19 | } 20 | } 21 | 22 | public: 23 | vector> subsets(vector& nums) { 24 | vector current; 25 | backtrack(nums, current, 0); 26 | return result; 27 | } 28 | }; 29 | 30 | /* 31 | Time Complexity: O(2^n) where n is the length of nums 32 | Space Complexity: O(n) for recursion stack 33 | */ -------------------------------------------------------------------------------- /Level 1/Week 09/Greedy/678. Valid Parenthesis String/README.md: -------------------------------------------------------------------------------- 1 | # Valid Parenthesis String 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` if `s` is **valid**. 8 | 9 | The following rules define a **valid** string: 10 | - Any left parenthesis `'('` must have a corresponding right parenthesis `')'`. 11 | - Any right parenthesis `')'` must have a corresponding left parenthesis `'('`. 12 | - Left parenthesis `'('` must go before the corresponding right parenthesis `')'`. 13 | - `'*'` could be treated as a single right parenthesis `')'` or a single left parenthesis `'('` or an empty string `""`. 14 | 15 | --- 16 | 17 | ## Examples 18 | 19 | ### Example 1 20 | Input: s = "()" 21 | Output: true 22 | 23 | ### Example 2 24 | Input: s = "(*)" 25 | Output: true 26 | 27 | ### Example 3 28 | Input: s = "(*))" 29 | Output: true 30 | 31 | --- 32 | 33 | ## Constraints 34 | 35 | - `1 <= s.length <= 100` 36 | - `s[i]` is `'('`, `')'` or `'*'`. 37 | 38 | --- 39 | -------------------------------------------------------------------------------- /Level 1/Week 09/Greedy/763. Partition Labels/README.md: -------------------------------------------------------------------------------- 1 | # Partition Labels 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | You are given a string `s`. We want to partition this string into as many parts as possible so that each letter appears in at most one part. 8 | 9 | Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. 10 | 11 | Return a list of integers representing the size of these parts. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: s = "ababcbacadefegdehijhklij" 19 | Output: [9,7,8] 20 | Explanation: 21 | The partition is "ababcbaca", "defegde", "hijhklij". 22 | This is a partition so that each letter appears in at most one part. 23 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts. 24 | 25 | ### Example 2 26 | Input: s = "eccbbbbdec" 27 | Output: [10] 28 | 29 | --- 30 | 31 | ## Constraints 32 | 33 | - `1 <= s.length <= 500` 34 | - `s` consists of lowercase English letters. 35 | 36 | --- 37 | -------------------------------------------------------------------------------- /Level 1/Week 04/Recursion/Fibonacci Number (Nth Term)/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: Recursive (Brute Force) 3 | 4 | This solution uses a simple recursive approach to compute the nth Fibonacci number. 5 | The Fibonacci sequence is defined as: 6 | fib(0) = 0 7 | fib(1) = 1 8 | fib(n) = fib(n - 1) + fib(n - 2) for n > 1 9 | 10 | The function calls itself for the two preceding numbers until it reaches the base cases (n = 0 or n = 1). 11 | 12 | Time Complexity: O(2^n) 13 | - This is because the function makes two recursive calls for each non-base case, 14 | leading to an exponential growth in calls. 15 | 16 | Space Complexity: O(n) 17 | - Due to the function call stack in recursion which can go up to n levels deep. 18 | 19 | Note: 20 | - This approach is simple but inefficient for large values of n. 21 | - It can be optimized using memoization or iteration to achieve O(n) time complexity. 22 | */ 23 | 24 | #include 25 | using namespace std; 26 | 27 | int fib(int n) { 28 | if (n <= 1){ 29 | return n; 30 | } 31 | return fib(n - 2) + fib(n - 1); 32 | } 33 | -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/148. Sort List/README.md: -------------------------------------------------------------------------------- 1 | # Sort List 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given the `head` of a linked list, return *the list after sorting it in **ascending order***. 8 | 9 | --- 10 | 11 | ## Examples 12 | 13 | ### Example 1 14 | Input: head = [4,2,1,3] 15 | Output: [1,2,3,4] 16 | 17 | ### Example 2 18 | Input: head = [-1,5,3,4,0] 19 | Output: [-1,0,3,4,5] 20 | 21 | ### Example 3 22 | Input: head = [] 23 | Output: [] 24 | 25 | --- 26 | 27 | ## Constraints 28 | 29 | - The number of nodes in the list is in the range `[0, 5 * 10^4]`. 30 | - `-10^5 <= Node.val <= 10^5` 31 | 32 | --- 33 | 34 | ## Approach 35 | 36 | This problem can be solved using merge sort with recursion: 37 | 1. Base case: if head is null or only one node remains 38 | 2. Recursive case: find the middle of the list 39 | 3. Recursively sort the left and right halves 40 | 4. Merge the two sorted halves 41 | 5. Return the merged sorted list 42 | 43 | The recursive approach naturally implements the divide and conquer strategy of merge sort. 44 | 45 | --- 46 | -------------------------------------------------------------------------------- /Level 1/Week 10/Backtracking/78. Subsets/README.md: -------------------------------------------------------------------------------- 1 | # Subsets 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given an integer array `nums` of **unique** elements, return *all possible subsets (the power set)*. 8 | 9 | The solution set **must not** contain duplicate subsets. Return the solution in **any order**. 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: nums = [1,2,3] 17 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 18 | 19 | ### Example 2 20 | Input: nums = [0] 21 | Output: [[],[0]] 22 | 23 | --- 24 | 25 | ## Constraints 26 | 27 | - `1 <= nums.length <= 10` 28 | - `-10 <= nums[i] <= 10` 29 | - All the numbers of `nums` are **unique**. 30 | 31 | --- 32 | 33 | ## Approach 34 | 35 | This problem can be solved using backtracking where we: 36 | 1. For each element, we have two choices: include it or exclude it 37 | 2. We build the subset incrementally 38 | 3. When we reach the end of the array, we add the current subset to our result 39 | 4. We backtrack by removing the last added element to try the exclude option 40 | 41 | --- 42 | -------------------------------------------------------------------------------- /Level 1/Week 09/Greedy/45. Jump Game II/README.md: -------------------------------------------------------------------------------- 1 | # Jump Game II 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | You are given a 0-indexed array of integers `nums` of length `n`. You are initially positioned at `nums[0]`. 8 | 9 | Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where: 10 | - `0 <= j <= nums[i]` and 11 | - `i + j < n` 12 | 13 | Return the minimum number of jumps to reach `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`. 14 | 15 | --- 16 | 17 | ## Examples 18 | 19 | ### Example 1 20 | Input: nums = [2,3,1,1,4] 21 | Output: 2 22 | Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. 23 | 24 | ### Example 2 25 | Input: nums = [2,3,0,1,4] 26 | Output: 2 27 | 28 | --- 29 | 30 | ## Constraints 31 | 32 | - `1 <= nums.length <= 10^4` 33 | - `0 <= nums[i] <= 1000` 34 | - It's guaranteed that you can reach `nums[n - 1]`. 35 | 36 | --- 37 | -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/206. Reverse Linked List/README.md: -------------------------------------------------------------------------------- 1 | # Reverse Linked List 2 | 3 | **Difficulty:** Easy 4 | 5 | ## Problem Description 6 | 7 | Given the `head` of a singly linked list, reverse the list, and return the reversed list. 8 | 9 | --- 10 | 11 | ## Examples 12 | 13 | ### Example 1 14 | Input: head = [1,2,3,4,5] 15 | Output: [5,4,3,2,1] 16 | 17 | ### Example 2 18 | Input: head = [1,2] 19 | Output: [2,1] 20 | 21 | ### Example 3 22 | Input: head = [] 23 | Output: [] 24 | 25 | --- 26 | 27 | ## Constraints 28 | 29 | - The number of nodes in the list is the range `[0, 5000]`. 30 | - `-5000 <= Node.val <= 5000` 31 | 32 | --- 33 | 34 | ## Approach 35 | 36 | This is a classic recursion problem for reversing a linked list: 37 | 1. Base case: if head is null or only one node remains 38 | 2. Recursive case: reverse the rest of the list 39 | 3. Make the current node point to the reversed list 40 | 4. Return the new head (which is the last node of original list) 41 | 42 | The recursive approach naturally handles the reversal by working backwards from the end of the list. 43 | 44 | --- 45 | -------------------------------------------------------------------------------- /Level 1/Week 07/K way merge [Heaps]/Find Median from Data Stream/README.md: -------------------------------------------------------------------------------- 1 | # Find Median from Data Stream 2 | 3 | **Difficulty:** Hard 4 | 5 | ## Problem Description 6 | 7 | The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. 8 | 9 | Implement the MedianFinder class: 10 | - MedianFinder() initializes the MedianFinder object. 11 | - void addNum(int num) adds the integer num from the data stream to the data structure. 12 | - double findMedian() returns the median of all elements so far. Answers within 10^-5 of the actual answer will be accepted. 13 | 14 | --- 15 | 16 | ## Examples 17 | 18 | ### Example 1 19 | Input: ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"] 20 | [[],[1],[2],[],[3],[]] 21 | Output: [null,null,null,1.5,null,2.0] 22 | 23 | --- 24 | 25 | ## Constraints 26 | 27 | - -10^5 <= num <= 10^5 28 | - There will be at least one element in the data structure before calling findMedian. 29 | - At most 5 * 10^4 calls will be made to addNum and findMedian. -------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/217. Contains Duplicate/README.md: -------------------------------------------------------------------------------- 1 | # 🧩 217. Contains Duplicate 2 | 3 | **Difficulty:** Easy 4 | **Tags:** Array, Hash Table, Two Pointers, Sorting 5 | 6 | --- 7 | 8 | ## 📝 Problem Statement 9 | 10 | Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is **distinct**. 11 | 12 | --- 13 | 14 | ## 📥 Input 15 | 16 | - A list of integers `nums`. 17 | 18 | ## 📤 Output 19 | 20 | - A boolean value `true` if a duplicate exists, `false` otherwise. 21 | 22 | --- 23 | 24 | ## 🧪 Examples 25 | 26 | ### Example 1: 27 | ```txt 28 | Input: nums = [1, 2, 3, 1] 29 | Output: true 30 | Explanation: 1 is repeated. 31 | ``` 32 | 33 | ### Example 2: 34 | 35 | Input: nums = [1, 2, 3, 4] 36 | Output: false 37 | Explanation: All elements are distinct. 38 | 39 | ### Example 3: 40 | 41 | Input: nums = [1,1,1,3,3,4,3,2,4,2] 42 | Output: true 43 | Explanation: Multiple elements appear more than once. 44 | 45 | ## 📌 Constraints 46 | 47 | - `1 <= nums.length <= 10⁵` 48 | - `-10⁹ <= nums[i] <= 10⁹` 49 | 50 | --- -------------------------------------------------------------------------------- /Common/Math/Extract Digits/extract_digit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | --------------------------------------------------- 6 | 🔹 Problem: Count Total Digits in a Number 7 | --------------------------------------------------- 8 | Goal: Extract digits of a number and count how many digits it has. 9 | 10 | ✅ Example: 11 | Input: 1234 12 | Digits: 1, 2, 3, 4 13 | Output: 4 (There are 4 digits) 14 | --------------------------------------------------- 15 | */ 16 | 17 | /* 18 | 🔸 Approach: Using Modulo (%) and Division (/) 19 | - Use %10 to get the last digit (rightmost digit) 20 | - Divide by 10 to remove the last digit 21 | - Repeat until number becomes 0 22 | */ 23 | 24 | int digitCount(int n) { 25 | int cnt = 0; 26 | while (n > 0) { 27 | int lastDigit = n % 10; 28 | cnt++; 29 | n = n / 10; 30 | } 31 | return cnt; 32 | } 33 | 34 | int main() { 35 | cout << "Enter a number: "; 36 | int num; 37 | cin >> num; 38 | 39 | cout << "Total digits in " << num << " = " << digitCount(num) << endl; 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Level 1/Week 10/Backtracking/90. Subsets II/README.md: -------------------------------------------------------------------------------- 1 | # Subsets II 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given an integer array `nums` that may contain **duplicates**, return *all possible subsets (the power set)*. 8 | 9 | The solution set **must not** contain duplicate subsets. Return the solution in **any order**. 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: nums = [1,2,2] 17 | Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] 18 | 19 | ### Example 2 20 | Input: nums = [0] 21 | Output: [[],[0]] 22 | 23 | --- 24 | 25 | ## Constraints 26 | 27 | - `1 <= nums.length <= 10` 28 | - `-10 <= nums[i] <= 10` 29 | 30 | --- 31 | 32 | ## Approach 33 | 34 | This problem is similar to Subsets I but with duplicates in the input array: 35 | 1. We sort the array to group duplicates together 36 | 2. We use backtracking to generate all possible subsets 37 | 3. We skip duplicate elements at the same level to avoid duplicate subsets 38 | 4. We have two choices for each element: include it or exclude it 39 | 5. We handle duplicates carefully to ensure unique subsets 40 | 41 | --- 42 | -------------------------------------------------------------------------------- /Level 1/Week 11/Dynamic Programming/70. Climbing Stairs/README.md: -------------------------------------------------------------------------------- 1 | # Climbing Stairs 2 | 3 | **Difficulty:** Easy 4 | 5 | ## Problem Description 6 | 7 | You are climbing a staircase. It takes `n` steps to reach the top. 8 | 9 | Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: n = 2 17 | Output: 2 18 | Explanation: There are two ways to climb to the top. 19 | 1. 1 step + 1 step 20 | 2. 2 steps 21 | 22 | ### Example 2 23 | Input: n = 3 24 | Output: 3 25 | Explanation: There are three ways to climb to the top. 26 | 1. 1 step + 1 step + 1 step 27 | 2. 1 step + 2 steps 28 | 3. 2 steps + 1 step 29 | 30 | --- 31 | 32 | ## Constraints 33 | 34 | - `1 <= n <= 45` 35 | 36 | --- 37 | 38 | ## Approaches 39 | 40 | This problem can be solved using 4 different dynamic programming approaches: 41 | 42 | 1. **Recursion** - Direct recursive implementation 43 | 2. **Memoization** - Top-down DP with caching 44 | 3. **Tabulation** - Bottom-up DP with array 45 | 4. **Space Optimization** - Optimized space complexity 46 | 47 | --- 48 | -------------------------------------------------------------------------------- /Level 0/9 Modified Binary Search/03. 0153-find-minimum-in-rotated-sorted-array/0153-find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int n = nums.size(); 5 | int left = 0; 6 | int right = n - 1; 7 | 8 | while (left <= right) { 9 | // If the subarray is already sorted 10 | if (nums[left] <= nums[right]) { 11 | return nums[left]; 12 | } 13 | 14 | int mid = left + (right - left) / 2; 15 | int next = (mid + 1) % n; 16 | int prev = (mid - 1 + n) % n; 17 | 18 | // Check if mid is the minimum 19 | if (nums[mid] <= nums[prev] && nums[mid] <= nums[next]) { 20 | return nums[mid]; 21 | } 22 | 23 | // Decide which half to search next 24 | if (nums[left] <= nums[mid]) { 25 | left = mid + 1; 26 | } else { 27 | right = mid - 1; 28 | } 29 | } 30 | 31 | return -1; // This should not be reached if input meets constraints 32 | } 33 | }; -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/24. Swap Nodes in Pairs/README.md: -------------------------------------------------------------------------------- 1 | # Swap Nodes in Pairs 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem **without modifying the values** in the list's nodes (i.e., only nodes themselves may be changed.) 8 | 9 | --- 10 | 11 | ## Examples 12 | 13 | ### Example 1 14 | Input: head = [1,2,3,4] 15 | Output: [2,1,4,3] 16 | 17 | ### Example 2 18 | Input: head = [] 19 | Output: [] 20 | 21 | ### Example 3 22 | Input: head = [1] 23 | Output: [1] 24 | 25 | --- 26 | 27 | ## Constraints 28 | 29 | - The number of nodes in the list is in the range `[0, 100]`. 30 | - `0 <= Node.val <= 100` 31 | 32 | --- 33 | 34 | ## Approach 35 | 36 | This problem can be solved using recursion: 37 | 1. Base case: if head is null or only one node remains 38 | 2. Recursive case: swap the first two nodes 39 | 3. Recursively swap the remaining nodes 40 | 4. Return the new head of the swapped pair 41 | 42 | The key insight is to handle the swapping at each level and then recursively process the rest of the list. 43 | 44 | --- 45 | -------------------------------------------------------------------------------- /Level 1/Week 03/LinkedList/206. Reverse Linked List/code.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Approach: 3 | * We will use the **iterative method** to reverse the singly-linked list. 4 | * - Initialize three pointers: `prev` as `nullptr`, `current` as `head`, and `nextNode` for temporary storage. 5 | * - Iterate through the list, and for each node: 6 | * - Save `current->next` to `nextNode`. 7 | * - Reverse the link: point `current->next` to `prev`. 8 | * - Move `prev` and `current` one step forward. 9 | * - At the end, `prev` will be the new head of the reversed list. 10 | * - Return `prev`. 11 | */ 12 | 13 | class Solution { 14 | public: 15 | ListNode* reverseList(ListNode* head) { 16 | ListNode* prev = nullptr; 17 | ListNode* current = head; 18 | 19 | while (current != nullptr) { 20 | ListNode* nextNode = current->next; // store next 21 | current->next = prev; // reverse current node's pointer 22 | prev = current; // move prev and current one step forward 23 | current = nextNode; 24 | } 25 | 26 | return prev; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Level 0/8 Trees/08. 0230-kth-smallest-element-in-a-bst/README.md: -------------------------------------------------------------------------------- 1 | # 230. Kth Smallest Element in a BST 2 | 3 | ## Problem Description 4 | 5 | Given the `root` of a binary search tree and an integer `k`, return *the* `kth` *smallest value (**1-indexed**) of all the values of the nodes in the tree*. 6 | 7 | ## Examples 8 | 9 | ### Example 1: 10 | ![Example 1](https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg) 11 | 12 | **Input:** `root = [3,1,4,null,2], k = 1` 13 | 14 | **Output:** `1` 15 | 16 | ### Example 2: 17 | ![Example 2](https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg) 18 | 19 | **Input:** `root = [5,3,6,2,4,null,null,1], k = 3` 20 | 21 | **Output:** `3` 22 | 23 | ## Constraints 24 | 25 | - The number of nodes in the tree is `n`. 26 | - `1 <= k <= n <= 10^4` 27 | - `0 <= Node.val <= 10^4` 28 | 29 | ## Follow-up 30 | 31 | 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? 32 | 33 | ## Related Topics 34 | 35 | - Tree 36 | - Depth-First Search 37 | - Binary Search Tree 38 | - Binary Tree 39 | 40 | ## Difficulty 41 | 42 | Medium 43 | -------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/128. Longest Consecutive Sequence/README.md: -------------------------------------------------------------------------------- 1 |

128. Longest Consecutive Sequence

Medium


Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

2 | 3 |

You must write an algorithm that runs in O(n) time.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [100,4,200,1,3,2]
10 | Output: 4
11 | Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums = [0,3,7,2,5,8,4,6,0,1]
18 | Output: 9
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • 0 <= nums.length <= 105
  • 26 |
  • -109 <= nums[i] <= 109
  • 27 |
28 | -------------------------------------------------------------------------------- /Level 1/Week 04/Trees/104. Maximum Depth of Binary Tree/README.md: -------------------------------------------------------------------------------- 1 |

104. Maximum Depth of Binary Tree

Easy


Given the root of a binary tree, return its maximum depth.

2 | 3 |

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: root = [3,9,20,null,null,15,7]
10 | Output: 3
11 | 
12 | 13 |

Example 2:

14 | 15 |
16 | Input: root = [1,null,2]
17 | Output: 2
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • The number of nodes in the tree is in the range [0, 104].
  • 25 |
  • -100 <= Node.val <= 100
  • 26 |
27 | -------------------------------------------------------------------------------- /Level 1/Week 07/K way merge [Heaps]/414. Third Maximum Number/README.md: -------------------------------------------------------------------------------- 1 | # Third Maximum Number 2 | 3 | **Difficulty:** Easy 4 | 5 | ## Problem Description 6 | 7 | Given an integer array `nums`, return the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number. 8 | 9 | --- 10 | 11 | ## Examples 12 | 13 | ### Example 1 14 | Input: nums = [3,2,1] 15 | Output: 1 16 | Explanation: 17 | The first distinct maximum is 3. 18 | The second distinct maximum is 2. 19 | The third distinct maximum is 1. 20 | 21 | ### Example 2 22 | Input: nums = [1,2] 23 | Output: 2 24 | Explanation: 25 | The first distinct maximum is 2. 26 | The second distinct maximum is 1. 27 | The third maximum does not exist, so the maximum (2) is returned. 28 | 29 | ### Example 3 30 | Input: nums = [2,2,3,1] 31 | Output: 1 32 | Explanation: 33 | The first distinct maximum is 3. 34 | The second distinct maximum is 2 (both 2's are counted together since they have the same value). 35 | The third distinct maximum is 1. 36 | 37 | --- 38 | 39 | ## Constraints 40 | 41 | - `1 <= nums.length <= 10^4` 42 | - `-2^31 <= nums[i] <= 2^31 - 1` 43 | 44 | --- -------------------------------------------------------------------------------- /Level 0/8 Trees/01. 0543-diameter-of-binary-tree/README.md: -------------------------------------------------------------------------------- 1 | # 543. Diameter of Binary Tree 2 | 3 | ## Problem Description 4 | 5 | Given the `root` of a binary tree, return *the length of the **diameter** of the tree*. 6 | 7 | The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`. 8 | 9 | The **length** of path between two nodes is represented by the number of edges between them. 10 | 11 | ## Examples 12 | 13 | ### Example 1: 14 | ![Example 1](https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg) 15 | 16 | **Input:** `root = [1,2,3,4,5]` 17 | 18 | **Output:** `3` 19 | 20 | **Explanation:** 3 is the length of the path [4,2,1,3] or [5,2,1,3]. 21 | 22 | ### Example 2: 23 | 24 | **Input:** `root = [1,2]` 25 | 26 | **Output:** `1` 27 | 28 | ## Constraints 29 | 30 | - The number of nodes in the tree is in the range `[1, 10^4]`. 31 | - `-100 <= Node.val <= 100` 32 | 33 | ## Follow-up 34 | 35 | Can you solve this problem in linear time? 36 | 37 | ## Related Topics 38 | 39 | - Tree 40 | - Depth-First Search 41 | - Binary Tree 42 | 43 | ## Difficulty 44 | 45 | Easy 46 | -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/287. Find the Duplicate Number/README.md: -------------------------------------------------------------------------------- 1 | # 287. Find the Duplicate Number 2 | 3 | > Difficulty: 🟠 Medium 4 | > Link: [Leetcode - Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) 5 | 6 | --- 7 | 8 | ## 🧠 Problem Description 9 | 10 | Given an array `nums` containing **n + 1** integers where each integer is in the range **[1, n]** inclusive, there is **only one repeated number** but it could be repeated **more than once**. 11 | 12 | You **must not**: 13 | - Modify the input array. 14 | - Use more than constant extra space. 15 | 16 | Return the **duplicate** number. 17 | 18 | --- 19 | 20 | ## 🧪 Examples 21 | 22 | ### Example 1: 23 | Input: nums = [1,3,4,2,2] 24 | Output: 2 25 | 26 | ### Example 2: 27 | Input: nums = [3,1,3,4,2] 28 | Output: 3 29 | 30 | ### Example 3: 31 | Input: nums = [3,3,3,3,3] 32 | Output: 3 33 | 34 | --- 35 | 36 | ## ✅ Constraints 37 | 38 | - 1 ≤ n ≤ 10⁵ 39 | - `nums.length == n + 1` 40 | - `1 ≤ nums[i] ≤ n` 41 | - All integers appear **only once**, except **one** that appears **two or more times** 42 | - **Do not modify** the array 43 | - Use **only constant extra space** 44 | 45 | --- -------------------------------------------------------------------------------- /Level 0/10 Backtracking/07. 0017-letter-combinations-of-a-phone-number/README.md: -------------------------------------------------------------------------------- 1 | # 17. Letter Combinations of a Phone Number 2 | 3 | ## Problem Description 4 | 5 | Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. 6 | 7 | A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 8 | 9 | ``` 10 | 2 -> "abc" 11 | 3 -> "def" 12 | 4 -> "ghi" 13 | 5 -> "jkl" 14 | 6 -> "mno" 15 | 7 -> "pqrs" 16 | 8 -> "tuv" 17 | 9 -> "wxyz" 18 | ``` 19 | 20 | ## Examples 21 | 22 | ### Example 1: 23 | 24 | **Input:** `digits = "23"` 25 | 26 | **Output:** `["ad","ae","af","bd","be","bf","cd","ce","cf"]` 27 | 28 | ### Example 2: 29 | 30 | **Input:** `digits = ""` 31 | 32 | **Output:** `[]` 33 | 34 | ### Example 3: 35 | 36 | **Input:** `digits = "2"` 37 | 38 | **Output:** `["a","b","c"]` 39 | 40 | ## Constraints 41 | 42 | - `0 <= digits.length <= 4` 43 | - `digits[i]` is a digit in the range `['2', '9']`. 44 | 45 | ## Related Topics 46 | 47 | - Hash Table 48 | - String 49 | - Backtracking 50 | 51 | ## Difficulty 52 | 53 | Medium -------------------------------------------------------------------------------- /Level 1/Week 04/Trees/111. Minimum Depth of Binary Tree/README.md: -------------------------------------------------------------------------------- 1 |

111. Minimum Depth of Binary Tree

Easy


Given a binary tree, find its minimum depth.

2 | 3 |

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

4 | 5 |

Note: A leaf is a node with no children.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: root = [3,9,20,null,null,15,7]
12 | Output: 2
13 | 
14 | 15 |

Example 2:

16 | 17 |
18 | Input: root = [2,null,3,null,4,null,5,null,6]
19 | Output: 5
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in the tree is in the range [0, 105].
  • 27 |
  • -1000 <= Node.val <= 1000
  • 28 |
29 | -------------------------------------------------------------------------------- /Level 1/Week 10/Backtracking/131. Palindrome Partitioning/README.md: -------------------------------------------------------------------------------- 1 | # Palindrome Partitioning 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return *all possible palindrome partitioning of* `s`. 8 | 9 | --- 10 | 11 | ## Examples 12 | 13 | ### Example 1 14 | Input: s = "aab" 15 | Output: [["a","a","b"],["aa","b"]] 16 | 17 | ### Example 2 18 | Input: s = "a" 19 | Output: [["a"]] 20 | 21 | --- 22 | 23 | ## Constraints 24 | 25 | - `1 <= s.length <= 16` 26 | - `s` contains only lowercase English letters. 27 | 28 | --- 29 | 30 | ## Approach 31 | 32 | This problem uses backtracking to find all valid palindrome partitions: 33 | 1. We try to partition the string at different positions 34 | 2. For each partition, we check if the substring is a palindrome 35 | 3. If it is a palindrome, we recursively partition the remaining string 36 | 4. We backtrack by removing the last partition to try different splits 37 | 5. When we've processed the entire string, we add the current partition to our result 38 | 6. We use a helper function to check if a string is a palindrome 39 | 40 | --- 41 | -------------------------------------------------------------------------------- /Level 0/10 Backtracking/03. 040-combination-sum-ii/README.md: -------------------------------------------------------------------------------- 1 | # 40. Combination Sum II 2 | 3 | ## Problem Description 4 | 5 | Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`. 6 | 7 | Each number in `candidates` may only be used **once** in the combination. 8 | 9 | **Note:** The solution set must not contain duplicate combinations. 10 | 11 | ## Examples 12 | 13 | ### Example 1: 14 | 15 | **Input:** `candidates = [10,1,2,7,6,1,5]`, `target = 8` 16 | 17 | **Output:** `[[1,1,6],[1,2,5],[1,7],[2,6]]` 18 | 19 | **Explanation:** 20 | - 1 and 1 are candidates, and 1 + 1 + 6 = 8. 21 | - 1 and 2 are candidates, and 1 + 2 + 5 = 8. 22 | - 1 and 7 are candidates, and 1 + 7 = 8. 23 | - 2 and 6 are candidates, and 2 + 6 = 8. 24 | 25 | ### Example 2: 26 | 27 | **Input:** `candidates = [2,5,2,1,2]`, `target = 5` 28 | 29 | **Output:** `[[1,2,2],[5]]` 30 | 31 | ## Constraints 32 | 33 | - `1 <= candidates.length <= 100` 34 | - `1 <= candidates[i] <= 50` 35 | - `1 <= target <= 30` 36 | 37 | ## Related Topics 38 | 39 | - Array 40 | - Backtracking 41 | 42 | ## Difficulty 43 | 44 | Medium -------------------------------------------------------------------------------- /Common/Math/Count Digits/README.md: -------------------------------------------------------------------------------- 1 | # 🔢 Count Digits That Divide the Number – C++ Implementation 2 | 3 | --- 4 | 5 | ## 🧠 Problem Definition 6 | 7 | Given an integer `n`, count how many of its digits **evenly divide** the number itself. 8 | 9 | ### ✳️ Rules: 10 | - Ignore digits that are **0** (to avoid division by zero) 11 | - Count digits that divide `n` **exactly** (i.e., `n % digit == 0`) 12 | 13 | --- 14 | 15 | ### ✅ Examples: 16 | 17 | #### Example 1: 18 | Input: 122 19 | Digits: 1, 2, 2 20 | 122 % 1 == 0 → ✅ 21 | 122 % 2 == 0 → ✅ 22 | 122 % 2 == 0 → ✅ 23 | 24 | Output: 3 25 | 26 | #### Example 2: 27 | 28 | Input: 1012 29 | Digits: 1, 0, 1, 2 30 | Skip 0 31 | 1012 % 1 == 0 → ✅ 32 | 1012 % 2 == 0 → ✅ 33 | 34 | Output: 3 35 | 36 | 37 | --- 38 | 39 | ## 📘 What’s Included? 40 | 41 | | Approach | Description | 42 | |----------|-------------| 43 | | Brute Force | Use `%` to extract digits and check divisibility | 44 | | `log10` Trick | Use log10 to find number of total digits (not dividing ones) | 45 | 46 | --- 47 | 48 | ## 🗂 File Structure 49 | 50 | Count Digits/ 51 | ├── even_digit_count.cpp # Full C++ implementation 52 | ├── README.md # Explanation and usage 53 | 54 | └── Makefile # Build and run the code -------------------------------------------------------------------------------- /Level 1/Week 10/Backtracking/46. Permutations/README.md: -------------------------------------------------------------------------------- 1 | # Permutations 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given an array `nums` of distinct integers, return *all the possible permutations*. You can return the answer in **any order**. 8 | 9 | --- 10 | 11 | ## Examples 12 | 13 | ### Example 1 14 | Input: nums = [1,2,3] 15 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 16 | 17 | ### Example 2 18 | Input: nums = [0,1] 19 | Output: [[0,1],[1,0]] 20 | 21 | ### Example 3 22 | Input: nums = [1] 23 | Output: [[1]] 24 | 25 | --- 26 | 27 | ## Constraints 28 | 29 | - `1 <= nums.length <= 6` 30 | - `-10 <= nums[i] <= 10` 31 | - All the integers of `nums` are **unique**. 32 | 33 | --- 34 | 35 | ## Approach 36 | 37 | This problem uses backtracking to generate all possible permutations: 38 | 1. We build the permutation incrementally by choosing one element at a time 39 | 2. We use a boolean array to track which elements have been used 40 | 3. For each position, we try all unused elements 41 | 4. We backtrack by marking elements as unused and removing them from the current permutation 42 | 5. When we've used all elements, we add the complete permutation to our result 43 | 44 | --- 45 | -------------------------------------------------------------------------------- /Level 1/Week 11/Dynamic Programming/509. Fibonacci Number/README.md: -------------------------------------------------------------------------------- 1 | # Fibonacci Number 2 | 3 | **Difficulty:** Easy 4 | 5 | ## Problem Description 6 | 7 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 8 | 9 | F(0) = 0, F(1) = 1 10 | F(n) = F(n - 1) + F(n - 2), for n > 1. 11 | 12 | Given n, calculate F(n). 13 | 14 | --- 15 | 16 | ## Examples 17 | 18 | ### Example 1 19 | Input: n = 2 20 | Output: 1 21 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 22 | 23 | ### Example 2 24 | Input: n = 3 25 | Output: 2 26 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 27 | 28 | ### Example 3 29 | Input: n = 4 30 | Output: 3 31 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 32 | 33 | --- 34 | 35 | ## Constraints 36 | 37 | - `0 <= n <= 30` 38 | 39 | --- 40 | 41 | ## Approaches 42 | 43 | This problem can be solved using 4 different dynamic programming approaches: 44 | 45 | 1. **Recursion** - Direct recursive implementation 46 | 2. **Memoization** - Top-down DP with caching 47 | 3. **Tabulation** - Bottom-up DP with array 48 | 4. **Space Optimization** - Optimized space complexity 49 | 50 | --- 51 | -------------------------------------------------------------------------------- /Level 1/Week 03/LinkedList/141. Linked List Cycle/code.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Approach: 3 | * We use Floyd’s Cycle Detection Algorithm (also known as the Tortoise and Hare algorithm): 4 | * - Use two pointers: `slow` and `fast`. 5 | * - `slow` moves one step at a time, while `fast` moves two steps at a time. 6 | * - If there is no cycle, `fast` will eventually reach the end (NULL). 7 | * - If there is a cycle, `fast` and `slow` will eventually meet at some point within the cycle. 8 | * - We return true if they meet, otherwise false if the loop exits without meeting. 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool hasCycle(ListNode *head) { 22 | ListNode* slow = head; 23 | ListNode* fast = head; 24 | 25 | while (fast != NULL && fast->next != NULL && fast->next->next != NULL) { 26 | slow = slow->next; 27 | fast = fast->next->next; 28 | if (slow == fast) { 29 | return true; 30 | } 31 | } 32 | return false; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Level 1/Week 07/K way merge [Heaps]/IPO/README.md: -------------------------------------------------------------------------------- 1 | # IPO 2 | 3 | **Difficulty:** Hard 4 | 5 | ## Problem Description 6 | 7 | Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. You are given n projects where the i-th project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start the corresponding project. 8 | 9 | Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. 10 | 11 | Pick at most k distinct projects from given projects to maximize your final capital, and return the maximum capital you can obtain after finishing at most k distinct projects. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] 19 | Output: 4 20 | 21 | ### Example 2 22 | Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] 23 | Output: 6 24 | 25 | --- 26 | 27 | ## Constraints 28 | 29 | - 1 <= k <= 10^5 30 | - 0 <= w <= 10^9 31 | - n == profits.length == capital.length 32 | - 1 <= n <= 10^5 33 | - 0 <= profits[i], capital[i] <= 10^4 -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/2824. Count Pairs Whose Sum is Less than Target/README.md: -------------------------------------------------------------------------------- 1 | # 2824. Count Pairs Whose Sum is Less than Target 2 | 3 | **Difficulty:** Easy 4 | **Link:** [LeetCode Problem](https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target/) 5 | 6 | --- 7 | 8 | ## 🧠 Problem Statement 9 | 10 | You are given: 11 | - A 0-indexed integer array `nums` of length `n` 12 | - An integer `target` 13 | 14 | Your task is to count the number of **pairs** `(i, j)` such that: 15 | - `0 <= i < j < n` 16 | - `nums[i] + nums[j] < target` 17 | 18 | Return the **count** of such pairs. 19 | 20 | --- 21 | 22 | ## 📌 Examples 23 | 24 | ### ✅ Example 1: 25 | ```txt 26 | Input: nums = [-1, 1, 2, 3, 1], target = 2 27 | Output: 3 28 | Explanation: 29 | The valid pairs are: 30 | 31 | (0, 1): -1 + 1 = 0 < 2 32 | 33 | (0, 2): -1 + 2 = 1 < 2 34 | 35 | (0, 4): -1 + 1 = 0 < 2 36 | ``` 37 | 38 | ### Example 2: 39 | Input: nums = [-6, 2, 5, -2, -7, -1, 3], target = -2 40 | Output: 10 41 | Explanation: 42 | Valid pairs include: 43 | 44 | (0,1), (0,3), (0,4), (0,5), (0,6) 45 | 46 | (1,4) 47 | 48 | (3,4), (3,5) 49 | 50 | (4,5), (4,6) 51 | 52 | 53 | ### Constraints 54 | 1 <= nums.length <= 50 55 | 56 | -50 <= nums[i], target <= 50 -------------------------------------------------------------------------------- /Level 0/9 Modified Binary Search/08. 0907-koko-eating-bananas/0907-koko-eating-bananas.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Helper to find the maximum element in the array 3 | int findMax(const vector& v) { 4 | int maxVal = INT_MIN; 5 | for (int i = 0; i < v.size(); i++) { 6 | maxVal = max(maxVal, v[i]); 7 | } 8 | return maxVal; 9 | } 10 | 11 | // Helper to calculate total hours needed at a given eating speed 12 | long long int calculateTotalHours(const vector& v, int hourly) { 13 | long long int totalHours = 0; 14 | for (int i = 0; i < v.size(); i++) { 15 | totalHours += ceil((double)v[i] / hourly); 16 | } 17 | return totalHours; 18 | } 19 | public: 20 | int minEatingSpeed(vector& piles, int h) { 21 | int low = 1, high = findMax(piles); 22 | 23 | while (low <= high) { 24 | int mid = (low + high) / 2; 25 | long long int totalH = calculateTotalHours(piles, mid); 26 | 27 | if (totalH <= h) { 28 | high = mid - 1; 29 | } else { 30 | low = mid + 1; 31 | } 32 | } 33 | return low; 34 | } 35 | }; -------------------------------------------------------------------------------- /Level 1/Week 02/Sliding windows/643. Maximum Average Subarray I/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach (Sliding Window): 3 | 4 | We want to find the maximum average of any contiguous subarray of length `k`. 5 | 6 | ⚙️ Logic: 7 | 1. Use two pointers: `left` and `right` to define the sliding window. 8 | 2. Accumulate the window sum while expanding the window with `right`. 9 | 3. Once the window size exceeds `k`, subtract `nums[left]` and move `left` forward. 10 | 4. When the window size is exactly `k`, compute the average and update the result. 11 | 12 | ✅ Time Complexity: O(n) 13 | ✅ Space Complexity: O(1) 14 | */ 15 | 16 | class Solution { 17 | public: 18 | double findMaxAverage(vector& nums, int k) { 19 | double window = 0; 20 | int left = 0; 21 | double averageSum = INT_MIN; 22 | 23 | for (int right = 0; right < nums.size(); right++) { 24 | window += nums[right]; 25 | 26 | if (right - left + 1 > k) { 27 | window -= nums[left]; 28 | left++; 29 | } 30 | 31 | if (right - left + 1 == k) { 32 | averageSum = max(averageSum, window / k); 33 | } 34 | } 35 | 36 | return averageSum; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Level 1/Week 04/Trees/102. Binary Tree Level Order Traversal/README.md: -------------------------------------------------------------------------------- 1 |

102. Binary Tree Level Order Traversal

Medium


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).

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: root = [3,9,20,null,null,15,7]
 8 | Output: [[3],[9,20],[15,7]]
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: root = [1]
15 | Output: [[1]]
16 | 
17 | 18 |

Example 3:

19 | 20 |
21 | Input: root = []
22 | Output: []
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • The number of nodes in the tree is in the range [0, 2000].
  • 30 |
  • -1000 <= Node.val <= 1000
  • 31 |
32 | -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/92. Reverse Linked List II/README.md: -------------------------------------------------------------------------------- 1 | # Reverse Linked List II 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes from position `left` to position `right`, and return the reversed list. 8 | 9 | --- 10 | 11 | ## Examples 12 | 13 | ### Example 1 14 | Input: head = [1,2,3,4,5], left = 2, right = 4 15 | Output: [1,4,3,2,5] 16 | 17 | ### Example 2 18 | Input: head = [5], left = 1, right = 1 19 | Output: [5] 20 | 21 | --- 22 | 23 | ## Constraints 24 | 25 | - The number of nodes in the list is `n`. 26 | - `1 <= n <= 500` 27 | - `-500 <= Node.val <= 500` 28 | - `1 <= left <= right <= n` 29 | 30 | --- 31 | 32 | ## Approach 33 | 34 | This problem can be solved using recursion: 35 | 1. Base case: if we reach the left position, start reversing 36 | 2. Recursive case: move forward until we reach the left position 37 | 3. Reverse the nodes from left to right 38 | 4. Connect the reversed portion with the rest of the list 39 | 5. Handle edge cases where left equals right 40 | 41 | The key is to track the position and reverse only the specified range while maintaining the list structure. 42 | 43 | --- 44 | -------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/1. Two Sum/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: 3 | 4 | To find two numbers in the array that add up to the given target, we use a hash map (`unordered_map`) to store each number and its index as we iterate through the array. 5 | 6 | 1. For each number `nums[i]`, we compute its complement `a = target - nums[i]`. 7 | 2. We check if this complement `a` has already been seen (i.e., exists in the map). 8 | - If it exists, we return the indices of the complement and the current number. 9 | 3. If not, we store the current number and its index in the map. 10 | 4. Since the problem guarantees exactly one solution, we return an empty vector if no solution is found by the end of the loop (though this case shouldn't occur). 11 | 12 | Time Complexity: O(n) 13 | Space Complexity: O(n) 14 | */ 15 | 16 | class Solution { 17 | public: 18 | vector twoSum(vector& nums, int target) { 19 | unordered_map mp; 20 | 21 | for (int i = 0; i < nums.size(); i++) { 22 | int a = target - nums[i]; 23 | 24 | if (mp.find(a) != mp.end()) { 25 | return {mp[a], i}; 26 | } 27 | 28 | mp[nums[i]] = i; 29 | } 30 | 31 | return {}; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Level 1/Week 04/Trees/226. Invert Binary Tree/README.md: -------------------------------------------------------------------------------- 1 |

226. Invert Binary Tree

Easy


Given the root of a binary tree, invert the tree, and return its root.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: root = [4,2,7,1,3,6,9]
 8 | Output: [4,7,2,9,6,3,1]
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: root = [2,1,3]
15 | Output: [2,3,1]
16 | 
17 | 18 |

Example 3:

19 | 20 |
21 | Input: root = []
22 | Output: []
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • The number of nodes in the tree is in the range [0, 100].
  • 30 |
  • -100 <= Node.val <= 100
  • 31 |
32 | -------------------------------------------------------------------------------- /Level 1/Week 10/Backtracking/40. Combination Sum II/README.md: -------------------------------------------------------------------------------- 1 | # Combination Sum II 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`. 8 | 9 | Each number in `candidates` may only be used **once** in the combination. 10 | 11 | **Note:** The solution set must not contain duplicate combinations. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: candidates = [10,1,2,7,6,1,5], target = 8 19 | Output: [[1,1,6],[1,2,5],[1,7],[2,6]] 20 | 21 | ### Example 2 22 | Input: candidates = [2,5,2,1,2], target = 5 23 | Output: [[1,2,2],[5]] 24 | 25 | --- 26 | 27 | ## Constraints 28 | 29 | - `1 <= candidates.length <= 100` 30 | - `1 <= candidates[i] <= 50` 31 | - `1 <= target <= 30` 32 | 33 | --- 34 | 35 | ## Approach 36 | 37 | This problem is similar to Combination Sum I but with key differences: 38 | 1. Each element can only be used once 39 | 2. We need to handle duplicates in the input array 40 | 3. We skip duplicate elements at the same level to avoid duplicate combinations 41 | 4. We use backtracking with careful duplicate handling 42 | 43 | --- 44 | -------------------------------------------------------------------------------- /Level 1/Week 02/Sliding windows/219. Contains Duplicate II/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach (Sliding Window + HashSet): 3 | 4 | We need to check if there are any duplicate elements within a window size of `k`. 5 | 6 | ⚙️ Logic: 7 | 1. Use an unordered_set to keep track of elements in the current window. 8 | 2. Iterate through the array with a `right` pointer. 9 | 3. If `nums[right]` already exists in the set → we found a duplicate within range → return true. 10 | 4. Insert the current element into the set. 11 | 5. If window size exceeds `k`, remove the element at `left` and move `left` forward to shrink the window. 12 | 13 | ✅ Time Complexity: O(n) 14 | ✅ Space Complexity: O(k) 15 | */ 16 | 17 | class Solution { 18 | public: 19 | bool containsNearbyDuplicate(vector& nums, int k) { 20 | unordered_set window; 21 | int left = 0; 22 | for (int right = 0; right < nums.size(); right++) { 23 | if (window.find(nums[right]) != window.end()) { 24 | return true; 25 | } 26 | 27 | window.insert(nums[right]); 28 | 29 | if (right - left + 1 > k) { 30 | window.erase(nums[left]); 31 | left++; 32 | } 33 | } 34 | return false; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Pre-Requisites/ReadME.md: -------------------------------------------------------------------------------- 1 | ### 🔰 Basics 2 | > *Languages don’t matter in DSA – they’re just tools. Pick the one you’re most comfortable with!* 3 | 4 | - **C++ Basics** 5 | - [English Playlist](https://www.youtube.com/watch?v=EAR7De6Goz4&list=PLgUwDviBIf0oF6QL8m22w1hIDC1vJ_BHz) 6 | - [Urdu/Hindi Playlist](https://youtu.be/yGB9jhsEsr8?si=oQewu7IGXINd_HXV) 7 | 8 | - **Python Basics** 9 | - [Crash Course](https://youtu.be/vLqTf2b6GZw?si=m3_VkDBLq6q3ESwv) 10 | 11 | - **Java Basics** 12 | - [Learn Java Fundamentals](https://read.learnyard.com/java-fundamentals/what-is-java) 13 | 14 | - **OOP Fundamentals** 15 | 1. [Part 1](https://youtu.be/i_5pvt7ag7E?si=WWkWlrFLgPngBJT_) 16 | 2. [Part 2](https://youtu.be/b3GccK5_KSQ?si=gII4wBcYCx_eK91B) 17 | 18 | --- 19 | 20 | ### ✅ Must‑Have 21 | 22 | - **Time & Space Complexity** 23 | [Understanding Complexity Analysis](https://www.youtube.com/watch?v=FPu9Uld7W-E&list=PLgUwDviBIf0oF6QL8m22w1hIDC1vJ_BHz&index=5) 24 | 25 | - **C++ STL Introduction** 26 | [STL Deep Dive](https://www.youtube.com/watch?v=RRVYpIET_RU&list=PLgUwDviBIf0oF6QL8m22w1hIDC1vJ_BHz) 27 | 28 | - **What are Online Judges (Leetcode, Codeforces, etc. )** 29 | [Overview & Setup](https://read.learnyard.com/dsa/oj-wwh) 30 | -------------------------------------------------------------------------------- /Level 0/8 Trees/07. 0098-validate-binary-search-tree/README.md: -------------------------------------------------------------------------------- 1 | # 98. Validate Binary Search Tree 2 | 3 | ## Problem Description 4 | 5 | Given the `root` of a binary tree, *determine if it is a valid binary search tree (BST)*. 6 | 7 | A **valid BST** is defined as follows: 8 | 9 | - The left subtree of a node contains only nodes with keys **less than** the node's key. 10 | - The right subtree of a node contains only nodes with keys **greater than** the node's key. 11 | - Both the left and right subtrees must also be binary search trees. 12 | 13 | ## Examples 14 | 15 | ### Example 1: 16 | ![Example 1](https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg) 17 | 18 | **Input:** `root = [2,1,3]` 19 | 20 | **Output:** `true` 21 | 22 | ### Example 2: 23 | ![Example 2](https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg) 24 | 25 | **Input:** `root = [5,1,4,null,null,3,6]` 26 | 27 | **Output:** `false` 28 | 29 | **Explanation:** The root node's value is 5 but its right child's value is 4. 30 | 31 | ## Constraints 32 | 33 | - The number of nodes in the tree is in the range `[1, 10^4]`. 34 | - `-2^31 <= Node.val <= 2^31 - 1` 35 | 36 | ## Related Topics 37 | 38 | - Tree 39 | - Depth-First Search 40 | - Binary Search Tree 41 | - Binary Tree 42 | 43 | ## Difficulty 44 | 45 | Medium 46 | -------------------------------------------------------------------------------- /Level 0/9 Modified Binary Search/05. 0081-search-in-rotated-sorted-array-ii/0081-search-in-rotated-sorted-array-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool search(vector& nums, int target) { 4 | int left = 0, right = nums.size() - 1; 5 | 6 | while (left <= right) { 7 | int mid = left + (right - left) / 2; 8 | 9 | if (nums[mid] == target) return true; 10 | 11 | // If we can't decide due to duplicates 12 | if (nums[left] == nums[mid] && nums[mid] == nums[right]) { 13 | left++; 14 | right--; 15 | } 16 | 17 | // Left half is sorted 18 | else if (nums[left] <= nums[mid]) { 19 | if (nums[left] <= target && target < nums[mid]) { 20 | right = mid - 1; 21 | } else { 22 | left = mid + 1; 23 | } 24 | } 25 | // Right half is sorted 26 | else { 27 | if (nums[mid] < target && target <= nums[right]) { 28 | left = mid + 1; 29 | } else { 30 | right = mid - 1; 31 | } 32 | } 33 | } 34 | 35 | return false; 36 | } 37 | }; -------------------------------------------------------------------------------- /Level 0/7 Sliding Window/07. 0567-permutation-in-string/README.md: -------------------------------------------------------------------------------- 1 |

567. Permutation in String

Medium


Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

2 | 3 |

In other words, return true if one of s1's permutations is the substring of s2.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: s1 = "ab", s2 = "eidbaooo"
10 | Output: true
11 | Explanation: s2 contains one permutation of s1 ("ba").
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: s1 = "ab", s2 = "eidboaoo"
18 | Output: false
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • 1 <= s1.length, s2.length <= 104
  • 26 |
  • s1 and s2 consist of lowercase English letters.
  • 27 |
28 | -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/26. Remove Duplicates from Sorted Array/README.md: -------------------------------------------------------------------------------- 1 | # 26. Remove Duplicates from Sorted Array 2 | 3 | **Difficulty:** Easy 4 | **Link:** [LeetCode Problem](https://leetcode.com/problems/remove-duplicates-from-sorted-array) 5 | 6 | --- 7 | 8 | ## 🧠 Problem Statement 9 | 10 | You are given a **sorted** array `nums` in **non-decreasing order**. 11 | Your task is to **remove duplicates in-place** so that each element appears **only once**, and return the new length `k` (i.e., number of unique elements). 12 | 13 | The first `k` elements in `nums` should hold the unique elements in their original order. 14 | The elements beyond `k` can be anything — they are not checked. 15 | 16 | --- 17 | 18 | ## 📌 Examples 19 | 20 | ### ✅ Example 1: 21 | ```txt 22 | Input: nums = [1, 1, 2] 23 | Output: 2, nums = [1, 2, _] 24 | Explanation: The function returns k = 2. The first two elements are the unique ones. 25 | ``` 26 | 27 | ### ✅ Example 2: 28 | 29 | Input: nums = [0,0,1,1,1,2,2,3,3,4] 30 | Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] 31 | Explanation: Return k = 5. The first 5 elements of nums hold all the unique numbers. 32 | 33 | ### Constraints 34 | 35 | 1 <= nums.length <= 3 * 10^4 36 | 37 | -100 <= nums[i] <= 100 38 | 39 | The array nums is sorted in non-decreasing order. -------------------------------------------------------------------------------- /Level 1/Week 02/Sliding windows/567. Permutation in String/README.md: -------------------------------------------------------------------------------- 1 |

567. Permutation in String

Medium


Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

2 | 3 |

In other words, return true if one of s1's permutations is the substring of s2.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: s1 = "ab", s2 = "eidbaooo"
10 | Output: true
11 | Explanation: s2 contains one permutation of s1 ("ba").
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: s1 = "ab", s2 = "eidboaoo"
18 | Output: false
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • 1 <= s1.length, s2.length <= 104
  • 26 |
  • s1 and s2 consist of lowercase English letters.
  • 27 |
28 | -------------------------------------------------------------------------------- /Level 1/Week 07/K way merge [Heaps]/IPO/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: 3 | 4 | Use two heaps: 5 | - Min heap for projects by capital 6 | - Max heap for available projects by profit 7 | 8 | At each step, move all projects affordable with current capital to the max heap, then pick the most profitable one. 9 | 10 | Time Complexity: O(n log n + k log n) 11 | Space Complexity: O(n) 12 | */ 13 | 14 | #include 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | class Solution { 20 | public: 21 | int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { 22 | int n = profits.size(); 23 | vector> projects; 24 | for (int i = 0; i < n; ++i) { 25 | projects.push_back({capital[i], profits[i]}); 26 | } 27 | sort(projects.begin(), projects.end()); 28 | priority_queue maxProfit; 29 | int idx = 0; 30 | for (int i = 0; i < k; ++i) { 31 | while (idx < n && projects[idx].first <= w) { 32 | maxProfit.push(projects[idx].second); 33 | ++idx; 34 | } 35 | if (maxProfit.empty()) break; 36 | w += maxProfit.top(); 37 | maxProfit.pop(); 38 | } 39 | return w; 40 | } 41 | }; -------------------------------------------------------------------------------- /Level 0/7 Sliding Window/02. 0643-maximum-average-subarray-i/README.md: -------------------------------------------------------------------------------- 1 |

643. Maximum Average Subarray I

Easy


You are given an integer array nums consisting of n elements, and an integer k.

2 | 3 |

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [1,12,-5,-6,50,3], k = 4
10 | Output: 12.75000
11 | Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums = [5], k = 1
18 | Output: 5.00000
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • n == nums.length
  • 26 |
  • 1 <= k <= n <= 105
  • 27 |
  • -104 <= nums[i] <= 104
  • 28 |
29 | -------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/242. Valid Anagram/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: 3 | We determine whether two strings `s` and `t` are anagrams by comparing the frequency of each character. 4 | 5 | 1. First, check if the lengths of both strings are different. 6 | - If they are, return false immediately (they can't be anagrams). 7 | 8 | 2. Use two hash maps (`unordered_map`) to count the frequency of each character in both strings: 9 | - `countS` for string `s` 10 | - `countT` for string `t` 11 | 12 | 3. Iterate through the strings and update the counts. 13 | 14 | 4. After the loop, compare the two maps: 15 | - If they are equal, the strings are anagrams → return true. 16 | - Otherwise, return false. 17 | 18 | Time Complexity: O(n), where n is the length of the strings. 19 | Space Complexity: O(1) (constant, since the alphabet size is fixed and small, though technically O(k) where k is the number of unique characters). 20 | */ 21 | 22 | class Solution { 23 | public: 24 | bool isAnagram(string s, string t) { 25 | if (s.size() != t.size()) return false; 26 | 27 | unordered_map countS, countT; 28 | for (int i = 0; i < s.size(); i++) { 29 | countS[s[i]]++; 30 | countT[t[i]]++; 31 | } 32 | return countS == countT; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Level 1/Week 04/Trees/110. Balanced Binary Tree/README.md: -------------------------------------------------------------------------------- 1 |

110. Balanced Binary Tree

Easy


Given a binary tree, determine if it is height-balanced.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: root = [3,9,20,null,null,15,7]
 8 | Output: true
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: root = [1,2,2,3,3,null,null,4,4]
15 | Output: false
16 | 
17 | 18 |

Example 3:

19 | 20 |
21 | Input: root = []
22 | Output: true
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • The number of nodes in the tree is in the range [0, 5000].
  • 30 |
  • -104 <= Node.val <= 104
  • 31 |
32 | -------------------------------------------------------------------------------- /Level 1/Week 06/Stack/739. Daily Temperatures/README.md: -------------------------------------------------------------------------------- 1 |

739. Daily Temperatures

Medium


Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

2 | 3 |

 

4 |

Example 1:

5 |
Input: temperatures = [73,74,75,71,69,72,76,73]
 6 | Output: [1,1,4,2,1,1,0,0]
 7 | 

Example 2:

8 |
Input: temperatures = [30,40,50,60]
 9 | Output: [1,1,1,0]
10 | 

Example 3:

11 |
Input: temperatures = [30,60,90]
12 | Output: [1,1,0]
13 | 
14 |

 

15 |

Constraints:

16 | 17 |
    18 |
  • 1 <= temperatures.length <= 105
  • 19 |
  • 30 <= temperatures[i] <= 100
  • 20 |
21 | -------------------------------------------------------------------------------- /Level 0/7 Sliding Window/03. 0219-contains-duplicate-ii/README.md: -------------------------------------------------------------------------------- 1 |

219. Contains Duplicate II

Easy


Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: nums = [1,2,3,1], k = 3
 8 | Output: true
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: nums = [1,0,1,1], k = 1
15 | Output: true
16 | 
17 | 18 |

Example 3:

19 | 20 |
21 | Input: nums = [1,2,3,1,2,3], k = 2
22 | Output: false
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 1 <= nums.length <= 105
  • 30 |
  • -109 <= nums[i] <= 109
  • 31 |
  • 0 <= k <= 105
  • 32 |
33 | -------------------------------------------------------------------------------- /Level 1/Week 11/Dynamic Programming/322. Coin Change/README.md: -------------------------------------------------------------------------------- 1 | # Coin Change 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. 8 | 9 | Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return `-1`. 10 | 11 | You may assume that you have an infinite number of each kind of coin. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: coins = [1,3,4], amount = 6 19 | Output: 2 20 | Explanation: 6 = 3 + 3 21 | 22 | ### Example 2 23 | Input: coins = [2], amount = 3 24 | Output: -1 25 | 26 | ### Example 3 27 | Input: coins = [1], amount = 0 28 | Output: 0 29 | 30 | --- 31 | 32 | ## Constraints 33 | 34 | - `1 <= coins.length <= 12` 35 | - `1 <= coins[i] <= 2^31 - 1` 36 | - `0 <= amount <= 10^4` 37 | 38 | --- 39 | 40 | ## Approaches 41 | 42 | This problem can be solved using 4 different dynamic programming approaches: 43 | 44 | 1. **Recursion** - Direct recursive implementation 45 | 2. **Memoization** - Top-down DP with caching 46 | 3. **Tabulation** - Bottom-up DP with array 47 | 4. **Space Optimization** - Optimized space complexity 48 | 49 | --- 50 | -------------------------------------------------------------------------------- /Level 1/Week 02/Sliding windows/219. Contains Duplicate II/README.md: -------------------------------------------------------------------------------- 1 |

219. Contains Duplicate II

Easy


Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: nums = [1,2,3,1], k = 3
 8 | Output: true
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: nums = [1,0,1,1], k = 1
15 | Output: true
16 | 
17 | 18 |

Example 3:

19 | 20 |
21 | Input: nums = [1,2,3,1,2,3], k = 2
22 | Output: false
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 1 <= nums.length <= 105
  • 30 |
  • -109 <= nums[i] <= 109
  • 31 |
  • 0 <= k <= 105
  • 32 |
33 | -------------------------------------------------------------------------------- /Level 1/Week 12/Graph/130. Surrounded Regions/README.md: -------------------------------------------------------------------------------- 1 | # Surrounded Regions 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given an `m x n` matrix `board` containing `'X'` and `'O'`, *capture all regions that are 4-directionally surrounded by* `'X'`. 8 | 9 | A region is **captured** by flipping all `'O'`'s into `'X'`'s in that surrounded region. 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] 17 | Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] 18 | 19 | ### Example 2 20 | Input: board = [["X"]] 21 | Output: [["X"]] 22 | 23 | --- 24 | 25 | ## Constraints 26 | 27 | - `m == board.length` 28 | - `n == board[i].length` 29 | - `1 <= m, n <= 200` 30 | - `board[i][j]` is `'X'` or `'O'`. 31 | 32 | --- 33 | 34 | ## Approach 35 | 36 | This problem can be solved using DFS from the boundaries: 37 | 1. Start DFS from all 'O' cells on the boundaries 38 | 2. Mark all 'O' cells that are connected to boundaries as safe 39 | 3. Flip all remaining 'O' cells to 'X' 40 | 4. The key insight is to work backwards from the boundaries 41 | 42 | The key insight is that only 'O' cells connected to boundaries cannot be surrounded, so we mark them as safe and flip the rest. 43 | 44 | --- 45 | -------------------------------------------------------------------------------- /Level 0/8 Trees/09. 0105-construct-binary-tree-from-preorder-and-inorder-traversal/README.md: -------------------------------------------------------------------------------- 1 | # 105. Construct Binary Tree from Preorder and Inorder Traversal 2 | 3 | ## Problem Description 4 | 5 | Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return *the binary tree*. 6 | 7 | ## Examples 8 | 9 | ### Example 1: 10 | ![Example 1](https://assets.leetcode.com/uploads/2021/02/19/tree.jpg) 11 | 12 | **Input:** `preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]` 13 | 14 | **Output:** `[3,9,20,null,null,15,7]` 15 | 16 | ### Example 2: 17 | 18 | **Input:** `preorder = [-1], inorder = [-1]` 19 | 20 | **Output:** `[-1]` 21 | 22 | ## Constraints 23 | 24 | - `1 <= preorder.length <= 3000` 25 | - `inorder.length == preorder.length` 26 | - `-3000 <= preorder[i], inorder[i] <= 3000` 27 | - `preorder` and `inorder` consist of **unique** values. 28 | - Each value of `inorder` also appears in `preorder`. 29 | - `preorder` is **guaranteed** to be the preorder traversal of the tree. 30 | - `inorder` is **guaranteed** to be the inorder traversal of the tree. 31 | 32 | ## Related Topics 33 | 34 | - Array 35 | - Hash Table 36 | - Divide and Conquer 37 | - Tree 38 | - Binary Tree 39 | 40 | ## Difficulty 41 | 42 | Medium 43 | -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/2824. Count Pairs Whose Sum is Less than Target/code.cpp: -------------------------------------------------------------------------------- 1 | // ✅ Approach: Two Pointer Technique 2 | // 3 | // 1. Sort the array to make it easier to apply the two-pointer strategy. 4 | // 2. Use two pointers: 5 | // - l = 0 (left/start of array) 6 | // - r = nums.size() - 1 (right/end of array) 7 | // 3. While l < r: 8 | // - If nums[l] + nums[r] < target, it means all elements from l to r-1 9 | // will also form valid pairs with nums[l] (since the array is sorted). 10 | // So we add (r - l) to the count and move l++. 11 | // - If the sum is greater than or equal to target, we move r-- to try smaller values. 12 | // 4. This avoids checking all pairs explicitly and improves efficiency. 13 | // 14 | // ✅ Time Complexity: O(n log n) due to sorting 15 | // ✅ Space Complexity: O(1) — constant extra space 16 | 17 | class Solution { 18 | public: 19 | int countPairs(vector& nums, int target) { 20 | sort(nums.begin(), nums.end()); 21 | int l = 0; 22 | int r = nums.size() - 1; 23 | int cnt = 0; 24 | while (l < r) { 25 | if (nums[l] + nums[r] < target) { 26 | cnt += r - l; 27 | l++; 28 | } else { 29 | r--; 30 | } 31 | } 32 | return cnt; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Level 1/Week 03/LinkedList/21. Merge Two Sorted Lists/code.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Approach: 3 | * We use an **iterative two-pointer technique** to merge two sorted linked lists. 4 | * - Create a dummy node to serve as the start of the merged list. 5 | * - Use a pointer `cur` to build the new list by comparing the current nodes of `list1` and `list2`. 6 | * - At each step, attach the node with the smaller value to `cur->next`, then move the corresponding list forward. 7 | * - Continue this process until one of the lists becomes null. 8 | * - Finally, append the remaining part of the non-null list (if any) to `cur->next`. 9 | * - Return `dummy.next` which points to the head of the merged sorted list. 10 | */ 11 | 12 | class Solution { 13 | public: 14 | ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { 15 | ListNode dummy(0); 16 | ListNode* cur = &dummy; 17 | 18 | while (list1 && list2) { 19 | if (list1->val < list2->val) { 20 | cur->next = list1; 21 | list1 = list1->next; 22 | } else { 23 | cur->next = list2; 24 | list2 = list2->next; 25 | } 26 | cur = cur->next; 27 | } 28 | 29 | cur->next = (list1 != nullptr) ? list1 : list2; 30 | return dummy.next; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Common/Math/Odd/README.md: -------------------------------------------------------------------------------- 1 | # 🔢 Check if a Number is Odd – C++ Solutions 2 | 3 | ### 💡 What is an Odd Number? 4 | 5 | An **odd number** is any number that **cannot be divided evenly by 2**. 6 | This means there will always be a **remainder of 1** when you divide it by 2. 7 | 8 | 🧠 Examples: 9 | - 3 → 3 % 2 = 1 ✅ Odd 10 | - 6 → 6 % 2 = 0 ❌ Not Odd 11 | 12 | --- 13 | 14 | ## 📘 What’s Inside This File? 15 | 16 | This program explores **four different ways** to check if a number is odd in C++. 17 | 18 | | Approach | Description | 19 | |---------|-------------| 20 | | 1 | Using modulo `%` operator | 21 | | 2 | Using bitwise AND `&` to inspect binary form | 22 | | 3 | Using integer division and reverse calculation | 23 | | 4 | Recursive subtraction down to 0 or 1 | 24 | 25 | --- 26 | 27 | ## 🗂 File Structure 28 | 29 | Odd/ 30 | │ 31 | ├── odd_number.cpp # All approaches with full comments 32 | ├── README.md # This file 33 | 34 | └── Makefile # Build and run commands 35 | --- 36 | 37 | ## 🔍 Sample Usage 38 | 39 | ```cpp 40 | #include 41 | using namespace std; 42 | 43 | int main() { 44 | int n = 7; 45 | 46 | if (odd(n)) { 47 | cout << n << " is odd\n"; 48 | } else { 49 | cout << n << " is even\n"; 50 | } 51 | 52 | // Try others: 53 | // odd_bitwise(n), odd_division(n), odd_recursive(n) 54 | } -------------------------------------------------------------------------------- /Level 0/1 Simulation - Strings/README.md: -------------------------------------------------------------------------------- 1 | ## 📚 List of Problems 2 | 3 | 1. [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description/) 4 | 2. [Reverse String](https://leetcode.com/problems/reverse-string/description/) 5 | 3. [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/description/) 6 | 4. [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/description/) 7 | 5. [Valid Anagram](https://leetcode.com/problems/valid-anagram/description/) 8 | 6. [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) 9 | 7. [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/description/) 10 | 8. [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/description/) 11 | 9. [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/) 12 | 10. [Is Subsequence](https://leetcode.com/problems/is-subsequence/description/) 13 | 11. [Rotate String](https://leetcode.com/problems/rotate-string) 14 | --- 15 | 16 | ## 💡 Suggestions 17 | 18 | - Make sure to prepare your notes alongside solving each problem. 19 | - Don’t spend more than 30–40 minutes on a single problem. 20 | - If you’re stuck on a problem, search on YouTube using the problem number. 21 | - Try to solve a problem in multiple ways. 22 | -------------------------------------------------------------------------------- /Level 0/8 Trees/02. 0572-subtree-of-another-tree/README.md: -------------------------------------------------------------------------------- 1 | # 572. Subtree of Another Tree 2 | 3 | ## Problem Description 4 | 5 | Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. 6 | 7 | A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. 8 | 9 | ## Examples 10 | 11 | ### Example 1: 12 | ![Example 1](https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg) 13 | 14 | **Input:** `root = [3,4,5,1,2], subRoot = [4,1,2]` 15 | 16 | **Output:** `true` 17 | 18 | ### Example 2: 19 | ![Example 2](https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg) 20 | 21 | **Input:** `root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]` 22 | 23 | **Output:** `false` 24 | 25 | ## Constraints 26 | 27 | - The number of nodes in the `root` tree is in the range `[1, 2000]`. 28 | - The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. 29 | - `-10^4 <= root.val <= 10^4` 30 | - `-10^4 <= subRoot.val <= 10^4` 31 | 32 | ## Related Topics 33 | 34 | - Tree 35 | - Depth-First Search 36 | - String Matching 37 | - Binary Tree 38 | - Hash Function 39 | 40 | ## Difficulty 41 | 42 | Easy 43 | -------------------------------------------------------------------------------- /Level 1/Week 04/Trees/104. Maximum Depth of Binary Tree/code.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Approach: 3 | * The goal is to find the maximum depth (or height) of a binary tree. 4 | * 5 | * This is done using recursion (Depth-First Search): 6 | * 1. If the current node is NULL, return 0 (base case). 7 | * 2. Recursively find the maximum depth of the left and right subtrees. 8 | * 3. Return the greater of the two depths plus 1 (for the current node). 9 | * 10 | * Time Complexity: O(n), where n is the number of nodes in the tree (each node is visited once). 11 | * Space Complexity: O(h), where h is the height of the tree due to the recursion stack. 12 | */ 13 | 14 | /** 15 | * Definition for a binary tree node. 16 | * struct TreeNode { 17 | * int val; 18 | * TreeNode *left; 19 | * TreeNode *right; 20 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 21 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 22 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 23 | * }; 24 | */ 25 | class Solution { 26 | public: 27 | int maxDepth(TreeNode* root) { 28 | if (root == NULL) { 29 | return 0; 30 | } 31 | int lefth = maxDepth(root->left); 32 | int righth = maxDepth(root->right); 33 | return max(lefth, righth) + 1; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Level 1/Week 06/Queue/862. Shortest Subarray with Sum at Least K/README.md: -------------------------------------------------------------------------------- 1 |

862. Shortest Subarray with Sum at Least K

Hard


Given an integer array nums and an integer k, return the length of the shortest non-empty subarray whose sum is at least k. If there is no such subarray, return -1.

2 | 3 |

A subarray is a contiguous part of an array.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [1], k = 1
10 | Output: 1
11 | 
12 | 13 |

Example 2:

14 | 15 |
16 | Input: nums = [1,2], k = 4
17 | Output: -1
18 | 
19 | 20 |

Example 3:

21 | 22 |
23 | Input: nums = [2,-1,2], k = 3
24 | Output: 3
25 | 
26 | 27 |

 

28 |

Constraints:

29 | 30 |
    31 |
  • 1 <= nums.length <= 105
  • 32 |
  • -105 <= nums[i] <= 105
  • 33 |
  • 1 <= k <= 109
  • 34 |
-------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/23. Merge k Sorted Lists/README.md: -------------------------------------------------------------------------------- 1 | # Merge k Sorted Lists 2 | 3 | **Difficulty:** Hard 4 | 5 | ## Problem Description 6 | 7 | You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order. 8 | 9 | *Merge all the linked-lists into one sorted linked-list and return it.* 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: lists = [[1,4,5],[1,3,4],[2,6]] 17 | Output: [1,1,2,3,4,4,5,6] 18 | 19 | ### Example 2 20 | Input: lists = [] 21 | Output: [] 22 | 23 | ### Example 3 24 | Input: lists = [[]] 25 | Output: [] 26 | 27 | --- 28 | 29 | ## Constraints 30 | 31 | - `k == lists.length` 32 | - `0 <= k <= 10^4` 33 | - `0 <= lists[i].length <= 500` 34 | - `-10^4 <= lists[i][j] <= 10^4` 35 | - `lists[i]` is sorted in **ascending order**. 36 | - The sum of `lists[i].length` will not exceed `10^4`. 37 | 38 | --- 39 | 40 | ## Approach 41 | 42 | This problem can be solved using divide and conquer with recursion: 43 | 1. Base case: if there are 0 or 1 lists, return the list or empty 44 | 2. Recursive case: divide the lists into two halves 45 | 3. Recursively merge each half 46 | 4. Merge the two merged halves using the two-list merge approach 47 | 5. Return the final merged list 48 | 49 | The recursive approach naturally breaks down the problem into smaller subproblems. 50 | 51 | --- 52 | -------------------------------------------------------------------------------- /Level 1/Week 07/K way merge [Heaps]/Find Median from Data Stream/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: 3 | 4 | Use two heaps: 5 | - Max heap for lower half 6 | - Min heap for upper half 7 | 8 | Balance the heaps so their sizes differ by at most one. Median is either the top of one heap or the average of the tops. 9 | 10 | Time Complexity: O(log n) per insertion, O(1) for median 11 | Space Complexity: O(n) 12 | */ 13 | 14 | #include 15 | using namespace std; 16 | 17 | class MedianFinder { 18 | priority_queue maxHeap; // lower half 19 | priority_queue, greater> minHeap; // upper half 20 | public: 21 | MedianFinder() {} 22 | void addNum(int num) { 23 | if (maxHeap.empty() || num <= maxHeap.top()) { 24 | maxHeap.push(num); 25 | } else { 26 | minHeap.push(num); 27 | } 28 | // Balance 29 | if (maxHeap.size() > minHeap.size() + 1) { 30 | minHeap.push(maxHeap.top()); maxHeap.pop(); 31 | } else if (minHeap.size() > maxHeap.size()) { 32 | maxHeap.push(minHeap.top()); minHeap.pop(); 33 | } 34 | } 35 | double findMedian() { 36 | if (maxHeap.size() == minHeap.size()) { 37 | return (maxHeap.top() + minHeap.top()) / 2.0; 38 | } else { 39 | return maxHeap.top(); 40 | } 41 | } 42 | }; -------------------------------------------------------------------------------- /Level 1/Week 09/Greedy/53. Maximum Subarray/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: Kadane's Algorithm (Greedy) 3 | 4 | This is the classic maximum subarray problem that can be solved using Kadane's algorithm. 5 | The greedy approach is to keep a running sum and reset it to the current element 6 | when it becomes negative, as a negative prefix would only decrease the sum. 7 | 8 | Algorithm: 9 | 1. Initialize maxSum to the first element and currentMax to 0 10 | 2. For each element: 11 | - If currentMax is negative, start a new subarray from current element 12 | - Otherwise, extend the current subarray by adding current element 13 | - Update maxSum if currentMax is greater 14 | 15 | Time Complexity: O(n) 16 | Space Complexity: O(1) 17 | */ 18 | 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | class Solution { 24 | public: 25 | int maxSubArray(vector& nums) { 26 | int maxSum = nums[0]; 27 | int currentMax = 0; 28 | 29 | for (int i = 0; i < nums.size(); i++){ 30 | if (currentMax < 0){ 31 | currentMax = nums[i]; 32 | } else { 33 | currentMax = nums[i] + currentMax; 34 | } 35 | 36 | if (currentMax > maxSum){ 37 | maxSum = currentMax; 38 | } 39 | } 40 | return maxSum; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Common/Math/Even/README.md: -------------------------------------------------------------------------------- 1 | # 🔢 Check if a Number is Even – C++ Solutions 2 | 3 | ### 💡 What is an Even Number? 4 | 5 | An **even number** is a number that can be **divided by 2 without any remainder**. 6 | In other words, if you divide it by 2 and there's nothing left over, it’s even. 7 | 8 | 🧠 Examples: 9 | - 4 → 4 % 2 = 0 ✅ Even 10 | - 9 → 9 % 2 = 1 ❌ Not Even 11 | 12 | --- 13 | 14 | ## 📘 What’s Inside This File? 15 | 16 | This program demonstrates **four different approaches** to check if a number is even in C++. 17 | 18 | | Approach | Description | 19 | |---------|-------------| 20 | | 1 | Using modulo (`%`) operator | 21 | | 2 | Using bitwise AND (`&`) to check the least significant bit | 22 | | 3 | Using integer division logic | 23 | | 4 | Recursive subtraction method | 24 | 25 | --- 26 | 27 | ## 🗂 File Structure 28 | 29 | Even/ 30 | │ 31 | ├── even_number.cpp # All approaches with comments 32 | ├── README.md # This file 33 | 34 | └── Makefile # Build and run the program 35 | --- 36 | 37 | ## 🔍 Sample Usage 38 | 39 | ```cpp 40 | #include 41 | using namespace std; 42 | 43 | int main() { 44 | int n = 10; 45 | 46 | if (even(n)) { 47 | cout << n << " is even\n"; 48 | } else { 49 | cout << n << " is odd\n"; 50 | } 51 | 52 | // Try others: 53 | // even_bitwise(n), even_division(n), even_recursive(n) 54 | } -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/26. Remove Duplicates from Sorted Array/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ✅ Approach: Two Pointer Technique 3 | 4 | We're given a **sorted array**, and we need to **remove duplicates in-place**, returning the length of the new array with unique elements at the beginning. 5 | 6 | 💡 Why Two Pointers? 7 | Since the array is sorted, all duplicates will be **next to each other**. 8 | We can use two pointers: 9 | - `i` → Points to the **last unique element** found 10 | - `j` → Goes through the array to find **new unique elements** 11 | 12 | 🔄 How it works: 13 | 1. Start with `i = 0` (first element is always unique) 14 | 2. Move `j` from index 1 to end: 15 | - If `nums[j] != nums[i]`, it means a new unique element is found 16 | - So, place it at `i+1`, and move `i` forward 17 | 3. Finally, return `i + 1` as the count of unique elements 18 | 19 | ✅ This modifies the input array to have all unique elements at the start. 20 | 📦 Time: O(n), Space: O(1) — done in-place without extra space. 21 | */ 22 | class Solution { 23 | public: 24 | int removeDuplicates(vector& nums) { 25 | int n = nums.size(); 26 | int i =0; 27 | for(int j = i+1 ; j 20 | using namespace std; 21 | 22 | class Solution { 23 | public: 24 | int canCompleteCircuit(vector& gas, vector& cost) { 25 | int n = gas.size(); 26 | int totalTank = 0; 27 | int currentTank = 0; 28 | int startingStation = 0; 29 | 30 | for (int i = 0; i < n; i++) { 31 | totalTank += gas[i] - cost[i]; 32 | currentTank += gas[i] - cost[i]; 33 | 34 | if (currentTank < 0) { 35 | startingStation = i + 1; 36 | currentTank = 0; 37 | } 38 | } 39 | 40 | return totalTank >= 0 ? startingStation : -1; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Level 0/0 Simulation - Arrays/README.md: -------------------------------------------------------------------------------- 1 | ## 📚 List of Problems 2 | 3 | 1. [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/description/) 4 | 2. [Find the Highest Altitude](https://leetcode.com/problems/find-the-highest-altitude/) 5 | 3. [Final Value of Variable After Performing Operations](https://leetcode.com/problems/final-value-of-variable-after-performing-operations/description/) 6 | 4. [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/description/) 7 | 5. [Concatenation of Array](https://leetcode.com/problems/concatenation-of-array/) 8 | 6. [Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs/description/) 9 | 7. [Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/description/) 10 | 8. [Move Zeroes](https://leetcode.com/problems/move-zeroes/description/) 11 | 9. [Maximum Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) 12 | 10. [Left Rotate an array by one place](https://leetcode.com/problems/rotate-array/) 13 | 14 | --- 15 | 16 | ## 💡 Suggestions 17 | 18 | - Make sure to prepare your notes alongside solving each problem. 19 | - Don’t spend more than 30–40 minutes on a single problem. 20 | - If you’re stuck on a problem, search on YouTube using the problem number. 21 | - Try to solve a problem in multiple ways. 22 | -------------------------------------------------------------------------------- /Level 0/10 Backtracking/05. 090-subsets-ii/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vector> result; 4 | 5 | void backtrack(vector& nums, vector& current, int start) { 6 | // Add current subset to result 7 | result.push_back(current); 8 | 9 | // Try all possible elements starting from 'start' 10 | for (int i = start; i < nums.size(); i++) { 11 | // Skip duplicates at the same level to avoid duplicate subsets 12 | if (i > start && nums[i] == nums[i-1]) { 13 | continue; 14 | } 15 | 16 | // Make choice: include nums[i] 17 | current.push_back(nums[i]); 18 | 19 | // Recurse with next element 20 | backtrack(nums, current, i + 1); 21 | 22 | // Backtrack: remove nums[i] 23 | current.pop_back(); 24 | } 25 | } 26 | 27 | public: 28 | vector> subsetsWithDup(vector& nums) { 29 | // Sort nums to handle duplicates efficiently 30 | sort(nums.begin(), nums.end()); 31 | 32 | vector current; 33 | backtrack(nums, current, 0); 34 | return result; 35 | } 36 | }; 37 | 38 | /* 39 | Time Complexity: O(2^n) where n is the length of nums 40 | Space Complexity: O(n) for recursion stack 41 | */ -------------------------------------------------------------------------------- /Level 1/Week 02/Sliding windows/3. Longest Substring Without Repeating Characters/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach (Sliding Window + HashSet): 3 | 4 | We aim to find the length of the longest substring without repeating characters. 5 | 6 | ⚙️ Logic: 7 | 1. Use a sliding window with two pointers: `left` and `right`. 8 | 2. Maintain a hash set to track characters in the current window. 9 | 3. As you expand `right`, check if `s[right]` is already in the window: 10 | - If it is, shrink the window from the left by removing `s[left]` until it's unique again. 11 | 4. Update `maxLen` with the size of the current valid window. 12 | 13 | ✅ Time Complexity: O(n) 14 | ✅ Space Complexity: O(min(n, charset)) – where charset is the size of the character set (e.g., 26 for lowercase, 128 for ASCII) 15 | */ 16 | 17 | class Solution { 18 | public: 19 | int lengthOfLongestSubstring(string s) { 20 | unordered_set window; 21 | int left = 0; 22 | int maxLen = 0; 23 | for (int right = 0; right < s.size(); right++) { 24 | while (window.find(s[right]) != window.end()) { 25 | window.erase(s[left]); 26 | left++; 27 | } 28 | window.insert(s[right]); 29 | int windowSize = right - left + 1; 30 | maxLen = max(maxLen, windowSize); 31 | } 32 | return maxLen; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Level 1/Week 06/Stack/84. Largest Rectangle in Histogram/README.md: -------------------------------------------------------------------------------- 1 |

84. Largest Rectangle in Histogram

Hard


Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: heights = [2,1,5,6,2,3]
 8 | Output: 10
 9 | Explanation: The above is a histogram where width of each bar is 1.
10 | The largest rectangle is shown in the red area, which has an area = 10 units.
11 | 
12 | 13 |

Example 2:

14 | 15 |
16 | Input: heights = [2,4]
17 | Output: 4
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= heights.length <= 105
  • 25 |
  • 0 <= heights[i] <= 104
  • 26 |
27 | -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/21. Merge Two Sorted Lists/README.md: -------------------------------------------------------------------------------- 1 | # Merge Two Sorted Lists 2 | 3 | **Difficulty:** Easy 4 | 5 | ## Problem Description 6 | 7 | You are given the heads of two sorted linked lists `list1` and `list2`. 8 | 9 | Merge the two lists into one **sorted** list. The list should be made by splicing together the nodes of the first two lists. 10 | 11 | Return *the head of the merged linked list*. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: list1 = [1,2,4], list2 = [1,3,4] 19 | Output: [1,1,2,3,4,4] 20 | 21 | ### Example 2 22 | Input: list1 = [], list2 = [] 23 | Output: [] 24 | 25 | ### Example 3 26 | Input: list1 = [], list2 = [0] 27 | Output: [0] 28 | 29 | --- 30 | 31 | ## Constraints 32 | 33 | - The number of nodes in both lists is in the range `[0, 50]`. 34 | - `-100 <= Node.val <= 100` 35 | - Both `list1` and `list2` are sorted in **non-decreasing** order. 36 | 37 | --- 38 | 39 | ## Approach 40 | 41 | This problem can be solved elegantly using recursion: 42 | 1. Base case: if one list is empty, return the other list 43 | 2. Recursive case: compare the heads of both lists 44 | 3. Choose the smaller head and recursively merge the rest 45 | 4. Connect the chosen head with the result of recursive merge 46 | 5. Return the merged list 47 | 48 | The recursive approach naturally handles the comparison and merging process. 49 | 50 | --- 51 | -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/25. Reverse Nodes in k-Group/README.md: -------------------------------------------------------------------------------- 1 | # Reverse Nodes in k-Group 2 | 3 | **Difficulty:** Hard 4 | 5 | ## Problem Description 6 | 7 | Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return the modified list. 8 | 9 | `k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it is. 10 | 11 | You may not alter the values in the list's nodes, only nodes themselves may be changed. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: head = [1,2,3,4,5], k = 2 19 | Output: [2,1,4,3,5] 20 | 21 | ### Example 2 22 | Input: head = [1,2,3,4,5], k = 3 23 | Output: [3,2,1,4,5] 24 | 25 | --- 26 | 27 | ## Constraints 28 | 29 | - The number of nodes in the list is `n`. 30 | - `1 <= k <= n <= 5000` 31 | - `0 <= Node.val <= 1000` 32 | 33 | --- 34 | 35 | ## Approach 36 | 37 | This problem uses recursion with multiple steps: 38 | 1. Check if there are k nodes remaining to reverse 39 | 2. If yes, reverse the first k nodes 40 | 3. Recursively process the remaining nodes 41 | 4. Connect the reversed group with the result of recursive call 42 | 5. Handle the case where remaining nodes are less than k 43 | 44 | The key is to reverse nodes in groups and maintain the connections between groups. 45 | 46 | --- 47 | -------------------------------------------------------------------------------- /Level 1/Week 03/LinkedList/19. Remove Nth Node From End of List/README.md: -------------------------------------------------------------------------------- 1 |

19. Remove Nth Node From End of List

Medium


Given the head of a linked list, remove the nth node from the end of the list and return its head.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: head = [1,2,3,4,5], n = 2
 8 | Output: [1,2,3,5]
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: head = [1], n = 1
15 | Output: []
16 | 
17 | 18 |

Example 3:

19 | 20 |
21 | Input: head = [1,2], n = 1
22 | Output: [1]
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • The number of nodes in the list is sz.
  • 30 |
  • 1 <= sz <= 30
  • 31 |
  • 0 <= Node.val <= 100
  • 32 |
  • 1 <= n <= sz
  • 33 |
34 | 35 |

 

36 |

Follow up: Could you do this in one pass?

37 | -------------------------------------------------------------------------------- /Level 0/10 Backtracking/02. 039-combination-sum/README.md: -------------------------------------------------------------------------------- 1 | # 39. Combination Sum 2 | 3 | ## Problem Description 4 | 5 | Given an array of **distinct** integers `candidates` and a target integer `target`, return *a list of all **unique combinations** of `candidates` where the chosen numbers sum to `target`*. You may return the combinations in **any order**. 6 | 7 | The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. 8 | 9 | ## Examples 10 | 11 | ### Example 1: 12 | 13 | **Input:** `candidates = [2,3,6,7]`, `target = 7` 14 | 15 | **Output:** `[[2,2,3],[7]]` 16 | 17 | **Explanation:** 18 | - 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 19 | - 7 is a candidate, and 7 = 7. 20 | - These are the only two combinations. 21 | 22 | ### Example 2: 23 | 24 | **Input:** `candidates = [2,3,5]`, `target = 8` 25 | 26 | **Output:** `[[2,2,2,2],[2,3,3],[3,5]]` 27 | 28 | ### Example 3: 29 | 30 | **Input:** `candidates = [2]`, `target = 1` 31 | 32 | **Output:** `[]` 33 | 34 | ## Constraints 35 | 36 | - `1 <= candidates.length <= 30` 37 | - `2 <= candidates[i] <= 40` 38 | - All elements of `candidates` are **distinct**. 39 | - `1 <= target <= 40` 40 | 41 | ## Related Topics 42 | 43 | - Array 44 | - Backtracking 45 | 46 | ## Difficulty 47 | 48 | Medium -------------------------------------------------------------------------------- /Level 0/9 Modified Binary Search/07. 0074-search-a-2d-matrix/0074-search-a-2d-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& matrix, int target) { 4 | int n = matrix.size(); // number of rows 5 | int m = matrix[0].size(); // number of columns 6 | 7 | int low = 0; 8 | int high = n * m - 1; 9 | 10 | while (low <= high) { 11 | int mid = (low + high) / 2; 12 | int row = mid / m; 13 | int col = mid % m; 14 | 15 | if (matrix[row][col] == target) { 16 | return true; 17 | } else if (matrix[row][col] < target) { 18 | low = mid + 1; 19 | } else { 20 | high = mid - 1; 21 | } 22 | } 23 | 24 | return false; 25 | } 26 | }; 27 | 28 | 29 | // Approach 1 30 | 31 | // bool searchMatrix(vector>& matrix, int target) { 32 | // int n = matrix.size(); // number of rows 33 | // int m = matrix[0].size(); // number of columns 34 | 35 | // int i = 0; 36 | // int j = m - 1; 37 | // while (i < n && j >= 0) { 38 | // if (matrix[i][j] == target) { 39 | // return true; 40 | // } else if (matrix[i][j] > target) { 41 | // j--; // move left 42 | // } else { 43 | // i++; // move down 44 | // } 45 | // } 46 | // return false; 47 | // } 48 | -------------------------------------------------------------------------------- /Level 0/9 Modified Binary Search/02. 0034-find-first-and-last-position-of-element-in-sorted-array/0034-find-first-and-last-position-of-element-in-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | vector res; 5 | 6 | int left = 0; 7 | int right = nums.size() - 1; 8 | 9 | int position = -1; 10 | 11 | while(left <= right){ 12 | int mid = left + (right - left) / 2; 13 | 14 | if(nums[mid] == target){ 15 | position = mid; 16 | right = mid - 1; 17 | }else if(nums[mid] > target){ 18 | right = mid - 1; 19 | }else{ 20 | left = mid + 1; 21 | } 22 | } 23 | 24 | res.push_back(position); 25 | 26 | position = -1; 27 | 28 | left = 0; 29 | right = nums.size() - 1; 30 | 31 | while(left <= right){ 32 | int mid = left + (right - left) / 2; 33 | 34 | if(nums[mid] == target){ 35 | position = mid; 36 | left = mid + 1; 37 | }else if(nums[mid] > target){ 38 | right = mid - 1; 39 | }else{ 40 | left = mid + 1; 41 | } 42 | } 43 | 44 | res.push_back(position); 45 | 46 | return res; 47 | } 48 | }; -------------------------------------------------------------------------------- /Level 0/8 Trees/10. 0124-binary-tree-maximum-path-sum/README.md: -------------------------------------------------------------------------------- 1 | # 124. Binary Tree Maximum Path Sum 2 | 3 | ## Problem Description 4 | 5 | A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root. 6 | 7 | The **path sum** of a path is the sum of the node's values in the path. 8 | 9 | Given the `root` of a binary tree, return *the maximum **path sum** of any **non-empty** path*. 10 | 11 | ## Examples 12 | 13 | ### Example 1: 14 | ![Example 1](https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg) 15 | 16 | **Input:** `root = [1,2,3]` 17 | 18 | **Output:** `6` 19 | 20 | **Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. 21 | 22 | ### Example 2: 23 | ![Example 2](https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg) 24 | 25 | **Input:** `root = [-10,9,20,null,null,15,7]` 26 | 27 | **Output:** `42` 28 | 29 | **Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. 30 | 31 | ## Constraints 32 | 33 | - The number of nodes in the tree is in the range `[1, 3 * 10^4]`. 34 | - `-1000 <= Node.val <= 1000` 35 | 36 | ## Related Topics 37 | 38 | - Dynamic Programming 39 | - Tree 40 | - Depth-First Search 41 | - Binary Tree 42 | 43 | ## Difficulty 44 | 45 | Hard 46 | -------------------------------------------------------------------------------- /Level 1/Week 03/LinkedList/206. Reverse Linked List/README.md: -------------------------------------------------------------------------------- 1 |

206. Reverse Linked List

Easy


Given the head of a singly linked list, reverse the list, and return the reversed list.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: head = [1,2,3,4,5]
 8 | Output: [5,4,3,2,1]
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: head = [1,2]
15 | Output: [2,1]
16 | 
17 | 18 |

Example 3:

19 | 20 |
21 | Input: head = []
22 | Output: []
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • The number of nodes in the list is the range [0, 5000].
  • 30 |
  • -5000 <= Node.val <= 5000
  • 31 |
32 | 33 |

 

34 |

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

35 | -------------------------------------------------------------------------------- /Level 1/Week 03/LinkedList/25. Reverse Nodes in k-Group/code.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseKGroup(ListNode* head, int k) { 14 | if (!head || k == 1) return head; 15 | 16 | ListNode* dummy = new ListNode(0); 17 | dummy->next = head; 18 | ListNode* group1 = dummy; 19 | 20 | while (true) { 21 | ListNode* kth = group1; 22 | for (int i = 0; i < k && kth; i++) { 23 | kth = kth->next; 24 | } 25 | if (!kth) break; 26 | 27 | ListNode* group2 = kth->next; 28 | ListNode* group3 = group1->next; 29 | 30 | // Reverse group 31 | ListNode* prev = group2; 32 | ListNode* curr = group3; 33 | while (curr != group2) { 34 | ListNode* temp = curr->next; 35 | curr->next = prev; 36 | prev = curr; 37 | curr = temp; 38 | } 39 | 40 | group1->next = kth; 41 | group1 = group3; 42 | } 43 | 44 | return dummy->next; 45 | } 46 | }; -------------------------------------------------------------------------------- /Level 1/Week 05/Modified Binary Search/4. Median of Two Sorted Arrays/README.md: -------------------------------------------------------------------------------- 1 |

4. Median of Two Sorted Arrays

Hard


Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

2 | 3 |

The overall run time complexity should be O(log (m+n)).

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums1 = [1,3], nums2 = [2]
10 | Output: 2.00000
11 | Explanation: merged array = [1,2,3] and median is 2.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums1 = [1,2], nums2 = [3,4]
18 | Output: 2.50000
19 | Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • nums1.length == m
  • 27 |
  • nums2.length == n
  • 28 |
  • 0 <= m <= 1000
  • 29 |
  • 0 <= n <= 1000
  • 30 |
  • 1 <= m + n <= 2000
  • 31 |
  • -106 <= nums1[i], nums2[i] <= 106
  • 32 |
33 | -------------------------------------------------------------------------------- /Level 0/9 Modified Binary Search/01. 0792-binary-search/README.md: -------------------------------------------------------------------------------- 1 |

792. Binary Search

Easy


Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

2 | 3 |

You must write an algorithm with O(log n) runtime complexity.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [-1,0,3,5,9,12], target = 9
10 | Output: 4
11 | Explanation: 9 exists in nums and its index is 4
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums = [-1,0,3,5,9,12], target = 2
18 | Output: -1
19 | Explanation: 2 does not exist in nums so return -1
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= nums.length <= 104
  • 27 |
  • -104 < nums[i], target < 104
  • 28 |
  • All the integers in nums are unique.
  • 29 |
  • nums is sorted in ascending order.
  • 30 |
31 | -------------------------------------------------------------------------------- /Level 1/Week 05/Modified Binary Search/704. Binary Search/README.md: -------------------------------------------------------------------------------- 1 |

704. Binary Search

Easy


Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

2 | 3 |

You must write an algorithm with O(log n) runtime complexity.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [-1,0,3,5,9,12], target = 9
10 | Output: 4
11 | Explanation: 9 exists in nums and its index is 4
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums = [-1,0,3,5,9,12], target = 2
18 | Output: -1
19 | Explanation: 2 does not exist in nums so return -1
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= nums.length <= 104
  • 27 |
  • -104 < nums[i], target < 104
  • 28 |
  • All the integers in nums are unique.
  • 29 |
  • nums is sorted in ascending order.
  • 30 |
31 | -------------------------------------------------------------------------------- /Level 1/Week 07/K way merge [Heaps]/1046. Last Stone Weight/README.md: -------------------------------------------------------------------------------- 1 | # Last Stone Weight 2 | 3 | **Difficulty:** Easy 4 | 5 | ## Problem Description 6 | 7 | You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. 8 | 9 | We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: 10 | 11 | - If `x == y`, both stones are destroyed, and 12 | - If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. 13 | 14 | At the end of the game, there is **at most one stone** left. 15 | 16 | Return the weight of the last remaining stone. If there are no stones left, return `0`. 17 | 18 | --- 19 | 20 | ## Examples 21 | 22 | ### Example 1 23 | Input: stones = [2,7,4,1,8,1] 24 | Output: 1 25 | Explanation: 26 | We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, 27 | we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, 28 | we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, 29 | we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. 30 | 31 | ### Example 2 32 | Input: stones = [1] 33 | Output: 1 34 | 35 | --- 36 | 37 | ## Constraints 38 | 39 | - `1 <= stones.length <= 30` 40 | - `1 <= stones[i] <= 1000` 41 | 42 | --- -------------------------------------------------------------------------------- /Level 1/Week 11/Dynamic Programming/62. Unique Paths/README.md: -------------------------------------------------------------------------------- 1 | # Unique Paths 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. 8 | 9 | Given the two integers `m` and `n`, return the number of possible unique paths that the robot can take to reach the bottom-right corner. 10 | 11 | The test cases are generated so that the answer will be less than or equal to `2 * 10^9`. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: m = 3, n = 7 19 | Output: 28 20 | 21 | ### Example 2 22 | Input: m = 3, n = 2 23 | Output: 3 24 | Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 25 | 1. Right -> Down -> Down 26 | 2. Down -> Down -> Right 27 | 3. Down -> Right -> Down 28 | 29 | --- 30 | 31 | ## Constraints 32 | 33 | - `1 <= m, n <= 100` 34 | 35 | --- 36 | 37 | ## Approaches 38 | 39 | This problem can be solved using 4 different dynamic programming approaches: 40 | 41 | 1. **Recursion** - Direct recursive implementation 42 | 2. **Memoization** - Top-down DP with caching 43 | 3. **Tabulation** - Bottom-up DP with 2D array 44 | 4. **Space Optimization** - Optimized to 1D array 45 | 46 | --- 47 | -------------------------------------------------------------------------------- /Level 1/Week 05/Modified Binary Search/704. Binary Search/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: Binary Search 3 | 4 | 1. **Initialize Pointers**: 5 | - Set `low = 0` and `high = nums.size() - 1` to define the search range. 6 | 7 | 2. **Iterative Loop**: 8 | - While `low <= high`, calculate the middle index: `mid = low + (high - low) / 2`. 9 | - Compare `nums[mid]` with the `target`. 10 | 11 | 3. **Comparison Cases**: 12 | - If `nums[mid] == target`: return `mid` (target found). 13 | - If `nums[mid] < target`: move to the right half → set `low = mid + 1`. 14 | - If `nums[mid] > target`: move to the left half → set `high = mid - 1`. 15 | 16 | 4. **Not Found**: 17 | - If the loop ends without returning, the target does not exist → return `-1`. 18 | 19 | Time Complexity: O(log n) 20 | Space Complexity: O(1) 21 | (Because the search space is halved each iteration and only a few variables are used) 22 | */ 23 | 24 | class Solution { 25 | public: 26 | int search(vector& nums, int target) { 27 | int low = 0; 28 | int high = nums.size() -1; 29 | while(low<=high){ 30 | int mid = low + (high - low)/2; 31 | if(nums[mid] == target){ 32 | return mid; 33 | } else if (nums[mid] < target){ 34 | low = mid +1; 35 | } else { 36 | high = mid - 1; 37 | } 38 | } 39 | return -1; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Level 1/Week 02/2 pointers/287. Find the Duplicate Number/code.cpp: -------------------------------------------------------------------------------- 1 | // ✅ Approach: 2 | // We treat the array like a linked list where: 3 | // - Each index represents a node. 4 | // - The value at each index points to the next node (like a pointer). 5 | // Since one number is repeated, it causes a cycle in this "linked list". 6 | // To detect the cycle, we use Floyd’s Tortoise and Hare algorithm: 7 | // 1. Initialize two pointers: slow and fast, both starting from index 0. 8 | // 2. Move slow one step at a time (slow = nums[slow]). 9 | // Move fast two steps at a time (fast = nums[nums[fast]]). 10 | // 3. When they meet, it confirms a cycle exists. 11 | // 4. Reset slow to start, move both one step at a time until they meet again. 12 | // 5. The point where they meet is the duplicate number (entry point of the cycle). 13 | 14 | class Solution { 15 | public: 16 | int findDuplicate(vector& nums) { 17 | int slow = nums[0]; 18 | int fast = nums[0]; 19 | 20 | // Phase 1: Detect intersection point in cycle 21 | do { 22 | slow = nums[slow]; 23 | fast = nums[nums[fast]]; 24 | } while (slow != fast); 25 | 26 | // Phase 2: Find the start of the cycle (duplicate number) 27 | slow = nums[0]; 28 | while (slow != fast) { 29 | slow = nums[slow]; 30 | fast = nums[fast]; 31 | } 32 | 33 | return fast; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Level 1/Week 10/Backtracking/78. Subsets/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem: 78. Subsets 3 | 4 | This is a classic backtracking problem where we need to generate all possible subsets. 5 | For each element, we have two choices: include it or exclude it. 6 | We use backtracking to explore all combinations systematically. 7 | 8 | Time Complexity: O(2^n) - we generate 2^n subsets 9 | Space Complexity: O(n) - recursion stack depth 10 | */ 11 | 12 | #include 13 | using namespace std; 14 | 15 | class Solution { 16 | public: 17 | vector> subsets(vector& nums) { 18 | vector> result; 19 | vector current; 20 | backtrack(nums, 0, current, result); 21 | return result; 22 | } 23 | 24 | private: 25 | void backtrack(vector& nums, int index, vector& current, vector>& result) { 26 | // Base case: when we've processed all elements 27 | if (index == nums.size()) { 28 | result.push_back(current); // Add current subset to result 29 | return; 30 | } 31 | 32 | // Choice 1: Include the current element 33 | current.push_back(nums[index]); 34 | backtrack(nums, index + 1, current, result); 35 | current.pop_back(); // Backtrack: remove the element 36 | 37 | // Choice 2: Exclude the current element 38 | backtrack(nums, index + 1, current, result); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Common/Math/Count Digits/count.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | --------------------------------------------------- 6 | 🔸 Approach 1: Brute Force using Modulo 7 | - Loop through each digit using modulo 8 | - Check if digit != 0 and divides original number 9 | --------------------------------------------------- 10 | */ 11 | int evenDigits(int n) { 12 | int cnt = 0; 13 | int N = n; // Store original number 14 | 15 | while (n > 0) { 16 | int digit = n % 10; 17 | n /= 10; 18 | 19 | if (digit != 0 && N % digit == 0) { 20 | cnt++; 21 | } 22 | } 23 | return cnt; 24 | } 25 | 26 | /* 27 | --------------------------------------------------- 28 | 🔸 Approach 2: Count Total Digits Using log10 29 | - Just counts total digits, not the ones that divide 30 | - Use: log10(num) + 1 31 | - Not relevant to "divisible digits" but useful 32 | --------------------------------------------------- 33 | */ 34 | int totalDigits(int num) { 35 | if (num == 0) return 1; 36 | return (int)(log10(num) + 1); 37 | } 38 | 39 | int main() { 40 | int number; 41 | cout << "Enter a number: "; 42 | cin >> number; 43 | 44 | cout << "Number of digits in " << number << " that divide it evenly: " 45 | << evenDigits(number) << endl; 46 | 47 | cout << "Total number of digits in " << number << ": " 48 | << totalDigits(number) << endl; 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Level 1/Week 07/K way merge [Heaps]/703. Kth Largest Element in a Stream/README.md: -------------------------------------------------------------------------------- 1 | # Kth Largest Element in a Stream 2 | 3 | **Difficulty:** Easy 4 | 5 | ## Problem Description 6 | 7 | Design a class to find the **kth largest** element in a stream. Note that it is the kth largest element in the **sorted order**, not the kth distinct element. 8 | 9 | Implement the `KthLargest` class: 10 | 11 | - `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of integers `nums`. 12 | - `int add(int val)` Appends the integer `val` to the stream and returns the element representing the kth largest element in the stream. 13 | 14 | --- 15 | 16 | ## Examples 17 | 18 | ### Example 1 19 | Input: 20 | ["KthLargest", "add", "add", "add", "add", "add"] 21 | [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] 22 | Output: [null, 4, 5, 5, 8, 8] 23 | 24 | Explanation: 25 | KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); 26 | kthLargest.add(3); // return 4 27 | kthLargest.add(5); // return 5 28 | kthLargest.add(10); // return 5 29 | kthLargest.add(9); // return 8 30 | kthLargest.add(4); // return 8 31 | 32 | --- 33 | 34 | ## Constraints 35 | 36 | - `1 <= k <= 10^4` 37 | - `0 <= nums.length <= 10^4` 38 | - `-10^4 <= nums[i] <= 10^4` 39 | - `-10^4 <= val <= 10^4` 40 | - At most `10^4` calls will be made to `add`. 41 | - It is guaranteed that there will be at least `k` elements in the array when you search for the kth element. 42 | 43 | --- -------------------------------------------------------------------------------- /Level 0/10 Backtracking/04. 046-permutations/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vector> result; 4 | 5 | void backtrack(vector& nums, vector& current, vector& used) { 6 | // Base case: if current permutation has all elements 7 | if (current.size() == nums.size()) { 8 | result.push_back(current); 9 | return; 10 | } 11 | 12 | // Try all elements for current position 13 | for (int i = 0; i < nums.size(); i++) { 14 | // Skip if element is already used 15 | if (used[i]) { 16 | continue; 17 | } 18 | 19 | // Make choice: use nums[i] at current position 20 | used[i] = true; 21 | current.push_back(nums[i]); 22 | 23 | // Recurse to fill next position 24 | backtrack(nums, current, used); 25 | 26 | // Backtrack: undo the choice 27 | current.pop_back(); 28 | used[i] = false; 29 | } 30 | } 31 | 32 | public: 33 | vector> permute(vector& nums) { 34 | vector current; 35 | vector used(nums.size(), false); 36 | backtrack(nums, current, used); 37 | return result; 38 | } 39 | }; 40 | 41 | /* 42 | Time Complexity: O(n!) where n is the length of nums 43 | Space Complexity: O(n) for recursion stack and used array 44 | */ -------------------------------------------------------------------------------- /Level 0/10 Backtracking/02. 039-combination-sum/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vector> result; 4 | 5 | void backtrack(vector& candidates, vector& current, int target, int start) { 6 | // Base case: if target becomes 0, we found a valid combination 7 | if (target == 0) { 8 | result.push_back(current); 9 | return; 10 | } 11 | 12 | // Base case: if target becomes negative, this path is invalid 13 | if (target < 0) { 14 | return; 15 | } 16 | 17 | // Try all candidates starting from 'start' index 18 | for (int i = start; i < candidates.size(); i++) { 19 | // Make choice: include candidates[i] 20 | current.push_back(candidates[i]); 21 | 22 | // Recurse with updated target (can reuse same element) 23 | backtrack(candidates, current, target - candidates[i], i); 24 | 25 | // Backtrack: remove candidates[i] 26 | current.pop_back(); 27 | } 28 | } 29 | 30 | public: 31 | vector> combinationSum(vector& candidates, int target) { 32 | vector current; 33 | backtrack(candidates, current, target, 0); 34 | return result; 35 | } 36 | }; 37 | 38 | /* 39 | Time Complexity: O(k * 2^target) where k is the average length of combinations 40 | Space Complexity: O(target) for recursion stack 41 | */ -------------------------------------------------------------------------------- /Level 1/Week 06/Stack/20. Valid Parentheses/README.md: -------------------------------------------------------------------------------- 1 |

20. Valid Parentheses

Easy


Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

2 | 3 |

An input string is valid if:

4 | 5 |
    6 |
  1. Open brackets must be closed by the same type of brackets.
  2. 7 |
  3. Open brackets must be closed in the correct order.
  4. 8 |
  5. Every close bracket has a corresponding open bracket of the same type.
  6. 9 |
10 | 11 |

 

12 |

Example 1:

13 | 14 |
15 | Input: s = "()"
16 | Output: true
17 | 
18 | 19 |

Example 2:

20 | 21 |
22 | Input: s = "()[]{}"
23 | Output: true
24 | 
25 | 26 |

Example 3:

27 | 28 |
29 | Input: s = "(]"
30 | Output: false
31 | 
32 | 33 |

 

34 |

Constraints:

35 | 36 |
    37 |
  • 1 <= s.length <= 104
  • 38 |
  • s consists of parentheses only '()[]{}'.
  • 39 |
40 | -------------------------------------------------------------------------------- /Level 1/Week 12/Graph/200. Number of Islands/README.md: -------------------------------------------------------------------------------- 1 | # Number of Islands 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return *the number of islands*. 8 | 9 | An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: grid = [ 17 | ["1","1","1","1","0"], 18 | ["1","1","0","1","0"], 19 | ["1","1","0","0","0"], 20 | ["0","0","0","0","0"] 21 | ] 22 | Output: 1 23 | 24 | ### Example 2 25 | Input: grid = [ 26 | ["1","1","0","0","0"], 27 | ["1","1","0","0","0"], 28 | ["0","0","1","0","0"], 29 | ["0","0","0","1","1"] 30 | ] 31 | Output: 3 32 | 33 | --- 34 | 35 | ## Constraints 36 | 37 | - `m == grid.length` 38 | - `n == grid[i].length` 39 | - `1 <= m, n <= 300` 40 | - `grid[i][j]` is `'0'` or `'1'`. 41 | 42 | --- 43 | 44 | ## Approach 45 | 46 | This problem can be solved using DFS or BFS: 47 | 1. Iterate through each cell in the grid 48 | 2. When we find a land cell ('1'), start a DFS/BFS to explore the entire island 49 | 3. Mark visited cells to avoid counting them again 50 | 4. Count the number of times we start a new exploration (number of islands) 51 | 52 | The key insight is to use a flood-fill approach to mark all connected land cells as visited. 53 | 54 | --- 55 | -------------------------------------------------------------------------------- /Common/Math/Odd/odd_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | ------------------------------------------ 6 | 🔹 Approach 1: Modulo Operator (%) 7 | - If a number divided by 2 leaves remainder 1, 8 | it's odd. 9 | - Straightforward and easy to understand. 10 | ------------------------------------------ 11 | */ 12 | bool odd(int n) { 13 | return n % 2 == 1; 14 | } 15 | 16 | /* 17 | ------------------------------------------ 18 | 🔹 Approach 2: Bitwise AND Operator (&) 19 | - Odd numbers have 1 as the last binary digit. 20 | - So, if (n & 1) == 1, it's odd. 21 | - Fast and efficient. 22 | ------------------------------------------ 23 | */ 24 | bool odd_bitwise(int n) { 25 | return (n & 1) != 0; 26 | } 27 | 28 | /* 29 | ------------------------------------------ 30 | 🔹 Approach 3: Integer Division 31 | - Divide the number by 2 and multiply it back. 32 | - If the result is not equal to original, 33 | it's odd. 34 | ------------------------------------------ 35 | */ 36 | bool odd_division(int n) { 37 | return (n / 2) * 2 != n; 38 | } 39 | 40 | /* 41 | ------------------------------------------ 42 | 🔹 Approach 4: Recursive Method 43 | - Base case: 0 → false (even), 1 → true (odd) 44 | - Reduce n by 1 each time to reach the base case. 45 | - Helps understand recursion. 46 | ------------------------------------------ 47 | */ 48 | bool odd_recursive(int n) { 49 | if (n == 0) return false; 50 | if (n == 1) return true; 51 | return odd_recursive(n - 2); 52 | } 53 | -------------------------------------------------------------------------------- /Level 1/Week 03/LinkedList/21. Merge Two Sorted Lists/README.md: -------------------------------------------------------------------------------- 1 |

21. Merge Two Sorted Lists

Easy


You are given the heads of two sorted linked lists list1 and list2.

2 | 3 |

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

4 | 5 |

Return the head of the merged linked list.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: list1 = [1,2,4], list2 = [1,3,4]
12 | Output: [1,1,2,3,4,4]
13 | 
14 | 15 |

Example 2:

16 | 17 |
18 | Input: list1 = [], list2 = []
19 | Output: []
20 | 
21 | 22 |

Example 3:

23 | 24 |
25 | Input: list1 = [], list2 = [0]
26 | Output: [0]
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • The number of nodes in both lists is in the range [0, 50].
  • 34 |
  • -100 <= Node.val <= 100
  • 35 |
  • Both list1 and list2 are sorted in non-decreasing order.
  • 36 |
37 | -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/445. Add Two Numbers II/README.md: -------------------------------------------------------------------------------- 1 | # Add Two Numbers II 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. 8 | 9 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: l1 = [7,2,4,3], l2 = [5,6,4] 17 | Output: [7,8,0,7] 18 | 19 | ### Example 2 20 | Input: l1 = [2,4,3], l2 = [5,6,4] 21 | Output: [8,0,7] 22 | 23 | ### Example 3 24 | Input: l1 = [0], l2 = [0] 25 | Output: [0] 26 | 27 | --- 28 | 29 | ## Constraints 30 | 31 | - The number of nodes in each linked list is in the range `[1, 100]`. 32 | - `0 <= Node.val <= 9` 33 | - It is guaranteed that the list represents a number that does not have leading zeros. 34 | 35 | --- 36 | 37 | ## Approach 38 | 39 | This problem is more complex than Add Two Numbers I because digits are in forward order: 40 | 1. First, we need to reverse both lists to work with least significant digits first 41 | 2. Use the recursive approach from Add Two Numbers I 42 | 3. Reverse the result back to get the correct order 43 | 4. Handle the carry propagation from least to most significant digits 44 | 45 | The recursive approach handles the addition, while list reversal handles the digit order. 46 | 47 | --- 48 | -------------------------------------------------------------------------------- /Level 1/Week 01/Arrays & Hashing/49. Group Anagrams/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: 3 | 4 | To group anagrams from a list of strings, we leverage the property that anagrams share the same characters in a different order. 5 | 6 | 1. We use a hash map (`unordered_map`) where: 7 | - The key is the sorted version of the string. 8 | - The value is a vector of strings that are anagrams of each other. 9 | 10 | 2. For each string in the input: 11 | - We create a copy and sort it alphabetically. 12 | - This sorted string acts as a key to group all its anagrams together in the map. 13 | 14 | 3. After processing all strings, we extract the grouped anagrams from the map and return them as a vector of vectors. 15 | 16 | Time Complexity: 17 | - O(n * k log k), where `n` is the number of strings and `k` is the average length of each string (due to sorting). 18 | 19 | Space Complexity: 20 | - O(n * k), for storing the grouped anagrams. 21 | 22 | */ 23 | 24 | class Solution { 25 | public: 26 | vector> groupAnagrams(vector& strs) { 27 | unordered_map> Groups; 28 | 29 | for (string s : strs) { 30 | string sortedStr = s; 31 | sort(sortedStr.begin(), sortedStr.end()); 32 | Groups[sortedStr].push_back(s); 33 | } 34 | 35 | vector> result; 36 | for (auto& pair : Groups) { 37 | result.push_back(pair.second); 38 | } 39 | 40 | return result; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/2. Add Two Numbers/README.md: -------------------------------------------------------------------------------- 1 | # Add Two Numbers 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. 8 | 9 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: l1 = [2,4,3], l2 = [5,6,4] 17 | Output: [7,0,8] 18 | Explanation: 342 + 465 = 807. 19 | 20 | ### Example 2 21 | Input: l1 = [0], l2 = [0] 22 | Output: [0] 23 | 24 | ### Example 3 25 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] 26 | Output: [8,9,9,9,0,0,0,1] 27 | 28 | --- 29 | 30 | ## Constraints 31 | 32 | - The number of nodes in each linked list is in the range `[1, 100]`. 33 | - `0 <= Node.val <= 9` 34 | - It is guaranteed that the list represents a number that does not have leading zeros. 35 | 36 | --- 37 | 38 | ## Approach 39 | 40 | This problem can be solved using recursion: 41 | 1. Base case: if both lists are null and no carry remains 42 | 2. Recursive case: add current digits and carry 43 | 3. Create a new node with the sum modulo 10 44 | 4. Recursively add the remaining digits with the carry 45 | 5. Connect the current node with the recursive result 46 | 47 | The recursive approach naturally handles the digit-by-digit addition and carry propagation. 48 | 49 | --- 50 | -------------------------------------------------------------------------------- /Level 1/Week 06/Queue/239. Sliding Window Maximum/README.md: -------------------------------------------------------------------------------- 1 |

239. Sliding Window Maximum

Hard


You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

2 | 3 |

Return the max sliding window.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
10 | Output: [3,3,5,5,6,7]
11 | Explanation:
12 | Window position                Max
13 | ---------------               -----
14 | [1  3  -1] -3  5  3  6  7       3
15 |  1 [3  -1  -3] 5  3  6  7       3
16 |  1  3 [-1  -3  5] 3  6  7       5
17 |  1  3  -1 [-3  5  3] 6  7       5
18 |  1  3  -1  -3 [5  3  6] 7       6
19 |  1  3  -1  -3  5 [3  6  7]      7
20 | 
21 | 22 |

Example 2:

23 | 24 |
25 | Input: nums = [1], k = 1
26 | Output: [1]
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • 1 <= nums.length <= 105
  • 34 |
  • -104 <= nums[i] <= 104
  • 35 |
  • 1 <= k <= nums.length
  • 36 |
-------------------------------------------------------------------------------- /Level 1/Week 12/Graph/994. Rotting Oranges/README.md: -------------------------------------------------------------------------------- 1 | # Rotting Oranges 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | You are given an `m x n` `grid` where each cell can have one of three values: 8 | 9 | - `0` representing an empty cell, 10 | - `1` representing a fresh orange, or 11 | - `2` representing a rotten orange. 12 | 13 | Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. 14 | 15 | Return *the minimum number of minutes that must elapse until no cell has a fresh orange*. If *this is impossible, return* `-1`. 16 | 17 | --- 18 | 19 | ## Examples 20 | 21 | ### Example 1 22 | Input: grid = [[2,1,1],[1,1,0],[0,1,1]] 23 | Output: 4 24 | 25 | ### Example 2 26 | Input: grid = [[2,1,1],[0,1,1],[1,0,1]] 27 | Output: -1 28 | 29 | ### Example 3 30 | Input: grid = [[0,2]] 31 | Output: 0 32 | 33 | --- 34 | 35 | ## Constraints 36 | 37 | - `m == grid.length` 38 | - `n == grid[i].length` 39 | - `1 <= m, n <= 10` 40 | - `grid[i][j]` is only `0`, `1`, or `2`. 41 | 42 | --- 43 | 44 | ## Approach 45 | 46 | This problem can be solved using BFS: 47 | 1. Find all rotten oranges and add them to a queue 48 | 2. Use BFS to simulate the rotting process minute by minute 49 | 3. Track the number of minutes elapsed 50 | 4. Check if all fresh oranges become rotten 51 | 5. Return -1 if some fresh oranges remain unreachable 52 | 53 | The key insight is to use BFS to simulate the spreading process level by level, where each level represents one minute. 54 | 55 | --- 56 | -------------------------------------------------------------------------------- /Level 0/9 Modified Binary Search/02. 0034-find-first-and-last-position-of-element-in-sorted-array/README.md: -------------------------------------------------------------------------------- 1 |

34. Find First and Last Position of Element in Sorted Array

Medium


Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

2 | 3 |

If target is not found in the array, return [-1, -1].

4 | 5 |

You must write an algorithm with O(log n) runtime complexity.

6 | 7 |

 

8 |

Example 1:

9 |
Input: nums = [5,7,7,8,8,10], target = 8
10 | Output: [3,4]
11 | 

Example 2:

12 |
Input: nums = [5,7,7,8,8,10], target = 6
13 | Output: [-1,-1]
14 | 

Example 3:

15 |
Input: nums = [], target = 0
16 | Output: [-1,-1]
17 | 
18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 0 <= nums.length <= 105
  • 23 |
  • -109 <= nums[i] <= 109
  • 24 |
  • nums is a non-decreasing array.
  • 25 |
  • -109 <= target <= 109
  • 26 |
27 | -------------------------------------------------------------------------------- /Level 1/Week 04/Trees/226. Invert Binary Tree/code.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Approach: 3 | * The goal is to invert a binary tree, meaning swap every left and right subtree recursively. 4 | * This is done using a Depth-First Search (DFS) approach: 5 | * 6 | * 1. Traverse the tree recursively. 7 | * 2. At each node, recursively invert the left and right subtrees. 8 | * 3. Swap the left and right pointers of the current node. 9 | * 4. Return the root after the entire tree has been inverted. 10 | * 11 | * Time Complexity: O(n), where n is the number of nodes in the tree. 12 | * Space Complexity: O(h), where h is the height of the tree due to the recursion stack. 13 | */ 14 | 15 | /** 16 | * Definition for a binary tree node. 17 | * struct TreeNode { 18 | * int val; 19 | * TreeNode *left; 20 | * TreeNode *right; 21 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 22 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 23 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 24 | * }; 25 | */ 26 | class Solution { 27 | public: 28 | TreeNode* invert(TreeNode* root) { 29 | if (root == NULL) { 30 | return NULL; 31 | } 32 | TreeNode* left = invert(root->left); 33 | TreeNode* right = invert(root->right); 34 | root->left = right; 35 | root->right = left; 36 | return root; 37 | } 38 | 39 | TreeNode* invertTree(TreeNode* root) { 40 | return invert(root); 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Level 1/Week 04/Trees/230. Kth Smallest Element in a BST/README.md: -------------------------------------------------------------------------------- 1 |

230. Kth Smallest Element in a BST

Medium


Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: root = [3,1,4,null,2], k = 1
 8 | Output: 1
 9 | 
10 | 11 |

Example 2:

12 | 13 |
14 | Input: root = [5,3,6,2,4,null,null,1], k = 3
15 | Output: 3
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • The number of nodes in the tree is n.
  • 23 |
  • 1 <= k <= n <= 104
  • 24 |
  • 0 <= Node.val <= 104
  • 25 |
26 | 27 |

 

28 |

Follow up: 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?

29 | -------------------------------------------------------------------------------- /Level 1/Week 06/Stack/20. Valid Parentheses/code.cpp: -------------------------------------------------------------------------------- 1 | // 🧠 Approach: 2 | // This problem checks for valid matching parentheses using a **stack**. 3 | // 1. Traverse the string character by character. 4 | // 2. If the character is an opening bracket `(`, `{`, or `[`, push it onto the stack. 5 | // 3. If the character is a closing bracket `)`, `}`, or `]`: 6 | // - Check if the stack is empty → if yes, return false (no matching opening). 7 | // - Otherwise, check if the top of the stack has the matching opening bracket. 8 | // If it doesn't match, return false. 9 | // - If it matches, pop the top from the stack. 10 | // 4. After the loop, the stack must be empty for the string to be valid (all opened brackets closed). 11 | 12 | // ✅ Time Complexity: O(n), where n = length of the string. 13 | // ✅ Space Complexity: O(n), for the stack usage in the worst case (all characters are opening brackets). 14 | 15 | class Solution { 16 | public: 17 | bool isValid(string s) { 18 | stack st; 19 | for (char c : s) { 20 | if (c == '(' || c == '{' || c == '[') { 21 | st.push(c); 22 | } else { 23 | if (st.empty() || 24 | (c == ')' && st.top() != '(') || 25 | (c == '}' && st.top() != '{') || 26 | (c == ']' && st.top() != '[')) { 27 | return false; 28 | } 29 | st.pop(); 30 | } 31 | } 32 | return st.empty(); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Common/Math/GCD_HCF_Calculation/README.md: -------------------------------------------------------------------------------- 1 | # 🔗 GCD / HCF of Two Numbers — C++ Implementation 2 | 3 | --- 4 | 5 | ## 📘 Problem Statement 6 | 7 | You are given two integers `a` and `b`. 8 | Your task is to compute their **GCD (Greatest Common Divisor)**, which is also called **HCF (Highest Common Factor)**. 9 | 10 | > ✅ GCD is the largest number that divides both `a` and `b` without leaving a remainder. 11 | 12 | --- 13 | 14 | ## ✳️ Example 15 | 16 | Input: 20, 15 17 | Divisors of 20 → 1, 2, 4, 5, 10, 20 18 | Divisors of 15 → 1, 3, 5, 15 19 | Common Divisors → 1, 5 20 | GCD = 5 21 | 22 | 23 | --- 24 | 25 | ## 🚀 Approaches 26 | 27 | ### 🔸 1. Brute Force 28 | 29 | - Loop from 1 to `min(a, b)` 30 | - Check if the number divides both `a` and `b` 31 | - Keep updating the largest such number 32 | 33 | #### ⏱️ Time Complexity: 34 | - O(min(a, b)) 35 | 36 | #### ✅ Usage: 37 | Good for small values or when learning the basics. 38 | 39 | --- 40 | 41 | ### 🔸 2. Euclidean Algorithm 42 | 43 | Uses the fact that: 44 | gcd(a, b) = gcd(b, a % b) 45 | 46 | 47 | 48 | - Repeat until one of the numbers becomes 0 49 | - The other number is the result 50 | 51 | #### ⏱️ Time Complexity: 52 | - O(log(min(a, b))) 53 | 54 | #### ✅ Usage: 55 | Efficient and used in real-world applications, competitive coding, cryptography, etc. 56 | 57 | --- 58 | 59 | ## 📂 File Structure 60 | 61 | GCD_HCF_Calculations/ 62 | ├── gcd.cpp # Full C++ source with both methods 63 | ├── README.md # Explanation and documentation 64 | ├── Makefile # Build and run commands -------------------------------------------------------------------------------- /Common/Math/Even/even_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | ------------------------------------------ 6 | 🔹 Approach 1: Modulo Operator (%) 7 | - If a number divided by 2 has no remainder, 8 | it is even. 9 | - Classic and most readable method. 10 | ------------------------------------------ 11 | */ 12 | bool even(int n) { 13 | return n % 2 == 0; 14 | } 15 | 16 | /* 17 | ------------------------------------------ 18 | 🔹 Approach 2: Bitwise AND Operator (&) 19 | - Binary trick: even numbers have 0 as the last bit. 20 | - Checking (n & 1) gives 0 if it's even. 21 | - Very efficient. 22 | ------------------------------------------ 23 | */ 24 | bool even_bitwise(int n) { 25 | return (n & 1) == 0; 26 | } 27 | 28 | /* 29 | ------------------------------------------ 30 | 🔹 Approach 3: Integer Division Trick 31 | - Divide the number by 2 and multiply it back. 32 | - If the result equals original number, it's even. 33 | - Uncommon but clever. 34 | ------------------------------------------ 35 | */ 36 | bool even_division(int n) { 37 | return (n / 2) * 2 == n; 38 | } 39 | 40 | /* 41 | ------------------------------------------ 42 | 🔹 Approach 4: Recursive Method 43 | - Subtract 2 recursively until 0 or 1. 44 | - Base Case: 0 = even, 1 = odd. 45 | - Great for learning recursion but not optimal. 46 | ------------------------------------------ 47 | */ 48 | bool even_recursive(int n) { 49 | if (n == 0) return true; 50 | if (n == 1) return false; 51 | return even_recursive(n - 2); 52 | } 53 | -------------------------------------------------------------------------------- /Level 1/Week 09/Greedy/45. Jump Game II/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: Greedy Algorithm 3 | 4 | The greedy approach is to always jump to the position that allows us to reach the farthest. 5 | We keep track of the current jump's range and the farthest position we can reach. 6 | When we reach the end of the current jump's range, we make another jump. 7 | 8 | Algorithm: 9 | 1. Track the farthest position reachable and current jump boundary 10 | 2. For each position, update the farthest reachable position 11 | 3. When we reach the current jump boundary, increment jumps and update boundary 12 | 4. Continue until we can reach the last index 13 | 14 | Time Complexity: O(n) 15 | Space Complexity: O(1) 16 | */ 17 | 18 | #include 19 | #include 20 | using namespace std; 21 | 22 | class Solution { 23 | public: 24 | int jump(vector& nums) 25 | { 26 | int n = nums.size(); 27 | 28 | if (n <= 1) 29 | { 30 | return 0; 31 | } 32 | 33 | int jumps = 0; 34 | int farthest = 0; 35 | int currentEnd = 0; 36 | 37 | for (int i = 0; i < n - 1; i++) 38 | { 39 | farthest = max(farthest, i + nums[i]); 40 | 41 | if (i == currentEnd) 42 | { 43 | ++jumps; 44 | currentEnd = farthest; 45 | 46 | if (currentEnd >= n - 1) 47 | { 48 | break; 49 | } 50 | } 51 | } 52 | 53 | return jumps; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /Level 1/Week 10/Backtracking/51. N-Queens/README.md: -------------------------------------------------------------------------------- 1 | # N-Queens 2 | 3 | **Difficulty:** Hard 4 | 5 | ## Problem Description 6 | 7 | The **n-queens puzzle** is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. 8 | 9 | Given an integer `n`, return *all distinct solutions to the **n-queens puzzle***. You may return the answer in **any order**. 10 | 11 | Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: n = 4 19 | Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] 20 | Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. 21 | 22 | ### Example 2 23 | Input: n = 1 24 | Output: [["Q"]] 25 | 26 | --- 27 | 28 | ## Constraints 29 | 30 | - `1 <= n <= 9` 31 | 32 | --- 33 | 34 | ## Approach 35 | 36 | This is a classic backtracking problem: 37 | 1. We place queens one by one in each row 38 | 2. For each row, we try placing a queen in each column 39 | 3. Before placing a queen, we check if it's safe (no conflicts with existing queens) 40 | 4. We check for conflicts in the same column, same diagonal, and same anti-diagonal 41 | 5. If safe, we place the queen and recursively try to place queens in the next row 42 | 6. We backtrack by removing the queen to try different positions 43 | 7. When we've placed all n queens, we add the board configuration to our result 44 | 45 | --- 46 | -------------------------------------------------------------------------------- /Level 1/Week 11/Dynamic Programming/198. House Robber/README.md: -------------------------------------------------------------------------------- 1 | # House Robber 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**. 8 | 9 | Given an integer array `nums` representing the amount of money of each house, return the maximum amount of money you can rob tonight **without alerting the police**. 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: nums = [1,2,3,1] 17 | Output: 4 18 | Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 19 | Total amount you can rob = 1 + 3 = 4. 20 | 21 | ### Example 2 22 | Input: nums = [2,7,9,3,1] 23 | Output: 12 24 | Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). 25 | Total amount you can rob = 2 + 9 + 1 = 12. 26 | 27 | --- 28 | 29 | ## Constraints 30 | 31 | - `1 <= nums.length <= 100` 32 | - `0 <= nums[i] <= 400` 33 | 34 | --- 35 | 36 | ## Approaches 37 | 38 | This problem can be solved using 4 different dynamic programming approaches: 39 | 40 | 1. **Recursion** - Direct recursive implementation 41 | 2. **Memoization** - Top-down DP with caching 42 | 3. **Tabulation** - Bottom-up DP with array 43 | 4. **Space Optimization** - Optimized space complexity 44 | 45 | --- 46 | -------------------------------------------------------------------------------- /Common/Math/Extract Digits/README.md: -------------------------------------------------------------------------------- 1 | # 🔢 Extract Digits & Count Total – C++ Implementation 2 | 3 | --- 4 | 5 | ## 📘 Problem Statement 6 | 7 | You are given a number `n`. The goal is to **extract its digits** and **count how many digits** the number has. 8 | 9 | This is a basic math operation used in problems such as: 10 | - Reverse a number 11 | - Palindrome checks 12 | - Sum of digits 13 | - Armstrong number logic 14 | 15 | --- 16 | 17 | ## ✳️ Example: 18 | 19 | ### Input: 20 | 1234 21 | ### Steps: 22 | 1234 % 10 = 4 → count = 1 23 | 123 % 10 = 3 → count = 2 24 | 12 % 10 = 2 → count = 3 25 | 1 % 10 = 1 → count = 4 26 | 0 → loop stops 27 | 28 | ### Output: 29 | 4 30 | 31 | --- 32 | 33 | ## 🚀 Approach 34 | 35 | ### 🔸 Using `%` and `/` 36 | 37 | | Operation | Meaning | 38 | |----------:|-------------------------| 39 | | `n % 10` | Extract the last digit | 40 | | `n / 10` | Remove the last digit | 41 | 42 | Repeat these steps until the number becomes `0`. For every iteration, increase the digit count. 43 | 44 | --- 45 | 46 | ## 🧠 Why This Works? 47 | 48 | Every number in base-10 can be broken down into its digits using: 49 | - `% 10` → gets the last digit 50 | - `/ 10` → removes the last digit 51 | 52 | This is the foundation for many number-based algorithms. 53 | 54 | --- 55 | 56 | ## 📂 File Structure 57 | 58 | ExtractDigit/ 59 | ├── extract_digit.cpp # Full working code 60 | ├── README.md # Explanation and approach 61 | 62 | └── Makefile # Build and run the code 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /Level 1/Week 11/Dynamic Programming/518. Coin Change II/README.md: -------------------------------------------------------------------------------- 1 | # Coin Change II 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. 8 | 9 | Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return `0`. 10 | 11 | You may assume that you have an infinite number of each kind of coin. 12 | 13 | The answer is **guaranteed** to fit into a signed **32-bit** integer. 14 | 15 | --- 16 | 17 | ## Examples 18 | 19 | ### Example 1 20 | Input: amount = 5, coins = [1,2,5] 21 | Output: 4 22 | Explanation: there are four ways to make up the amount: 23 | 5=5 24 | 5=2+2+1 25 | 5=2+1+1+1 26 | 5=1+1+1+1+1 27 | 28 | ### Example 2 29 | Input: amount = 3, coins = [2] 30 | Output: 0 31 | Explanation: the amount of 3 cannot be made up just with coins of 2. 32 | 33 | ### Example 3 34 | Input: amount = 10, coins = [10] 35 | Output: 1 36 | 37 | --- 38 | 39 | ## Constraints 40 | 41 | - `1 <= coins.length <= 300` 42 | - `1 <= coins[i] <= 5000` 43 | - `0 <= amount <= 5000` 44 | 45 | --- 46 | 47 | ## Approaches 48 | 49 | This problem can be solved using 4 different dynamic programming approaches: 50 | 51 | 1. **Recursion** - Direct recursive implementation 52 | 2. **Memoization** - Top-down DP with caching 53 | 3. **Tabulation** - Bottom-up DP with array 54 | 4. **Space Optimization** - Optimized space complexity 55 | 56 | --- 57 | -------------------------------------------------------------------------------- /Level 0/7 Sliding Window/08. 0003-longest-substring-without-repeating-characters/README.md: -------------------------------------------------------------------------------- 1 |

3. Longest Substring Without Repeating Characters

Medium


Given a string s, find the length of the longest substring without duplicate characters.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: s = "abcabcbb"
 8 | Output: 3
 9 | Explanation: The answer is "abc", with the length of 3.
10 | 
11 | 12 |

Example 2:

13 | 14 |
15 | Input: s = "bbbbb"
16 | Output: 1
17 | Explanation: The answer is "b", with the length of 1.
18 | 
19 | 20 |

Example 3:

21 | 22 |
23 | Input: s = "pwwkew"
24 | Output: 3
25 | Explanation: The answer is "wke", with the length of 3.
26 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • 0 <= s.length <= 5 * 104
  • 34 |
  • s consists of English letters, digits, symbols and spaces.
  • 35 |
36 | -------------------------------------------------------------------------------- /Level 0/8 Trees/06. 1448-count-good-nodes-in-binary-tree/README.md: -------------------------------------------------------------------------------- 1 | # 1448. Count Good Nodes in Binary Tree 2 | 3 | ## Problem Description 4 | 5 | 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. 6 | 7 | Return the number of **good** nodes in the binary tree. 8 | 9 | ## Examples 10 | 11 | ### Example 1: 12 | ![Example 1](https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png) 13 | 14 | **Input:** `root = [3,1,4,3,null,1,5]` 15 | 16 | **Output:** `4` 17 | 18 | **Explanation:** Nodes in blue are **good**. 19 | Root Node (3) is always a good node. 20 | Node 4 -> (3,4) is the maximum value in the path starting from the root. 21 | Node 5 -> (3,4,5) is the maximum value in the path 22 | Node 3 -> (3,1,3) is the maximum value in the path. 23 | 24 | ### Example 2: 25 | ![Example 2](https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png) 26 | 27 | **Input:** `root = [3,3,null,4,2]` 28 | 29 | **Output:** `3` 30 | 31 | **Explanation:** Node 2 -> (3, 3, 2) is not good, because "3" is higher than it. 32 | 33 | ### Example 3: 34 | 35 | **Input:** `root = [1]` 36 | 37 | **Output:** `1` 38 | 39 | **Explanation:** Root is considered as good. 40 | 41 | ## Constraints 42 | 43 | - The number of nodes in the binary tree is in the range `[1, 10^5]`. 44 | - Each node's value is between `[-10^4, 10^4]`. 45 | 46 | ## Related Topics 47 | 48 | - Tree 49 | - Depth-First Search 50 | - Breadth-First Search 51 | - Binary Tree 52 | 53 | ## Difficulty 54 | 55 | Medium 56 | -------------------------------------------------------------------------------- /Level 1/Week 02/Sliding windows/3. Longest Substring Without Repeating Characters/README.md: -------------------------------------------------------------------------------- 1 |

3. Longest Substring Without Repeating Characters

Medium


Given a string s, find the length of the longest substring without repeating characters.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: s = "abcabcbb"
 8 | Output: 3
 9 | Explanation: The answer is "abc", with the length of 3.
10 | 
11 | 12 |

Example 2:

13 | 14 |
15 | Input: s = "bbbbb"
16 | Output: 1
17 | Explanation: The answer is "b", with the length of 1.
18 | 
19 | 20 |

Example 3:

21 | 22 |
23 | Input: s = "pwwkew"
24 | Output: 3
25 | Explanation: The answer is "wke", with the length of 3.
26 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • 0 <= s.length <= 5 * 104
  • 34 |
  • s consists of English letters, digits, symbols and spaces.
  • 35 |
36 | -------------------------------------------------------------------------------- /Level 0/10 Backtracking/07. 0017-letter-combinations-of-a-phone-number/code.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vector result; 4 | vector digitMap = { 5 | "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" 6 | }; 7 | 8 | void backtrack(const string& digits, string& current, int index) { 9 | // Base case: if we've processed all digits 10 | if (index >= digits.length()) { 11 | if (!current.empty()) { 12 | result.push_back(current); 13 | } 14 | return; 15 | } 16 | 17 | // Get the letters for current digit 18 | int digit = digits[index] - '0'; 19 | string letters = digitMap[digit]; 20 | 21 | // Try each letter for current digit 22 | for (char letter : letters) { 23 | // Make choice: add letter 24 | current += letter; 25 | 26 | // Recurse to next digit 27 | backtrack(digits, current, index + 1); 28 | 29 | // Backtrack: remove letter 30 | current.pop_back(); 31 | } 32 | } 33 | 34 | public: 35 | vector letterCombinations(string digits) { 36 | if (digits.empty()) { 37 | return result; 38 | } 39 | 40 | string current; 41 | backtrack(digits, current, 0); 42 | return result; 43 | } 44 | }; 45 | 46 | /* 47 | Time Complexity: O(4^n) where n is the length of digits 48 | Space Complexity: O(n) for recursion stack 49 | */ -------------------------------------------------------------------------------- /Common/Math/Reverse Number/README.md: -------------------------------------------------------------------------------- 1 | # 🔁 Reverse a Number – C++ Techniques 2 | 3 | --- 4 | 5 | ## 📘 Problem Statement 6 | 7 | Given an integer `n`, return the number formed by reversing its digits. 8 | 9 | --- 10 | 11 | ## ✳️ Example 12 | 13 | Input: 1234 14 | Output: 4321 15 | 16 | Input: 900 17 | Output: 9 18 | 19 | 20 | --- 21 | 22 | ## 🚀 Approaches 23 | 24 | ### ✅ 1. Using While Loop (Mathematical) 25 | - Extract last digit using `% 10` 26 | - Build the reversed number using: `reversed = reversed * 10 + digit` 27 | - Remove last digit using `/= 10` 28 | 29 | 🕒 **Time Complexity**: O(d) where d = number of digits 30 | 🧠 **Space Complexity**: O(1) 31 | 32 | --- 33 | 34 | ### ✅ 2. Recursive Approach 35 | - Base case: if num == 0 → return reversed 36 | - Recursive step: reverse `num/10` while building reversed number 37 | 38 | 🕒 **Time Complexity**: O(d) 39 | 🧠 **Space Complexity**: O(d) (recursive call stack) 40 | 41 | --- 42 | 43 | ### ✅ 3. Using String Conversion 44 | - Convert number to string 45 | - Reverse the string 46 | - Convert back to integer 47 | 48 | 🕒 **Time Complexity**: O(d) 49 | 🧠 **Space Complexity**: O(d) 50 | 51 | --- 52 | 53 | ### ✅ 4. For Loop (Math Variant) 54 | - More compact math version using `for` loop 55 | - Equivalent logic to the while loop approach 56 | 57 | 🕒 **Time Complexity**: O(d) 58 | 59 | --- 60 | 61 | ## 📂 Folder Structure 62 | ReverseNumberTechniques/ 63 | ├── reverse_number.cpp # Full code with all 4 approaches 64 | ├── README.md # Detailed explanation and usage 65 | ├── Makefile # Build and run commands 66 | -------------------------------------------------------------------------------- /Level 1/Week 03/LinkedList/143. Reorder List/README.md: -------------------------------------------------------------------------------- 1 |

143. Reorder List

Medium


You are given the head of a singly linked-list. The list can be represented as:

2 | 3 |
 4 | L0 → L1 → … → Ln - 1 → Ln
 5 | 
6 | 7 |

Reorder the list to be on the following form:

8 | 9 |
10 | L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
11 | 
12 | 13 |

You may not modify the values in the list's nodes. Only nodes themselves may be changed.

14 | 15 |

 

16 |

Example 1:

17 | 18 |
19 | Input: head = [1,2,3,4]
20 | Output: [1,4,2,3]
21 | 
22 | 23 |

Example 2:

24 | 25 |
26 | Input: head = [1,2,3,4,5]
27 | Output: [1,5,2,4,3]
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • The number of nodes in the list is in the range [1, 5 * 104].
  • 35 |
  • 1 <= Node.val <= 1000
  • 36 |
37 | -------------------------------------------------------------------------------- /Level 1/Week 12/Graph/133. Clone Graph/README.md: -------------------------------------------------------------------------------- 1 | # Clone Graph 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. 8 | 9 | Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. 10 | 11 | Each node in the graph contains a val (`int`) and a list (`List[Node]`) of its neighbors. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: adjList = [[2,4],[1,3],[2,4],[1,3]] 19 | Output: [[2,4],[1,3],[2,4],[1,3]] 20 | 21 | ### Example 2 22 | Input: adjList = [[]] 23 | Output: [[]] 24 | 25 | ### Example 3 26 | Input: adjList = [] 27 | Output: [] 28 | 29 | --- 30 | 31 | ## Constraints 32 | 33 | - The number of nodes in the graph is in the range `[0, 100]`. 34 | - `1 <= Node.val <= 100` 35 | - `Node.val` is unique for each node. 36 | - There are no repeated edges and no self-loops in the graph. 37 | - The Graph is connected and all nodes can be visited starting from the given node. 38 | 39 | --- 40 | 41 | ## Approach 42 | 43 | This problem requires a deep copy of a graph: 44 | 1. Use DFS or BFS to traverse the original graph 45 | 2. Create a new node for each node we visit 46 | 3. Use a hash map to track which nodes have been cloned 47 | 4. Copy the neighbors recursively 48 | 5. Handle the case where a node has already been cloned 49 | 50 | The key insight is to use a hash map to avoid infinite recursion and ensure each node is cloned only once. 51 | 52 | --- 53 | -------------------------------------------------------------------------------- /Level 1/Week 10/Backtracking/17. Letter Combinations of a Phone Number/README.md: -------------------------------------------------------------------------------- 1 | # Letter Combinations of a Phone Number 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. 8 | 9 | A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 10 | 11 | ``` 12 | 2: abc 13 | 3: def 14 | 4: ghi 15 | 5: jkl 16 | 6: mno 17 | 7: pqrs 18 | 8: tuv 19 | 9: wxyz 20 | ``` 21 | 22 | --- 23 | 24 | ## Examples 25 | 26 | ### Example 1 27 | Input: digits = "23" 28 | Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 29 | 30 | ### Example 2 31 | Input: digits = "" 32 | Output: [] 33 | 34 | ### Example 3 35 | Input: digits = "2" 36 | Output: ["a","b","c"] 37 | 38 | --- 39 | 40 | ## Constraints 41 | 42 | - `0 <= digits.length <= 4` 43 | - `digits[i]` is a digit in the range `['2', '9']`. 44 | 45 | --- 46 | 47 | ## Approach 48 | 49 | This problem uses backtracking to generate all possible letter combinations: 50 | 1. We build the combination incrementally by choosing one letter at a time 51 | 2. For each digit, we try all possible letters that it can represent 52 | 3. We use a mapping array to convert digits to letters 53 | 4. We backtrack by removing the last added letter to try different combinations 54 | 5. When we've processed all digits, we add the complete combination to our result 55 | 6. We handle the empty string case separately 56 | 57 | --- 58 | -------------------------------------------------------------------------------- /Level 1/Week 12/Graph/207. Course Schedule/README.md: -------------------------------------------------------------------------------- 1 | # Course Schedule 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`. 8 | 9 | - For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`. 10 | 11 | Return `true` if you can finish all courses. Otherwise, return `false`. 12 | 13 | --- 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | Input: numCourses = 2, prerequisites = [[1,0]] 19 | Output: true 20 | 21 | ### Example 2 22 | Input: numCourses = 2, prerequisites = [[1,0],[0,1]] 23 | Output: false 24 | 25 | --- 26 | 27 | ## Constraints 28 | 29 | - `1 <= numCourses <= 2000` 30 | - `0 <= prerequisites.length <= 5000` 31 | - `prerequisites[i].length == 2` 32 | - `0 <= ai, bi < numCourses` 33 | - All the pairs `prerequisites[i]` are **unique**. 34 | 35 | --- 36 | 37 | ## Approach 38 | 39 | This problem can be solved using topological sort or cycle detection: 40 | 1. Build an adjacency list representation of the graph 41 | 2. Use DFS to detect cycles in the graph 42 | 3. If there's a cycle, it's impossible to complete all courses 43 | 4. Use a visited array to track visited nodes and detect cycles 44 | 5. Return true if no cycles are found 45 | 46 | The key insight is that if there's a cycle in the dependency graph, it's impossible to complete all courses. 47 | 48 | --- 49 | -------------------------------------------------------------------------------- /Level 1/Week 03/LinkedList/2. Add Two Numbers/README.md: -------------------------------------------------------------------------------- 1 |

2. Add Two Numbers

Medium


You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

2 | 3 |

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: l1 = [2,4,3], l2 = [5,6,4]
10 | Output: [7,0,8]
11 | Explanation: 342 + 465 = 807.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: l1 = [0], l2 = [0]
18 | Output: [0]
19 | 
20 | 21 |

Example 3:

22 | 23 |
24 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
25 | Output: [8,9,9,9,0,0,0,1]
26 | 
27 | 28 |

 

29 |

Constraints:

30 | 31 |
    32 |
  • The number of nodes in each linked list is in the range [1, 100].
  • 33 |
  • 0 <= Node.val <= 9
  • 34 |
  • It is guaranteed that the list represents a number that does not have leading zeros.
  • 35 |
36 | -------------------------------------------------------------------------------- /Level 0/8 Trees/11. 0297-serialize-and-deserialize-binary-tree/README.md: -------------------------------------------------------------------------------- 1 | # 297. Serialize and Deserialize Binary Tree 2 | 3 | ## Problem Description 4 | 5 | Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. 6 | 7 | Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. 8 | 9 | **Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-`1,null,2,3,4`-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. 10 | 11 | ## Examples 12 | 13 | ### Example 1: 14 | 15 | **Input:** `root = [1,2,3,null,null,4,5]` 16 | 17 | **Output:** `[1,2,3,null,null,4,5]` 18 | 19 | ### Example 2: 20 | 21 | **Input:** `root = []` 22 | 23 | **Output:** `[]` 24 | 25 | ## Constraints 26 | 27 | - The number of nodes in the tree is in the range `[0, 10^4]`. 28 | - `-1000 <= Node.val <= 1000` 29 | 30 | ## Related Topics 31 | 32 | - String 33 | - Tree 34 | - Depth-First Search 35 | - Breadth-First Search 36 | - Design 37 | - Binary Tree 38 | 39 | ## Difficulty 40 | 41 | Hard 42 | -------------------------------------------------------------------------------- /Level 1/Week 02/Sliding windows/424. Longest Repeating Character Replacement/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach (Sliding Window with Frequency Count): 3 | 4 | We aim to find the length of the longest substring that can be made of the same character after replacing at most `k` characters. 5 | 6 | ⚙️ Logic: 7 | 1. Use a sliding window defined by two pointers: `left` and `right`. 8 | 2. Maintain a frequency array `hash[26]` to count letters in the current window. 9 | 3. Track the most frequent character count in the window as `maxfre`. 10 | 4. If the number of characters to be replaced → `(right - left + 1) - maxfre` > `k`, then shrink the window from the left. 11 | 5. At every step, update the maximum window length. 12 | 13 | ✅ Time Complexity: O(n) 14 | ✅ Space Complexity: O(1) – only 26 alphabet characters 15 | 16 | 📌 Note: 17 | We don't shrink the window on every invalid step — only when needed. This helps us maintain a valid window efficiently. 18 | */ 19 | 20 | class Solution { 21 | public: 22 | int characterReplacement(string s, int k) { 23 | int left = 0; 24 | int maxLen = 0; 25 | int maxfre = 0; 26 | vector hash(26, 0); 27 | 28 | for (int right = 0; right < s.size(); right++) { 29 | hash[s[right] - 'A']++; 30 | maxfre = max(maxfre, hash[s[right] - 'A']); 31 | 32 | if ((right - left + 1) - maxfre > k) { 33 | hash[s[left] - 'A']--; 34 | left++; 35 | } 36 | 37 | maxLen = max(maxLen, right - left + 1); 38 | } 39 | 40 | return maxLen; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Level 1/Week 09/Greedy/1899. Merge Triplets to Form Target Triplet/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: Greedy Algorithm 3 | 4 | The key insight is that we can only use triplets that don't exceed the target in any dimension. 5 | If any element of a triplet is greater than the corresponding target element, 6 | that triplet can never be part of the solution. 7 | 8 | Algorithm: 9 | 1. Filter triplets: only consider triplets where all elements <= corresponding target elements 10 | 2. For valid triplets, track the maximum value we can achieve in each position 11 | 3. Check if we can exactly match the target in all three positions 12 | 13 | Time Complexity: O(n) where n is the number of triplets 14 | Space Complexity: O(1) 15 | */ 16 | 17 | #include 18 | #include 19 | using namespace std; 20 | 21 | class Solution { 22 | public: 23 | bool mergeTriplets(vector>& triplets, vector& target) { 24 | vector maxTriplet(3, 0); 25 | 26 | for (const auto& triplet : triplets) { 27 | // Only consider triplets that don't exceed target in any dimension 28 | if (triplet[0] <= target[0] && triplet[1] <= target[1] && triplet[2] <= target[2]) { 29 | maxTriplet[0] = max(maxTriplet[0], triplet[0]); 30 | maxTriplet[1] = max(maxTriplet[1], triplet[1]); 31 | maxTriplet[2] = max(maxTriplet[2], triplet[2]); 32 | } 33 | } 34 | 35 | return (maxTriplet[0] == target[0] && 36 | maxTriplet[1] == target[1] && 37 | maxTriplet[2] == target[2]); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/24. Swap Nodes in Pairs/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem: 24. Swap Nodes in Pairs 3 | 4 | This is a classic linked list problem that can be solved elegantly using recursion. 5 | Key insights: 6 | 1. We swap the first two nodes at each recursive call 7 | 2. We recursively process the remaining nodes 8 | 3. We need to handle edge cases (empty list, single node) 9 | 4. The recursive approach naturally handles the list structure 10 | 11 | Time Complexity: O(n) - we visit each node once 12 | Space Complexity: O(n) - recursion stack depth 13 | */ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode() : val(0), next(nullptr) {} 21 | * ListNode(int x) : val(x), next(nullptr) {} 22 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 23 | * }; 24 | */ 25 | 26 | class Solution { 27 | public: 28 | ListNode* swapPairs(ListNode* head) { 29 | // Base case: if head is null or only one node remains 30 | if (head == nullptr || head->next == nullptr) { 31 | return head; 32 | } 33 | 34 | // Store the second node as it will become the new head 35 | ListNode* second = head->next; 36 | 37 | // Recursively swap the remaining nodes 38 | ListNode* remaining = swapPairs(second->next); 39 | 40 | // Swap the first two nodes 41 | second->next = head; 42 | head->next = remaining; 43 | 44 | // Return the new head (second node) 45 | return second; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Level 0/7 Sliding Window/09. 0424-longest-repeating-character-replacement/README.md: -------------------------------------------------------------------------------- 1 |

424. Longest Repeating Character Replacement

Medium


You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

2 | 3 |

Return the length of the longest substring containing the same letter you can get after performing the above operations.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: s = "ABAB", k = 2
10 | Output: 4
11 | Explanation: Replace the two 'A's with two 'B's or vice versa.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: s = "AABABBA", k = 1
18 | Output: 4
19 | Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
20 | The substring "BBBB" has the longest repeating letters, which is 4.
21 | There may exists other ways to achieve this answer too.
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • 1 <= s.length <= 105
  • 28 |
  • s consists of only uppercase English letters.
  • 29 |
  • 0 <= k <= s.length
  • 30 |
31 | -------------------------------------------------------------------------------- /Level 1/Week 10/Backtracking/79. Word Search/README.md: -------------------------------------------------------------------------------- 1 | # Word Search 2 | 3 | **Difficulty:** Medium 4 | 5 | ## Problem Description 6 | 7 | Given an `m x n` grid of characters `board` and a string `word`, return `true` *if* `word` *exists in the grid*. 8 | 9 | The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | ### Example 1 16 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" 17 | Output: true 18 | 19 | ### Example 2 20 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" 21 | Output: true 22 | 23 | ### Example 3 24 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" 25 | Output: false 26 | 27 | --- 28 | 29 | ## Constraints 30 | 31 | - `m == board.length` 32 | - `n == board[i].length` 33 | - `1 <= m, n <= 6` 34 | - `1 <= word.length <= 15` 35 | - `board` and `word` consists of only lowercase and uppercase English letters. 36 | 37 | --- 38 | 39 | ## Approach 40 | 41 | This problem uses backtracking with DFS: 42 | 1. We start from each cell in the grid 43 | 2. For each cell, we try to match the first character of the word 44 | 3. If matched, we recursively search in all four directions (up, down, left, right) 45 | 4. We mark visited cells to avoid reusing them 46 | 5. We backtrack by unmarking cells when the current path doesn't lead to a solution 47 | 6. We return true if we can match the entire word 48 | 49 | --- 50 | -------------------------------------------------------------------------------- /Common/Math/Prime/README.md: -------------------------------------------------------------------------------- 1 | # 🔢 Prime Number Checker – C++ Implementations 2 | 3 | --- 4 | 5 | ## 🧠 What is a Prime Number? 6 | 7 | A **prime number** is a natural number greater than 1 that: 8 | - Has exactly **two distinct** positive divisors: **1 and itself** 9 | - Cannot be formed by multiplying two smaller natural numbers 10 | 11 | ### ✅ Examples: 12 | - 2 → Prime (only 1 and 2) 13 | - 3 → Prime (only 1 and 3) 14 | - 4 → ❌ Not Prime (1, 2, 4) 15 | - 5 → Prime 16 | - 6 → ❌ Not Prime (1, 2, 3, 6) 17 | 18 | --- 19 | 20 | ## 📘 What’s Covered? 21 | 22 | This file demonstrates **three distinct approaches** to determine if a number is prime: 23 | 24 | | Approach | Description | 25 | |----------------|---------------------------------------------------| 26 | | Brute Force | Try all numbers from 2 to n-1 | 27 | | Optimized | Try only up to √n (square root) | 28 | | Recursive | Use recursion to divide from 2 up to √n | 29 | 30 | --- 31 | 32 | ## 🗂 File Structure 33 | 34 | Prime/ 35 | │ 36 | ├── prime_number.cpp # All three approaches with comments 37 | ├── README.md # This file 38 | 39 | ├── Makefile # Build and run commands 40 | 41 | --- 42 | 43 | ## 🔍 Sample Usage 44 | 45 | ```cpp 46 | #include 47 | using namespace std; 48 | 49 | int main() { 50 | int n = 29; 51 | 52 | cout << "Brute Force: " << isPrimeBruteForce(n) << endl; 53 | cout << "Optimized: " << isPrimeOptimized(n) << endl; 54 | cout << "Recursive: " << isPrimeRecursive(n) << endl; 55 | 56 | return 0; 57 | } 58 | 59 | -------------------------------------------------------------------------------- /Level 1/Week 02/Sliding windows/424. Longest Repeating Character Replacement/README.md: -------------------------------------------------------------------------------- 1 |

424. Longest Repeating Character Replacement

Medium


You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

2 | 3 |

Return the length of the longest substring containing the same letter you can get after performing the above operations.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: s = "ABAB", k = 2
10 | Output: 4
11 | Explanation: Replace the two 'A's with two 'B's or vice versa.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: s = "AABABBA", k = 1
18 | Output: 4
19 | Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
20 | The substring "BBBB" has the longest repeating letters, which is 4.
21 | There may exists other ways to achieve this answer too.
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • 1 <= s.length <= 105
  • 28 |
  • s consists of only uppercase English letters.
  • 29 |
  • 0 <= k <= s.length
  • 30 |
31 | -------------------------------------------------------------------------------- /Level 1/Week 10/Recursion/206. Reverse Linked List/code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem: 206. Reverse Linked List 3 | 4 | This is a classic recursion problem for reversing a linked list. 5 | Key insights: 6 | 1. Base case: if head is null or only one node remains 7 | 2. Recursive case: reverse the rest of the list 8 | 3. Make the current node point to the reversed list 9 | 4. Return the new head (which is the last node of original list) 10 | 5. The recursive approach naturally handles the reversal by working backwards 11 | 12 | Time Complexity: O(n) - we visit each node once 13 | Space Complexity: O(n) - recursion stack depth 14 | */ 15 | 16 | /** 17 | * Definition for singly-linked list. 18 | * struct ListNode { 19 | * int val; 20 | * ListNode *next; 21 | * ListNode() : val(0), next(nullptr) {} 22 | * ListNode(int x) : val(x), next(nullptr) {} 23 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 24 | * }; 25 | */ 26 | 27 | class Solution { 28 | public: 29 | ListNode* reverseList(ListNode* head) { 30 | // Base case: if head is null or only one node remains 31 | if (head == nullptr || head->next == nullptr) { 32 | return head; 33 | } 34 | 35 | // Recursively reverse the rest of the list 36 | ListNode* reversedRest = reverseList(head->next); 37 | 38 | // Make the current node point to the reversed list 39 | head->next->next = head; 40 | head->next = nullptr; 41 | 42 | // Return the new head (which is the last node of original list) 43 | return reversedRest; 44 | } 45 | }; 46 | --------------------------------------------------------------------------------