File size: 32,251 Bytes
3498b25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74c6467
3498b25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
import gradio as gr
import json
from typing import Dict, List, Tuple, Set

class DSALearningRoadmap:
    def __init__(self):
        self.topics_data = {
            "Arrays": {
                "difficulty": "Beginner",
                "prerequisites": [],
                "description": "Linear data structure storing elements in contiguous memory locations",
                "key_concepts": ["Indexing", "Traversal", "Insertion", "Deletion", "Searching"],
                "learning_path": [
                    "Understand array basics and memory layout",
                    "Learn array operations (CRUD)",
                    "Practice basic array problems",
                    "Master array traversal patterns",
                    "Solve sliding window problems"
                ],
                "time_estimate": "1-2 weeks",
                "connects_to": ["Strings", "Sorting", "Searching", "Dynamic Programming", "Two Pointers"],
                "important_problems": [
                    "Two Sum", "Maximum Subarray", "Rotate Array", "Merge Sorted Arrays", "Find Duplicates"
                ]
            },
            "Strings": {
                "difficulty": "Beginner",
                "prerequisites": ["Arrays"],
                "description": "Sequence of characters, often implemented as character arrays",
                "key_concepts": ["String manipulation", "Pattern matching", "Substring operations", "String comparison"],
                "learning_path": [
                    "Learn string basics and operations",
                    "Practice string manipulation problems",
                    "Master substring and pattern matching",
                    "Learn string algorithms (KMP, Rabin-Karp)",
                    "Solve advanced string problems"
                ],
                "time_estimate": "2-3 weeks",
                "connects_to": ["Arrays", "Hashing", "Tries", "Dynamic Programming"],
                "important_problems": [
                    "Valid Palindrome", "Longest Substring Without Repeating Characters", "Group Anagrams", "String to Integer", "Implement strStr()"
                ]
            },
            "Linked Lists": {
                "difficulty": "Beginner",
                "prerequisites": ["Arrays"],
                "description": "Linear data structure where elements are stored in nodes connected via pointers",
                "key_concepts": ["Pointers", "Node operations", "Traversal", "Insertion", "Deletion"],
                "learning_path": [
                    "Understand pointers and node structure",
                    "Learn basic linked list operations",
                    "Practice traversal and manipulation",
                    "Master different types (singly, doubly, circular)",
                    "Solve complex linked list problems"
                ],
                "time_estimate": "2-3 weeks",
                "connects_to": ["Stacks", "Queues", "Trees", "Graphs", "Hashing"],
                "important_problems": [
                    "Reverse Linked List", "Merge Two Sorted Lists", "Detect Cycle", "Remove Nth Node", "Intersection of Two Linked Lists"
                ]
            },
            "Stacks": {
                "difficulty": "Beginner",
                "prerequisites": ["Arrays", "Linked Lists"],
                "description": "LIFO (Last In First Out) data structure",
                "key_concepts": ["Push", "Pop", "Peek", "Stack overflow", "Applications"],
                "learning_path": [
                    "Learn stack concept and operations",
                    "Implement stack using arrays and linked lists",
                    "Practice basic stack problems",
                    "Learn stack applications (expression evaluation, parsing)",
                    "Master advanced stack problems"
                ],
                "time_estimate": "1-2 weeks",
                "connects_to": ["Queues", "Recursion", "Trees", "Graphs", "Dynamic Programming"],
                "important_problems": [
                    "Valid Parentheses", "Min Stack", "Evaluate Reverse Polish Notation", "Largest Rectangle in Histogram", "Daily Temperatures"
                ]
            },
            "Queues": {
                "difficulty": "Beginner",
                "prerequisites": ["Arrays", "Linked Lists"],
                "description": "FIFO (First In First Out) data structure",
                "key_concepts": ["Enqueue", "Dequeue", "Front", "Rear", "Circular queue"],
                "learning_path": [
                    "Learn queue concept and operations",
                    "Implement queue using arrays and linked lists",
                    "Practice basic queue problems",
                    "Learn different types (circular, priority, deque)",
                    "Master BFS and queue applications"
                ],
                "time_estimate": "1-2 weeks",
                "connects_to": ["Stacks", "Trees", "Graphs", "BFS", "Priority Queues"],
                "important_problems": [
                    "Implement Queue using Stacks", "Sliding Window Maximum", "Design Circular Queue", "Rotting Oranges", "First Unique Character"
                ]
            },
            "Recursion": {
                "difficulty": "Intermediate",
                "prerequisites": ["Arrays", "Stacks"],
                "description": "Problem-solving technique where a function calls itself",
                "key_concepts": ["Base case", "Recursive case", "Call stack", "Memoization", "Tail recursion"],
                "learning_path": [
                    "Understand recursion concept and base cases",
                    "Practice simple recursive problems",
                    "Learn recursive patterns and techniques",
                    "Master backtracking using recursion",
                    "Optimize recursive solutions"
                ],
                "time_estimate": "2-3 weeks",
                "connects_to": ["Dynamic Programming", "Trees", "Graphs", "Backtracking", "Divide and Conquer"],
                "important_problems": [
                    "Fibonacci Sequence", "Factorial", "Tower of Hanoi", "Generate Parentheses", "Permutations"
                ]
            },
            "Sorting": {
                "difficulty": "Intermediate",
                "prerequisites": ["Arrays", "Recursion"],
                "description": "Algorithms to arrange elements in a specific order",
                "key_concepts": ["Comparison sorting", "Time complexity", "Space complexity", "Stability", "In-place sorting"],
                "learning_path": [
                    "Learn basic sorting algorithms (bubble, selection, insertion)",
                    "Master efficient sorting algorithms (merge, quick, heap)",
                    "Understand time and space complexity analysis",
                    "Practice sorting-based problems",
                    "Learn specialized sorting techniques"
                ],
                "time_estimate": "2-3 weeks",
                "connects_to": ["Arrays", "Divide and Conquer", "Heaps", "Searching", "Trees"],
                "important_problems": [
                    "Merge Intervals", "Sort Colors", "Kth Largest Element", "Meeting Rooms", "Largest Number"
                ]
            },
            "Searching": {
                "difficulty": "Intermediate",
                "prerequisites": ["Arrays", "Recursion", "Sorting"],
                "description": "Algorithms to find specific elements in data structures",
                "key_concepts": ["Linear search", "Binary search", "Search space", "Invariants", "Applications"],
                "learning_path": [
                    "Learn linear search and its applications",
                    "Master binary search and its variants",
                    "Practice search in rotated/modified arrays",
                    "Learn search in 2D arrays and matrices",
                    "Solve complex search problems"
                ],
                "time_estimate": "2-3 weeks",
                "connects_to": ["Arrays", "Sorting", "Trees", "Graphs", "Two Pointers"],
                "important_problems": [
                    "Binary Search", "Find First and Last Position", "Search in Rotated Array", "Find Peak Element", "Search 2D Matrix"
                ]
            },
            "Trees": {
                "difficulty": "Intermediate",
                "prerequisites": ["Linked Lists", "Recursion", "Stacks", "Queues"],
                "description": "Hierarchical data structure with nodes connected by edges",
                "key_concepts": ["Root", "Leaves", "Height", "Depth", "Traversals", "Binary trees"],
                "learning_path": [
                    "Learn tree terminology and concepts",
                    "Master tree traversals (inorder, preorder, postorder)",
                    "Practice binary tree problems",
                    "Learn binary search trees (BST)",
                    "Solve advanced tree problems"
                ],
                "time_estimate": "3-4 weeks",
                "connects_to": ["Graphs", "Heaps", "Tries", "Dynamic Programming", "DFS", "BFS"],
                "important_problems": [
                    "Maximum Depth of Binary Tree", "Validate Binary Search Tree", "Lowest Common Ancestor", "Binary Tree Level Order Traversal", "Serialize and Deserialize Binary Tree"
                ]
            },
            "Graphs": {
                "difficulty": "Advanced",
                "prerequisites": ["Trees", "Queues", "Stacks", "Recursion"],
                "description": "Non-linear data structure consisting of vertices and edges",
                "key_concepts": ["Vertices", "Edges", "Directed/Undirected", "Weighted/Unweighted", "Representation"],
                "learning_path": [
                    "Learn graph terminology and representation",
                    "Master graph traversals (DFS, BFS)",
                    "Practice basic graph problems",
                    "Learn shortest path algorithms",
                    "Solve complex graph problems"
                ],
                "time_estimate": "4-5 weeks",
                "connects_to": ["Trees", "DFS", "BFS", "Dynamic Programming", "Greedy Algorithms"],
                "important_problems": [
                    "Clone Graph", "Number of Islands", "Course Schedule", "Shortest Path in Binary Matrix", "Word Ladder"
                ]
            },
            "Dynamic Programming": {
                "difficulty": "Advanced",
                "prerequisites": ["Arrays", "Recursion", "Trees"],
                "description": "Optimization technique using memoization to solve overlapping subproblems",
                "key_concepts": ["Optimal substructure", "Overlapping subproblems", "Memoization", "Tabulation", "State transitions"],
                "learning_path": [
                    "Understand DP concepts and when to use",
                    "Learn basic DP patterns (fibonacci, climbing stairs)",
                    "Practice 1D DP problems",
                    "Master 2D DP problems",
                    "Solve complex DP problems"
                ],
                "time_estimate": "4-6 weeks",
                "connects_to": ["Arrays", "Strings", "Trees", "Graphs", "Greedy Algorithms"],
                "important_problems": [
                    "Climbing Stairs", "House Robber", "Coin Change", "Longest Common Subsequence", "Edit Distance"
                ]
            },
            "Hashing": {
                "difficulty": "Intermediate",
                "prerequisites": ["Arrays", "Strings"],
                "description": "Technique for fast data retrieval using hash functions",
                "key_concepts": ["Hash functions", "Hash tables", "Collision resolution", "Load factor", "Applications"],
                "learning_path": [
                    "Learn hash function concepts",
                    "Understand hash table implementation",
                    "Practice basic hashing problems",
                    "Learn collision resolution techniques",
                    "Master advanced hashing applications"
                ],
                "time_estimate": "2-3 weeks",
                "connects_to": ["Arrays", "Strings", "Sets", "Maps", "Caching"],
                "important_problems": [
                    "Two Sum", "Group Anagrams", "First Non-Repeating Character", "Longest Substring Without Repeating Characters", "Design HashSet"
                ]
            },
            "Heaps": {
                "difficulty": "Advanced",
                "prerequisites": ["Trees", "Arrays", "Sorting"],
                "description": "Complete binary tree with heap property (min-heap or max-heap)",
                "key_concepts": ["Heap property", "Heapify", "Priority queue", "Heap operations", "Applications"],
                "learning_path": [
                    "Learn heap concepts and properties",
                    "Implement heap operations",
                    "Practice basic heap problems",
                    "Master priority queue applications",
                    "Solve complex heap problems"
                ],
                "time_estimate": "2-3 weeks",
                "connects_to": ["Trees", "Sorting", "Graphs", "Greedy Algorithms", "Priority Queues"],
                "important_problems": [
                    "Kth Largest Element", "Merge K Sorted Lists", "Top K Frequent Elements", "Find Median from Data Stream", "Task Scheduler"
                ]
            },
            "Tries": {
                "difficulty": "Advanced",
                "prerequisites": ["Trees", "Strings"],
                "description": "Tree-like data structure for storing strings efficiently",
                "key_concepts": ["Prefix tree", "Autocomplete", "Word search", "Memory optimization", "Applications"],
                "learning_path": [
                    "Learn trie structure and operations",
                    "Implement basic trie functionality",
                    "Practice word-based problems",
                    "Master prefix matching applications",
                    "Solve complex trie problems"
                ],
                "time_estimate": "2-3 weeks",
                "connects_to": ["Trees", "Strings", "DFS", "Backtracking"],
                "important_problems": [
                    "Implement Trie", "Word Search II", "Design Add and Search Words", "Longest Word in Dictionary", "Replace Words"
                ]
            },
            "Two Pointers": {
                "difficulty": "Intermediate",
                "prerequisites": ["Arrays", "Strings", "Sorting"],
                "description": "Technique using two pointers to solve problems efficiently",
                "key_concepts": ["Left-right pointers", "Fast-slow pointers", "Sliding window", "Meet in middle", "Optimization"],
                "learning_path": [
                    "Learn two-pointer technique basics",
                    "Practice left-right pointer problems",
                    "Master fast-slow pointer technique",
                    "Learn sliding window applications",
                    "Solve complex two-pointer problems"
                ],
                "time_estimate": "2-3 weeks",
                "connects_to": ["Arrays", "Strings", "Linked Lists", "Sorting", "Searching"],
                "important_problems": [
                    "Two Sum II", "3Sum", "Container With Most Water", "Trapping Rain Water", "Longest Substring Without Repeating Characters"
                ]
            },
            "Greedy Algorithms": {
                "difficulty": "Advanced",
                "prerequisites": ["Sorting", "Arrays", "Graphs"],
                "description": "Problem-solving technique making locally optimal choices",
                "key_concepts": ["Greedy choice", "Local optimization", "Proof techniques", "Activity selection", "Optimization"],
                "learning_path": [
                    "Learn greedy algorithm concepts",
                    "Practice basic greedy problems",
                    "Master interval scheduling problems",
                    "Learn graph-based greedy algorithms",
                    "Solve complex greedy problems"
                ],
                "time_estimate": "3-4 weeks",
                "connects_to": ["Sorting", "Graphs", "Dynamic Programming", "Heaps"],
                "important_problems": [
                    "Activity Selection", "Fractional Knapsack", "Minimum Spanning Tree", "Huffman Coding", "Gas Station"
                ]
            },
            "Backtracking": {
                "difficulty": "Advanced",
                "prerequisites": ["Recursion", "Trees", "Arrays"],
                "description": "Algorithmic technique for finding solutions by exploring all possibilities",
                "key_concepts": ["State space", "Pruning", "Constraint satisfaction", "Recursive exploration", "Optimization"],
                "learning_path": [
                    "Learn backtracking concepts",
                    "Practice basic backtracking problems",
                    "Master constraint satisfaction problems",
                    "Learn optimization techniques",
                    "Solve complex backtracking problems"
                ],
                "time_estimate": "3-4 weeks",
                "connects_to": ["Recursion", "Trees", "Graphs", "Dynamic Programming"],
                "important_problems": [
                    "N-Queens", "Sudoku Solver", "Word Search", "Combination Sum", "Palindrome Partitioning"
                ]
            },
            "Divide and Conquer": {
                "difficulty": "Advanced",
                "prerequisites": ["Recursion", "Sorting", "Arrays"],
                "description": "Problem-solving technique dividing problems into smaller subproblems",
                "key_concepts": ["Divide", "Conquer", "Combine", "Recurrence relations", "Master theorem"],
                "learning_path": [
                    "Learn divide and conquer concepts",
                    "Practice basic divide and conquer problems",
                    "Master sorting algorithms using D&C",
                    "Learn advanced applications",
                    "Analyze time complexity"
                ],
                "time_estimate": "3-4 weeks",
                "connects_to": ["Recursion", "Sorting", "Trees", "Dynamic Programming"],
                "important_problems": [
                    "Merge Sort", "Quick Sort", "Maximum Subarray", "Closest Pair of Points", "Strassen's Matrix Multiplication"
                ]
            }
        }
    
    def get_topic_roadmap(self, topic_name: str) -> str:
        """Generate detailed roadmap for a specific topic"""
        if topic_name not in self.topics_data:
            return "❌ Topic not found! Please select a valid topic."
        
        topic = self.topics_data[topic_name]
        
        # Build the roadmap string
        roadmap = f"""
# 🎯 {topic_name} Learning Roadmap

## πŸ“Š Overview
**Difficulty Level:** {topic['difficulty']}  
**Estimated Time:** {topic['time_estimate']}  
**Description:** {topic['description']}

## πŸ”— Prerequisites
"""
        
        if topic['prerequisites']:
            roadmap += "**You should learn these topics first:**\n"
            for prereq in topic['prerequisites']:
                roadmap += f"β€’ {prereq}\n"
        else:
            roadmap += "**Great news!** This is a foundational topic - no prerequisites needed! πŸŽ‰\n"
        
        roadmap += f"""
## πŸ—ΊοΈ Learning Path
**Follow this step-by-step approach:**

"""
        
        for i, step in enumerate(topic['learning_path'], 1):
            roadmap += f"{i}. {step}\n"
        
        roadmap += f"""
## πŸ”‘ Key Concepts to Master
"""
        for concept in topic['key_concepts']:
            roadmap += f"β€’ {concept}\n"
        
        roadmap += f"""
## πŸ’‘ Important Problems to Practice
"""
        for problem in topic['important_problems']:
            roadmap += f"β€’ {problem}\n"
        
        roadmap += f"""
## 🌐 Connected Topics
**After mastering {topic_name}, you'll be ready for:**
"""
        for connected in topic['connects_to']:
            roadmap += f"β€’ {connected}\n"
        
        return roadmap
    
    def get_prerequisites_chain(self, topic_name: str) -> str:
        """Get the complete prerequisite chain for a topic"""
        if topic_name not in self.topics_data:
            return "❌ Topic not found!"
        
        visited = set()
        chain = []
        
        def dfs_prerequisites(topic):
            if topic in visited or topic not in self.topics_data:
                return
            
            visited.add(topic)
            
            # Add prerequisites first
            for prereq in self.topics_data[topic]['prerequisites']:
                dfs_prerequisites(prereq)
            
            chain.append(topic)
        
        dfs_prerequisites(topic_name)
        
        if len(chain) <= 1:
            return f"πŸŽ‰ **{topic_name}** is a foundational topic - you can start learning it right away!"
        
        result = f"πŸ“š **Complete Learning Path to Master {topic_name}:**\n\n"
        
        for i, topic in enumerate(chain, 1):
            difficulty = self.topics_data[topic]['difficulty']
            time_est = self.topics_data[topic]['time_estimate']
            
            if i == len(chain):
                result += f"🎯 **{i}. {topic}** (Your Target!)  \n"
            else:
                result += f"πŸ“– **{i}. {topic}**  \n"
            
            result += f"   *Difficulty: {difficulty} | Time: {time_est}*\n\n"
        
        total_topics = len(chain)
        result += f"**Total Topics to Cover:** {total_topics}\n"
        result += f"**Estimated Total Time:** {self._estimate_total_time(chain)}\n"
        
        return result
    
    def _estimate_total_time(self, chain: List[str]) -> str:
        """Estimate total time needed for a chain of topics"""
        total_weeks = 0
        for topic in chain:
            time_str = self.topics_data[topic]['time_estimate']
            # Extract weeks from string like "2-3 weeks"
            weeks = time_str.split()[0].split('-')
            avg_weeks = (int(weeks[0]) + int(weeks[-1])) / 2
            total_weeks += avg_weeks
        
        return f"{int(total_weeks)} weeks"
    
    def get_topic_connections(self, topic_name: str) -> str:
        """Show how a topic connects to other topics"""
        if topic_name not in self.topics_data:
            return "❌ Topic not found!"
        
        topic = self.topics_data[topic_name]
        
        result = f"πŸ”— **Topic Interconnections for {topic_name}**\n\n"
        
        # Prerequisites
        result += "**πŸ“š Prerequisites (Learn these first):**\n"
        if topic['prerequisites']:
            for prereq in topic['prerequisites']:
                result += f"β€’ {prereq}\n"
        else:
            result += "β€’ None - This is a foundational topic! πŸŽ‰\n"
        
        # What connects to this topic
        result += f"\n**➑️ What {topic_name} enables:**\n"
        for connected in topic['connects_to']:
            result += f"β€’ {connected}\n"
        
        # Find what topics depend on this one
        dependents = []
        for other_topic, other_data in self.topics_data.items():
            if topic_name in other_data['prerequisites']:
                dependents.append(other_topic)
        
        if dependents:
            result += f"\n**🎯 Topics that require {topic_name}:**\n"
            for dependent in dependents:
                result += f"β€’ {dependent}\n"
        
        return result
    
    def get_difficulty_based_roadmap(self, difficulty: str) -> str:
        """Get all topics for a specific difficulty level"""
        topics_by_difficulty = {
            'Beginner': [],
            'Intermediate': [],
            'Advanced': []
        }
        
        for topic_name, topic_data in self.topics_data.items():
            topics_by_difficulty[topic_data['difficulty']].append(topic_name)
        
        if difficulty not in topics_by_difficulty:
            return "❌ Invalid difficulty level!"
        
        result = f"πŸ“Š **{difficulty} Level DSA Topics**\n\n"
        
        topics = topics_by_difficulty[difficulty]
        if not topics:
            result += "No topics found for this difficulty level."
            return result
        
        for i, topic in enumerate(topics, 1):
            topic_data = self.topics_data[topic]
            result += f"**{i}. {topic}**\n"
            result += f"   *Time: {topic_data['time_estimate']}*\n"
            result += f"   *{topic_data['description']}*\n\n"
        
        return result
    
    def get_all_topics_overview(self) -> str:
        """Get overview of all topics with their relationships"""
        result = "πŸ—ΊοΈ **Complete DSA Topics Overview**\n\n"
        
        # Group by difficulty
        by_difficulty = {'Beginner': [], 'Intermediate': [], 'Advanced': []}
        for topic, data in self.topics_data.items():
            by_difficulty[data['difficulty']].append(topic)
        
        for difficulty in ['Beginner', 'Intermediate', 'Advanced']:
            result += f"## {difficulty} Topics\n"
            for topic in by_difficulty[difficulty]:
                result += f"β€’ **{topic}** ({self.topics_data[topic]['time_estimate']})\n"
            result += "\n"
        
        result += "**πŸ’‘ Tips:**\n"
        result += "β€’ Start with Beginner topics if you're new to DSA\n"
        result += "β€’ Each topic builds upon previous knowledge\n"
        result += "β€’ Practice problems regularly to reinforce concepts\n"
        result += "β€’ Focus on understanding connections between topics\n"
        
        return result

# Initialize the DSA roadmap system
dsa_system = DSALearningRoadmap()

# Get list of all topics for dropdown
all_topics = list(dsa_system.topics_data.keys())
difficulty_levels = ['All', 'Beginner', 'Intermediate', 'Advanced']

def generate_roadmap(topic_name):
    """Generate roadmap for selected topic"""
    return dsa_system.get_topic_roadmap(topic_name)

def show_prerequisites_chain(topic_name):
    """Show complete prerequisite chain"""
    return dsa_system.get_prerequisites_chain(topic_name)

def show_topic_connections(topic_name):
    """Show topic interconnections"""
    return dsa_system.get_topic_connections(topic_name)

def show_difficulty_roadmap(difficulty):
    """Show topics by difficulty"""
    if difficulty == 'All':
        return dsa_system.get_all_topics_overview()
    return dsa_system.get_difficulty_based_roadmap(difficulty)

# Create the Gradio interface
with gr.Blocks(title="🎯 DSA Learning Roadmap", theme=gr.themes.Default()) as app:
    gr.Markdown("""
    # 🎯 DSA Learning Roadmap Generator
    
    **Solve the problem of not knowing DSA prerequisites!** 
    
    This tool helps you understand:
    - πŸ“š What to learn before tackling any DSA topic
    - πŸ—ΊοΈ Step-by-step learning paths
    - πŸ”— How topics interconnect with each other
    - ⏱️ Time estimates for mastering each topic
    
    Select any topic below to get your personalized roadmap!
    """)
    
    with gr.Tabs():
        # Tab 1: Individual Topic Roadmap
        with gr.TabItem("πŸ“– Topic Roadmap"):
            gr.Markdown("### Get detailed roadmap for any DSA topic")
            
            topic_dropdown = gr.Dropdown(
                choices=all_topics,
                label="🎯 Select a DSA Topic",
                value="Arrays",
                info="Choose any topic to get a complete learning roadmap"
            )
            
            generate_btn = gr.Button("πŸš€ Generate Roadmap", variant="primary")
            roadmap_output = gr.Markdown(label="πŸ“‹ Your Learning Roadmap")
            
            generate_btn.click(
                fn=generate_roadmap,
                inputs=topic_dropdown,
                outputs=roadmap_output
            )
            
            # Auto-generate on selection change
            topic_dropdown.change(
                fn=generate_roadmap,
                inputs=topic_dropdown,
                outputs=roadmap_output
            )
        
        # Tab 2: Prerequisites Chain
        with gr.TabItem("πŸ”— Prerequisites Chain"):
            gr.Markdown("### See the complete learning path to master any topic")
            
            prereq_dropdown = gr.Dropdown(
                choices=all_topics,
                label="🎯 Select Target Topic",
                value="Dynamic Programming",
                info="See everything you need to learn before mastering this topic"
            )
            
            prereq_btn = gr.Button("πŸ“š Show Learning Path", variant="primary")
            prereq_output = gr.Markdown(label="πŸ“‹ Complete Learning Path")
            
            prereq_btn.click(
                fn=show_prerequisites_chain,
                inputs=prereq_dropdown,
                outputs=prereq_output
            )
            
            prereq_dropdown.change(
                fn=show_prerequisites_chain,
                inputs=prereq_dropdown,
                outputs=prereq_output
            )
        
        # Tab 3: Topic Connections
        with gr.TabItem("🌐 Topic Connections"):
            gr.Markdown("### Understand how topics connect to each other")
            
            connection_dropdown = gr.Dropdown(
                choices=all_topics,
                label="🎯 Select Topic",
                value="Trees",
                info="See how this topic connects to other DSA concepts"
            )
            
            connection_btn = gr.Button("πŸ”— Show Connections", variant="primary")
            connection_output = gr.Markdown(label="πŸ“‹ Topic Interconnections")
            
            connection_btn.click(
                fn=show_topic_connections,
                inputs=connection_dropdown,
                outputs=connection_output
            )
            
            connection_dropdown.change(
                fn=show_topic_connections,
                inputs=connection_dropdown,
                outputs=connection_output
            )
        
        # Tab 4: Difficulty-based Overview
        with gr.TabItem("πŸ“Š By Difficulty"):
            gr.Markdown("### Browse topics by difficulty level")
            
            difficulty_dropdown = gr.Dropdown(
                choices=difficulty_levels,
                label="πŸ“ˆ Select Difficulty Level",
                value="All",
                info="View topics grouped by difficulty"
            )
            
            difficulty_btn = gr.Button("πŸ“Š Show Topics", variant="primary")
            difficulty_output = gr.Markdown(label="πŸ“‹ Topics by Difficulty")
            
            difficulty_btn.click(
                fn=show_difficulty_roadmap,
                inputs=difficulty_dropdown,
                outputs=difficulty_output
            )
            
            difficulty_dropdown.change(
                fn=show_difficulty_roadmap,
                inputs=difficulty_dropdown,
                outputs=difficulty_output
            )
    
    # Footer
    gr.Markdown("""
    ---
    ### πŸ’‘ How to Use This Tool:
    1. **Topic Roadmap**: Get detailed learning plan for any specific topic
    2. **Prerequisites Chain**: See exactly what to learn before your target topic
    3. **Topic Connections**: Understand how topics relate to each other
    4. **By Difficulty**: Browse topics based on your current skill level
    
    ### 🎯 Pro Tips:
    - Start with **Beginner** topics if you're new to DSA
    - Follow the **Prerequisites Chain** for optimal learning order
    - Practice the **Important Problems** listed in each roadmap
    - Use **Topic Connections** to plan your learning journey
    
    **Happy Learning! πŸš€**
    """)

# Launch the app
if __name__ == "__main__":
    app.launch(share=True)