-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadvanced-algorithms-database.json
More file actions
367 lines (367 loc) · 24.3 KB
/
advanced-algorithms-database.json
File metadata and controls
367 lines (367 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
{
"metadata": {
"name": "Advanced Algorithms Database",
"description": "Complex data structures and advanced algorithmic patterns for experienced developers",
"difficulty_range": ["medium", "hard"],
"prerequisites": ["variable_manipulation", "array_operations", "hashmap_operations", "basic_trees", "basic_graphs"],
"learning_objectives": [
"Master complex data structures (trees, graphs, heaps)",
"Understand advanced algorithmic patterns (DP, greedy, backtracking)",
"Learn optimization techniques and space-time trade-offs",
"Practice system design and algorithm selection",
"Develop problem-solving intuition for complex scenarios"
],
"total_questions": 60,
"estimated_time": "15-20 hours"
},
"question_categories": {
"tree_algorithms": {
"description": "Binary trees, BST operations, and tree traversals",
"difficulty": "medium",
"count": 15,
"questions": [
{
"id": "tree_301",
"title": "Binary Tree Maximum Path Sum",
"description": "Given a binary tree, find the maximum path sum. A path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections.",
"difficulty": "hard",
"data_structure": "trees",
"pattern": "dfs",
"input_format": "root: TreeNode",
"output_format": "int",
"constraints": "Number of nodes in the tree is in the range [1, 3 * 10^4], -1000 <= Node.val <= 1000",
"test_cases": [
{"input": {"root": [1, 2, 3]}, "output": 6, "explanation": "The optimal path is 2 -> 1 -> 3 with a sum of 6"},
{"input": {"root": [-10, 9, 20, null, null, 15, 7]}, "output": 42, "explanation": "The optimal path is 15 -> 20 -> 7 with a sum of 42"},
{"input": {"root": [-3]}, "output": -3, "explanation": "Single node with negative value"},
{"input": {"root": [1, -2, 3]}, "output": 4, "explanation": "The optimal path is 1 -> 3 with a sum of 4"}
],
"solution_template": "def max_path_sum(root):\n def max_gain(node):\n nonlocal max_sum\n if not node:\n return 0\n \n # Max sum on the left and right sub-trees of node\n left_gain = max(max_gain(node.left), 0)\n right_gain = max(max_gain(node.right), 0)\n \n # The price to start a new path where 'node' is the highest node\n price_newpath = node.val + left_gain + right_gain\n \n # Update max_sum if it's better to start a new path\n max_sum = max(max_sum, price_newpath)\n \n # For recursion: return the max gain if continue the same path\n return node.val + max(left_gain, right_gain)\n \n max_sum = float('-inf')\n max_gain(root)\n return max_sum",
"time_complexity": "O(n)",
"space_complexity": "O(h) where h is the height of the tree",
"tags": ["trees", "dfs", "dynamic_programming", "hard"],
"learning_points": [
"Tree DFS with return values",
"Global maximum tracking",
"Path vs subtree optimization",
"Negative value handling"
]
},
{
"id": "tree_302",
"title": "Serialize and Deserialize Binary Tree",
"description": "Design an algorithm to serialize and deserialize a binary tree. Serialization is the process of converting a data structure into a sequence of bits so that it can be stored in a file or memory buffer.",
"difficulty": "hard",
"data_structure": "trees",
"pattern": "serialization",
"input_format": "root: TreeNode",
"output_format": "str (serialized), TreeNode (deserialized)",
"constraints": "Number of nodes in the tree is in the range [0, 10^4], -1000 <= Node.val <= 1000",
"test_cases": [
{"input": {"root": [1, 2, 3, null, null, 4, 5]}, "output": {"serialized": "1,2,3,#,#,4,5,#,#,#,#", "deserialized": [1, 2, 3, null, null, 4, 5]}, "explanation": "Serialize and deserialize the tree"},
{"input": {"root": []}, "output": {"serialized": "#", "deserialized": []}, "explanation": "Empty tree serialization"},
{"input": {"root": [1]}, "output": {"serialized": "1,#,#", "deserialized": [1]}, "explanation": "Single node tree"}
],
"solution_template": "class Codec:\n def serialize(self, root):\n def preorder(node):\n if not node:\n vals.append('# ')\n return\n vals.append(str(node.val) + ' ')\n preorder(node.left)\n preorder(node.right)\n \n vals = []\n preorder(root)\n return ''.join(vals)\n \n def deserialize(self, data):\n def preorder():\n val = next(vals)\n if val == '#':\n return None\n node = TreeNode(int(val))\n node.left = preorder()\n node.right = preorder()\n return node\n \n vals = iter(data.split())\n return preorder()",
"time_complexity": "O(n) for both serialize and deserialize",
"space_complexity": "O(n) for both serialize and deserialize",
"tags": ["trees", "serialization", "dfs", "hard"],
"learning_points": [
"Tree serialization techniques",
"Preorder traversal for serialization",
"Iterator pattern for deserialization",
"Null node representation"
]
}
]
},
"graph_algorithms": {
"description": "Graph traversal, shortest paths, and network algorithms",
"difficulty": "medium",
"count": 15,
"questions": [
{
"id": "graph_301",
"title": "Course Schedule",
"description": "Given the total number of courses and a list of prerequisite pairs, determine if it's possible to finish all courses.",
"difficulty": "medium",
"data_structure": "graphs",
"pattern": "topological_sort",
"input_format": "numCourses: int, prerequisites: List[List[int]]",
"output_format": "bool",
"constraints": "1 <= numCourses <= 10^5, 0 <= len(prerequisites) <= 5000, prerequisites[i].length == 2",
"test_cases": [
{"input": {"numCourses": 2, "prerequisites": [[1, 0]]}, "output": true, "explanation": "Course 0 -> Course 1, possible to finish"},
{"input": {"numCourses": 2, "prerequisites": [[1, 0], [0, 1]]}, "output": false, "explanation": "Circular dependency, impossible to finish"},
{"input": {"numCourses": 3, "prerequisites": [[1, 0], [2, 1]]}, "output": true, "explanation": "Course 0 -> Course 1 -> Course 2, possible to finish"},
{"input": {"numCourses": 1, "prerequisites": []}, "output": true, "explanation": "Single course with no prerequisites"}
],
"solution_template": "def can_finish(numCourses, prerequisites):\n from collections import defaultdict, deque\n \n # Build adjacency list and in-degree count\n graph = defaultdict(list)\n in_degree = [0] * numCourses\n \n for course, prereq in prerequisites:\n graph[prereq].append(course)\n in_degree[course] += 1\n \n # Find courses with no prerequisites\n queue = deque()\n for i in range(numCourses):\n if in_degree[i] == 0:\n queue.append(i)\n \n # Process courses\n completed = 0\n while queue:\n course = queue.popleft()\n completed += 1\n \n for next_course in graph[course]:\n in_degree[next_course] -= 1\n if in_degree[next_course] == 0:\n queue.append(next_course)\n \n return completed == numCourses",
"time_complexity": "O(V + E) where V is courses, E is prerequisites",
"space_complexity": "O(V + E)",
"tags": ["graphs", "topological_sort", "bfs", "medium"],
"learning_points": [
"Topological sorting",
"Cycle detection in directed graphs",
"In-degree counting",
"BFS for dependency resolution"
]
},
{
"id": "graph_302",
"title": "Word Ladder",
"description": "Given two words and a dictionary, find the length of shortest transformation sequence from beginWord to endWord.",
"difficulty": "hard",
"data_structure": "graphs",
"pattern": "bfs",
"input_format": "beginWord: str, endWord: str, wordList: List[str]",
"output_format": "int",
"constraints": "1 <= len(beginWord) <= 10, 1 <= len(endWord) <= 10, 1 <= len(wordList) <= 5000",
"test_cases": [
{"input": {"beginWord": "hit", "endWord": "cog", "wordList": ["hot", "dot", "dog", "lot", "log", "cog"]}, "output": 5, "explanation": "hit -> hot -> dot -> dog -> cog (5 steps)"},
{"input": {"beginWord": "hit", "endWord": "cog", "wordList": ["hot", "dot", "dog", "lot", "log"]}, "output": 0, "explanation": "endWord not in wordList"},
{"input": {"beginWord": "a", "endWord": "c", "wordList": ["a", "b", "c"]}, "output": 2, "explanation": "a -> c (2 steps)"},
{"input": {"beginWord": "hot", "endWord": "dog", "wordList": ["hot", "dog"]}, "output": 0, "explanation": "No valid transformation"}
],
"solution_template": "def ladder_length(beginWord, endWord, wordList):\n from collections import deque\n \n if endWord not in wordList:\n return 0\n \n wordSet = set(wordList)\n queue = deque([(beginWord, 1)])\n visited = {beginWord}\n \n while queue:\n word, length = queue.popleft()\n \n if word == endWord:\n return length\n \n # Try all possible one-character changes\n for i in range(len(word)):\n for c in 'abcdefghijklmnopqrstuvwxyz':\n if c != word[i]:\n new_word = word[:i] + c + word[i+1:]\n if new_word in wordSet and new_word not in visited:\n visited.add(new_word)\n queue.append((new_word, length + 1))\n \n return 0",
"time_complexity": "O(M^2 * N) where M is word length, N is word count",
"space_complexity": "O(M * N)",
"tags": ["graphs", "bfs", "string_manipulation", "hard"],
"learning_points": [
"BFS for shortest path",
"String transformation",
"Word graph construction",
"Level-by-level traversal"
]
}
]
},
"dynamic_programming": {
"description": "Dynamic programming patterns and optimization problems",
"difficulty": "hard",
"count": 15,
"questions": [
{
"id": "dp_301",
"title": "Longest Increasing Subsequence",
"description": "Given an integer array, return the length of the longest strictly increasing subsequence.",
"difficulty": "medium",
"data_structure": "arrays",
"pattern": "dp",
"input_format": "nums: List[int]",
"output_format": "int",
"constraints": "1 <= len(nums) <= 2500, -10^4 <= nums[i] <= 10^4",
"test_cases": [
{"input": {"nums": [10, 9, 2, 5, 3, 7, 101, 18]}, "output": 4, "explanation": "The longest increasing subsequence is [2, 3, 7, 101]"},
{"input": {"nums": [0, 1, 0, 3, 2, 3]}, "output": 4, "explanation": "The longest increasing subsequence is [0, 1, 2, 3]"},
{"input": {"nums": [7, 7, 7, 7, 7, 7, 7]}, "output": 1, "explanation": "The longest increasing subsequence is [7]"},
{"input": {"nums": [1, 3, 6, 7, 9, 4, 10, 5, 6]}, "output": 6, "explanation": "The longest increasing subsequence is [1, 3, 4, 5, 6, 10]"}
],
"solution_template": "def length_of_lis(nums):\n if not nums:\n return 0\n \n dp = [1] * len(nums)\n \n for i in range(1, len(nums)):\n for j in range(i):\n if nums[j] < nums[i]:\n dp[i] = max(dp[i], dp[j] + 1)\n \n return max(dp)",
"time_complexity": "O(n^2)",
"space_complexity": "O(n)",
"optimized_solution": "def length_of_lis_optimized(nums):\n import bisect\n \n tails = []\n for num in nums:\n pos = bisect.bisect_left(tails, num)\n if pos == len(tails):\n tails.append(num)\n else:\n tails[pos] = num\n \n return len(tails)",
"optimized_time_complexity": "O(n log n)",
"optimized_space_complexity": "O(n)",
"tags": ["arrays", "dp", "binary_search", "medium"],
"learning_points": [
"Dynamic programming state definition",
"Optimal substructure",
"Binary search optimization",
"Patience sorting algorithm"
]
},
{
"id": "dp_302",
"title": "Edit Distance",
"description": "Given two strings, return the minimum number of operations required to convert word1 to word2. Operations: insert, delete, or replace a character.",
"difficulty": "hard",
"data_structure": "strings",
"pattern": "dp",
"input_format": "word1: str, word2: str",
"output_format": "int",
"constraints": "0 <= len(word1), len(word2) <= 500, word1 and word2 consist of lowercase English letters",
"test_cases": [
{"input": {"word1": "horse", "word2": "ros"}, "output": 3, "explanation": "horse -> rorse -> rose -> ros (3 operations)"},
{"input": {"word1": "intention", "word2": "execution"}, "output": 5, "explanation": "intention -> inention -> enention -> exention -> exection -> execution (5 operations)"},
{"input": {"word1": "", "word2": "a"}, "output": 1, "explanation": "Insert 'a' (1 operation)"},
{"input": {"word1": "a", "word2": ""}, "output": 1, "explanation": "Delete 'a' (1 operation)"}
],
"solution_template": "def min_distance(word1, word2):\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n \n # Base cases\n for i in range(m + 1):\n dp[i][0] = i\n for j in range(n + 1):\n dp[0][j] = j\n \n # Fill the DP table\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if word1[i-1] == word2[j-1]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = 1 + min(\n dp[i-1][j], # Delete\n dp[i][j-1], # Insert\n dp[i-1][j-1] # Replace\n )\n \n return dp[m][n]",
"time_complexity": "O(m * n)",
"space_complexity": "O(m * n)",
"tags": ["strings", "dp", "edit_distance", "hard"],
"learning_points": [
"2D dynamic programming",
"Edit distance algorithm",
"Base case initialization",
"State transition logic"
]
}
]
},
"greedy_algorithms": {
"description": "Greedy algorithms and optimization problems",
"difficulty": "medium",
"count": 8,
"questions": [
{
"id": "greedy_301",
"title": "Jump Game",
"description": "Given an array of non-negative integers, you are initially positioned at the first index. Each element represents your maximum jump length. Determine if you can reach the last index.",
"difficulty": "medium",
"data_structure": "arrays",
"pattern": "greedy",
"input_format": "nums: List[int]",
"output_format": "bool",
"constraints": "1 <= len(nums) <= 10^4, 0 <= nums[i] <= 10^5",
"test_cases": [
{"input": {"nums": [2, 3, 1, 1, 4]}, "output": true, "explanation": "Jump 1 step from index 0 to 1, then 3 steps to the last index"},
{"input": {"nums": [3, 2, 1, 0, 4]}, "output": false, "explanation": "You will always arrive at index 3 no matter what. Its maximum jump length is 0"},
{"input": {"nums": [0]}, "output": true, "explanation": "Already at the last index"},
{"input": {"nums": [1, 0, 1, 0]}, "output": false, "explanation": "Cannot reach the last index"}
],
"solution_template": "def can_jump(nums):\n max_reach = 0\n \n for i in range(len(nums)):\n if i > max_reach:\n return False\n max_reach = max(max_reach, i + nums[i])\n if max_reach >= len(nums) - 1:\n return True\n \n return True",
"time_complexity": "O(n)",
"space_complexity": "O(1)",
"tags": ["arrays", "greedy", "medium"],
"learning_points": [
"Greedy approach",
"Maximum reach tracking",
"Early termination",
"Single pass solution"
]
},
{
"id": "greedy_302",
"title": "Gas Station",
"description": "Given gas stations and costs, determine the starting gas station's index if you can travel around the circuit once, otherwise return -1.",
"difficulty": "medium",
"data_structure": "arrays",
"pattern": "greedy",
"input_format": "gas: List[int], cost: List[int]",
"output_format": "int",
"constraints": "len(gas) == len(cost), 1 <= len(gas) <= 10^4, 0 <= gas[i], cost[i] <= 10^4",
"test_cases": [
{"input": {"gas": [1, 2, 3, 4, 5], "cost": [3, 4, 5, 1, 2]}, "output": 3, "explanation": "Start at station 3 (index 3) and fill up with 4 units of gas"},
{"input": {"gas": [2, 3, 4], "cost": [3, 4, 3]}, "output": -1, "explanation": "Cannot complete the circuit"},
{"input": {"gas": [5, 1, 2, 3, 4], "cost": [4, 4, 1, 5, 1]}, "output": 4, "explanation": "Start at station 4 (index 4)"},
{"input": {"gas": [1, 1, 1, 1, 1], "cost": [1, 1, 1, 1, 1]}, "output": 0, "explanation": "Can start at any station"}
],
"solution_template": "def can_complete_circuit(gas, cost):\n total_tank = 0\n current_tank = 0\n start_station = 0\n \n for i in range(len(gas)):\n total_tank += gas[i] - cost[i]\n current_tank += gas[i] - cost[i]\n \n if current_tank < 0:\n start_station = i + 1\n current_tank = 0\n \n return start_station if total_tank >= 0 else -1",
"time_complexity": "O(n)",
"space_complexity": "O(1)",
"tags": ["arrays", "greedy", "medium"],
"learning_points": [
"Greedy algorithm design",
"Total vs current tank tracking",
"Circuit completion logic",
"Single pass solution"
]
}
]
},
"backtracking": {
"description": "Backtracking algorithms and constraint satisfaction",
"difficulty": "hard",
"count": 7,
"questions": [
{
"id": "backtrack_301",
"title": "N-Queens",
"description": "Place n queens on an n×n chessboard such that no two queens attack each other. Return all distinct solutions.",
"difficulty": "hard",
"data_structure": "arrays",
"pattern": "backtracking",
"input_format": "n: int",
"output_format": "List[List[str]]",
"constraints": "1 <= n <= 9",
"test_cases": [
{"input": {"n": 4}, "output": [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]], "explanation": "Two distinct solutions for 4-queens problem"},
{"input": {"n": 1}, "output": [["Q"]], "explanation": "Single queen on 1x1 board"},
{"input": {"n": 2}, "output": [], "explanation": "No solution for 2-queens problem"},
{"input": {"n": 3}, "output": [], "explanation": "No solution for 3-queens problem"}
],
"solution_template": "def solve_n_queens(n):\n def is_safe(row, col, board):\n # Check column\n for i in range(row):\n if board[i][col] == 'Q':\n return False\n \n # Check diagonal (top-left to bottom-right)\n i, j = row - 1, col - 1\n while i >= 0 and j >= 0:\n if board[i][j] == 'Q':\n return False\n i -= 1\n j -= 1\n \n # Check diagonal (top-right to bottom-left)\n i, j = row - 1, col + 1\n while i >= 0 and j < n:\n if board[i][j] == 'Q':\n return False\n i -= 1\n j += 1\n \n return True\n \n def backtrack(row, board, result):\n if row == n:\n result.append([''.join(row) for row in board])\n return\n \n for col in range(n):\n if is_safe(row, col, board):\n board[row][col] = 'Q'\n backtrack(row + 1, board, result)\n board[row][col] = '.'\n \n result = []\n board = [['.' for _ in range(n)] for _ in range(n)]\n backtrack(0, board, result)\n return result",
"time_complexity": "O(N!)",
"space_complexity": "O(N^2)",
"tags": ["arrays", "backtracking", "hard"],
"learning_points": [
"Backtracking algorithm",
"Constraint checking",
"State space exploration",
"Recursive solution building"
]
}
]
}
},
"progression_path": {
"medium": {
"focus": "Tree algorithms and graph traversal",
"questions": ["tree_301", "graph_301", "dp_301", "greedy_301", "greedy_302"],
"learning_goal": "Master tree operations, graph algorithms, and basic DP patterns"
},
"hard": {
"focus": "Complex algorithms and optimization",
"questions": ["tree_302", "graph_302", "dp_302", "backtrack_301"],
"learning_goal": "Master advanced algorithms, system design, and complex problem solving"
}
},
"algorithm_selection_guide": {
"when_to_use_dp": {
"indicators": ["optimal substructure", "overlapping subproblems", "optimization problems"],
"examples": ["longest common subsequence", "edit distance", "knapsack problems"],
"time_complexity": "O(n^2) to O(n^3) typically",
"space_complexity": "O(n) to O(n^2) typically"
},
"when_to_use_greedy": {
"indicators": ["local optimal choice", "no need to backtrack", "optimization problems"],
"examples": ["activity selection", "huffman coding", "minimum spanning tree"],
"time_complexity": "O(n log n) typically",
"space_complexity": "O(1) to O(n) typically"
},
"when_to_use_backtracking": {
"indicators": ["constraint satisfaction", "exhaustive search needed", "decision problems"],
"examples": ["n-queens", "sudoku solver", "permutation generation"],
"time_complexity": "O(b^d) where b is branching factor, d is depth",
"space_complexity": "O(d) for recursion depth"
},
"when_to_use_graph_algorithms": {
"indicators": ["network problems", "relationship modeling", "path finding"],
"examples": ["shortest path", "cycle detection", "topological sorting"],
"time_complexity": "O(V + E) for BFS/DFS, O(V log V + E) for Dijkstra",
"space_complexity": "O(V + E) typically"
}
},
"performance_optimization": {
"time_complexity_optimization": {
"techniques": ["memoization", "tabulation", "space-time trade-offs", "algorithm selection"],
"examples": ["DP with memoization", "sliding window", "two pointers", "binary search"]
},
"space_complexity_optimization": {
"techniques": ["in-place algorithms", "iterative solutions", "space-efficient data structures"],
"examples": ["in-place array reversal", "iterative DFS", "rolling hash"]
}
},
"common_patterns": {
"divide_and_conquer": {
"description": "Break problem into smaller subproblems",
"use_cases": ["merge sort", "quick sort", "binary search", "closest pair"],
"time_complexity": "O(n log n) typically",
"space_complexity": "O(log n) for recursion"
},
"sliding_window": {
"description": "Maintain a window of elements",
"use_cases": ["substring problems", "subarray problems", "window-based optimization"],
"time_complexity": "O(n)",
"space_complexity": "O(k) where k is window size"
},
"two_pointers": {
"description": "Use two pointers to traverse data",
"use_cases": ["sorted array problems", "palindrome checking", "pair finding"],
"time_complexity": "O(n)",
"space_complexity": "O(1)"
}
}
}