-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdsa-foundations.html
More file actions
2328 lines (1933 loc) · 136 KB
/
dsa-foundations.html
File metadata and controls
2328 lines (1933 loc) · 136 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
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DSA Foundations - Everything You Need to Know - Better Dev</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="topbar">
<button class="sidebar-toggle" aria-label="Open navigation" aria-expanded="false">
<span class="hamburger-icon"></span>
</button>
<a href="index.html" class="logo">Better Dev</a>
</header>
<div class="sidebar-backdrop" aria-hidden="true"></div>
<aside class="sidebar" aria-label="Site navigation">
<div class="sidebar-header">
<span class="sidebar-title">Navigation</span>
<button class="sidebar-close" aria-label="Close navigation">×</button>
</div>
<div class="sidebar-search">
<input type="text" class="sidebar-search-input" placeholder="Search topics..." aria-label="Search topics">
<div class="sidebar-search-results"></div>
</div>
<nav class="sidebar-nav">
<div class="sidebar-group">
<a href="index.html">Home</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Mathematics</div>
<a href="pre-algebra.html">Pre-Algebra</a>
<a href="algebra.html">Algebra</a>
<a href="sequences-series.html">Sequences & Series</a>
<a href="geometry.html">Geometry</a>
<a href="calculus.html">Calculus</a>
<a href="discrete-math.html">Discrete Math</a>
<a href="linear-algebra.html">Linear Algebra</a>
<a href="probability.html">Probability & Statistics</a>
<a href="binary-systems.html">Binary & Number Systems</a>
<a href="number-theory.html">Number Theory for CP</a>
<a href="computational-geometry.html">Computational Geometry</a>
<a href="game-theory.html">Game Theory</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Data Structures & Algorithms</div>
<a href="dsa-foundations.html">DSA Foundations</a>
<a href="arrays.html">Arrays & Strings</a>
<a href="stacks-queues.html">Stacks & Queues</a>
<a href="hashmaps.html">Hash Maps & Sets</a>
<a href="linked-lists.html">Linked Lists</a>
<a href="trees.html">Trees & BST</a>
<a href="graphs.html">Graphs</a>
<a href="sorting.html">Sorting & Searching</a>
<a href="patterns.html">LeetCode Patterns</a>
<a href="dp.html">Dynamic Programming</a>
<a href="advanced.html">Advanced Topics</a>
<a href="string-algorithms.html">String Algorithms</a>
<a href="advanced-graphs.html">Advanced Graphs</a>
<a href="advanced-dp.html">Advanced DP</a>
<a href="advanced-ds.html">Advanced Data Structures</a>
<a href="leetcode-650.html">The 650 Problems</a>
<a href="competitive-programming.html">CP Roadmap</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Languages & Systems</div>
<a href="cpp.html">C++</a>
<a href="golang.html">Go</a>
<a href="javascript.html">JavaScript Deep Dive</a>
<a href="typescript.html">TypeScript</a>
<a href="nodejs.html">Node.js Internals</a>
<a href="os.html">Operating Systems</a>
<a href="linux.html">Linux</a>
<a href="git.html">Git</a>
<a href="backend.html">Backend</a>
<a href="system-design.html">System Design</a>
<a href="networking.html">Networking</a>
<a href="cloud.html">Cloud & Infrastructure</a>
<a href="docker.html">Docker & Compose</a>
<a href="kubernetes.html">Kubernetes</a>
<a href="message-queues.html">Queues & Pub/Sub</a>
<a href="selfhosting.html">VPS & Self-Hosting</a>
<a href="databases.html">PostgreSQL & MySQL</a>
<a href="stripe.html">Stripe & Payments</a>
<a href="distributed-systems.html">Distributed Systems</a>
<a href="backend-engineering.html">Backend Engineering</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">JS/TS Ecosystem</div>
<a href="js-tooling.html">Tooling & Bundlers</a>
<a href="js-testing.html">Testing</a>
<a href="ts-projects.html">Building with TS</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">More</div>
<a href="seans-brain.html">Sean's Brain</a>
</div>
</nav>
</aside>
<div class="container">
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> / DSA Foundations</div>
<h1>DSA Foundations</h1>
<p>Everything you need to understand about data structures and algorithms, explained so simply that a 10-year-old could follow along. This is your starting point before diving into any specific topic.</p>
<div class="tip-box" style="margin-top: 1rem;">
<div class="label">Who This Is For</div>
<p>You're a CS student (or self-learner) who wants to master DSA for competitive programming, LeetCode, and technical interviews. Maybe you've tried reading about Big-O or linked lists before and it didn't click. This page fixes that. We start from absolute zero and build up every concept with real-world analogies, visual diagrams, and the actual math behind why things work.</p>
</div>
</div>
<div class="toc">
<h4>Table of Contents</h4>
<a href="#what-is-ds">1. What Even IS a Data Structure?</a>
<a href="#what-is-algo">2. What Even IS an Algorithm?</a>
<a href="#memory">3. How Computers Store Data (Memory)</a>
<a href="#time-complexity">4. Time Complexity -- The Most Important Concept</a>
<a href="#big-o-math">5. The Math Behind Big-O (Why It Works)</a>
<a href="#space-complexity">6. Space Complexity</a>
<a href="#ds-overview">7. Every Data Structure Explained From Zero</a>
<a href="#algorithms">8. Essential Algorithms Explained</a>
<a href="#recursion">9. Recursion -- Functions That Call Themselves</a>
<a href="#backtracking">10. Backtracking -- Try All Possibilities</a>
<a href="#prefix-sum">11. Prefix Sum -- Precompute Cumulative Sums</a>
<a href="#suffix-sum">12. Suffix Sum -- Precompute from Right</a>
<a href="#sweep-line">13. Sweep Line -- Event-Based Processing</a>
<a href="#memoization">14. Memoization -- Remember Your Work</a>
<a href="#tabulation">15. Tabulation -- Build Up Solutions</a>
<a href="#python-java-dsa">16. Python & Java DSA Quick Reference</a>
<a href="#problem-solving">17. How to Think About Problems</a>
<a href="#cp-tips">18. Tips to Become a World-Class Competitive Programmer</a>
<a href="#roadmap">19. Learning Roadmap</a>
<a href="#quiz">20. Practice Quiz</a>
</div>
<!-- ============================================================ -->
<!-- SECTION 1: WHAT IS A DATA STRUCTURE -->
<!-- ============================================================ -->
<section id="what-is-ds">
<h2>1. What Even IS a Data Structure?</h2>
<p>Imagine you just moved into a new house. You have a bunch of stuff -- books, clothes, food, tools. You <em>could</em> just throw everything into one giant pile in the middle of the room. But that would be a nightmare to find anything in, right?</p>
<p>So instead, you <strong>organize</strong> your stuff:</p>
<ul>
<li>Books go on a <strong>bookshelf</strong> (easy to browse, sorted by topic)</li>
<li>Clothes go in a <strong>wardrobe</strong> (easy to pick an outfit)</li>
<li>Food goes in the <strong>fridge</strong> (keeps things fresh, organized by shelf)</li>
<li>Tools go in a <strong>toolbox</strong> (everything has its slot)</li>
</ul>
<p>A <strong>data structure</strong> is exactly the same thing, but for computer data. It's a way of organizing information so you can find it, add to it, and work with it efficiently.</p>
<div class="formula-box">
Data Structure = A way of organizing data so that it can be used efficiently
</div>
<p>Just like you wouldn't use a bookshelf to store soup (that's what the fridge is for), different data structures are good for different jobs:</p>
<table>
<tr><th>Real World</th><th>Data Structure</th><th>Good For</th></tr>
<tr><td>Row of lockers</td><td>Array</td><td>Quick access by number</td></tr>
<tr><td>Treasure hunt clues</td><td>Linked List</td><td>Easy to insert/remove items</td></tr>
<tr><td>Stack of plates</td><td>Stack</td><td>Undo/redo, backtracking</td></tr>
<tr><td>Queue at a shop</td><td>Queue</td><td>First come, first served</td></tr>
<tr><td>Dictionary / phone book</td><td>Hash Map</td><td>Instant lookup by name</td></tr>
<tr><td>Family tree</td><td>Tree</td><td>Hierarchical data, fast search</td></tr>
<tr><td>Road map / social network</td><td>Graph</td><td>Connections between things</td></tr>
</table>
<div class="tip-box">
<div class="label">Key Insight</div>
<p>There is no single "best" data structure. The right choice depends on what you need to do. A great programmer knows when to use which one -- and that's exactly what this page teaches you.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 2: WHAT IS AN ALGORITHM -->
<!-- ============================================================ -->
<section id="what-is-algo">
<h2>2. What Even IS an Algorithm?</h2>
<p>An algorithm is just a <strong>set of steps to solve a problem</strong>. That's it. You already use algorithms every day without realizing it.</p>
<div class="example-box">
<div class="label">Real-World Algorithm: Making a Cup of Tea</div>
<p><strong>Step 1:</strong> Boil water<br>
<strong>Step 2:</strong> Put tea bag in cup<br>
<strong>Step 3:</strong> Pour boiling water into cup<br>
<strong>Step 4:</strong> Wait 3 minutes<br>
<strong>Step 5:</strong> Remove tea bag<br>
<strong>Step 6:</strong> Add milk/sugar if you want<br><br>
That's an algorithm. A clear set of instructions that always produces the right result.</p>
</div>
<p>In programming, an algorithm is the same thing -- a step-by-step procedure to solve a problem. For example:</p>
<ul>
<li><strong>Finding the biggest number in a list</strong> -- look at each number, keep track of the biggest one you've seen so far</li>
<li><strong>Sorting a deck of cards</strong> -- pick up cards one at a time, insert each into the right position</li>
<li><strong>Finding a word in a dictionary</strong> -- open to the middle, decide if your word comes before or after, repeat on the correct half</li>
</ul>
<p>That last one? That's <strong>binary search</strong> -- one of the most important algorithms in computer science. You've been doing it since you were a kid looking up words.</p>
<div class="warning-box">
<div class="label">Why Some Algorithms Are Better Than Others</div>
<p>Imagine you need to find the name "Sean" in a phone book with 1,000,000 names.</p>
<p><strong>Bad algorithm:</strong> Start at page 1 and read every single name until you find "Sean". Could take up to 1,000,000 checks.</p>
<p><strong>Good algorithm (binary search):</strong> Open to the middle. "Sean" comes after "M", so look in the second half. Open to the middle of that. Keep halving. Only takes about <strong>20 checks</strong> to search 1,000,000 names.</p>
<p>Same problem. Same answer. But one approach is <strong>50,000x faster</strong>. That's why algorithms matter.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 3: MEMORY -->
<!-- ============================================================ -->
<section id="memory">
<h2>3. How Computers Store Data (Memory)</h2>
<p>Before you can understand data structures, you need to understand how a computer actually stores data. Don't worry -- it's simpler than you think.</p>
<h3>RAM = A Giant Row of Numbered Boxes</h3>
<p>Your computer's memory (RAM) is like a massive row of numbered mailboxes. Each mailbox:</p>
<ul>
<li>Has a <strong>number</strong> (called an <strong>address</strong>) -- like mailbox #0, #1, #2, etc.</li>
<li>Can hold <strong>one piece of data</strong> -- a number, a letter, etc.</li>
<li>Can be accessed <strong>instantly</strong> if you know its number</li>
</ul>
<div class="memory-diagram">
Address: [0] [1] [2] [3] [4] [5] [6] [7]
Data: [ 42 ] [ 17 ] [ 85 ] [ 3 ] [ 99 ] [ 51 ] [ 8 ] [ 64 ]
</div>
<p>When you create a variable in code like <code>x = 42</code>, the computer:</p>
<ol>
<li>Finds an empty mailbox (say, address #0)</li>
<li>Puts the value 42 in it</li>
<li>Remembers that "x" means "go to address #0"</li>
</ol>
<h3>Why This Matters for Data Structures</h3>
<p>The key insight is: <strong>going to a specific mailbox by its number is instant</strong>. The computer doesn't have to walk past mailbox #0, #1, #2... to get to mailbox #500. It just jumps straight there. This is called <strong>random access</strong>, and it's why arrays are so fast at looking up items by index.</p>
<div class="tip-box">
<div class="label">The Memory Trade-Off</div>
<p>Every data structure is making a trade-off about how to use these mailboxes. Arrays put data in consecutive mailboxes (fast to access, hard to insert). Linked lists scatter data across random mailboxes but connect them with pointers (easy to insert, slow to access). Understanding this trade-off is the key to mastering data structures.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 4: TIME COMPLEXITY -->
<!-- ============================================================ -->
<section id="time-complexity">
<h2>4. Time Complexity -- The Most Important Concept in DSA</h2>
<p>This is it. This is the single most important concept in all of data structures and algorithms. If you understand this deeply, everything else falls into place.</p>
<h3>Why We Care About Speed</h3>
<p>Imagine you're building an app. When you have 100 users, any code works fine. But what happens when you have <strong>1,000,000 users</strong>? Or <strong>1,000,000,000</strong>?</p>
<p>Bad code that takes 1 second for 100 users might take <strong>3 hours</strong> for 1,000,000 users. Good code takes 1 second for both. That's the difference between a successful app and a broken one.</p>
<h3>We Count Steps, Not Seconds</h3>
<p>We don't measure speed in seconds because different computers run at different speeds. Instead, we count <strong>how many operations</strong> the algorithm needs as the input gets bigger.</p>
<div class="example-box">
<div class="label">Example: Finding the Maximum</div>
<p>Given a list of n numbers, find the biggest one.</p>
<p><strong>Algorithm:</strong> Look at each number, keep track of the biggest.<br>
For a list of 10 numbers: ~10 operations<br>
For a list of 1,000 numbers: ~1,000 operations<br>
For a list of 1,000,000 numbers: ~1,000,000 operations</p>
<p>The number of operations <strong>grows linearly</strong> with the input size. We call this <strong>O(n)</strong>.</p>
</div>
<h3>The Big-O Notation Cheat Sheet</h3>
<p>Big-O tells us: <em>"As the input gets really big, how does the number of operations grow?"</em></p>
<table>
<tr><th>Big-O</th><th>Name</th><th>Analogy</th><th>Speed</th></tr>
<tr><td><strong>O(1)</strong></td><td>Constant</td><td>Knowing exactly which locker to open</td><td>Instant, no matter the size</td></tr>
<tr><td><strong>O(log n)</strong></td><td>Logarithmic</td><td>Looking up a word in a dictionary</td><td>Incredibly fast</td></tr>
<tr><td><strong>O(n)</strong></td><td>Linear</td><td>Reading every page of a book</td><td>Fast, grows steadily</td></tr>
<tr><td><strong>O(n log n)</strong></td><td>Linearithmic</td><td>Smart sorting (merge sort)</td><td>Pretty fast</td></tr>
<tr><td><strong>O(n²)</strong></td><td>Quadratic</td><td>Comparing every person with every other person</td><td>Slow for large inputs</td></tr>
<tr><td><strong>O(2ⁿ)</strong></td><td>Exponential</td><td>Trying every combination on a lock</td><td>Impossibly slow</td></tr>
<tr><td><strong>O(n!)</strong></td><td>Factorial</td><td>Trying every possible arrangement</td><td>Heat death of the universe</td></tr>
</table>
<h3>Let's See Actual Numbers</h3>
<p>This is where it gets real. Look at how many operations each complexity needs for different input sizes:</p>
<table>
<tr><th>n</th><th>O(1)</th><th>O(log n)</th><th>O(n)</th><th>O(n log n)</th><th>O(n²)</th><th>O(2ⁿ)</th></tr>
<tr><td>10</td><td>1</td><td>3</td><td>10</td><td>33</td><td>100</td><td>1,024</td></tr>
<tr><td>100</td><td>1</td><td>7</td><td>100</td><td>664</td><td>10,000</td><td>1.27 x 10³⁰</td></tr>
<tr><td>1,000</td><td>1</td><td>10</td><td>1,000</td><td>9,966</td><td>1,000,000</td><td>IMPOSSIBLE</td></tr>
<tr><td>10,000</td><td>1</td><td>13</td><td>10,000</td><td>132,877</td><td>100,000,000</td><td>IMPOSSIBLE</td></tr>
<tr><td>100,000</td><td>1</td><td>17</td><td>100,000</td><td>1,660,964</td><td>10,000,000,000</td><td>IMPOSSIBLE</td></tr>
<tr><td>1,000,000</td><td>1</td><td>20</td><td>1,000,000</td><td>19,931,569</td><td>1,000,000,000,000</td><td>IMPOSSIBLE</td></tr>
</table>
<div class="warning-box">
<div class="label">Look at That Table Carefully</div>
<p>For n = 1,000,000:<br>
O(log n) needs just <strong>20 operations</strong>. That's binary search.<br>
O(n) needs <strong>1 million operations</strong>. Fine, takes maybe 0.01 seconds.<br>
O(n²) needs <strong>1 trillion operations</strong>. That's roughly <strong>16 minutes</strong>.<br>
O(2ⁿ) is literally impossible -- more operations than atoms in the universe.</p>
<p>This is why understanding time complexity is life or death for your code.</p>
</div>
<h3>Understanding Each Complexity</h3>
<h3>O(1) -- Constant Time</h3>
<p>No matter how big the input is, it always takes the same number of steps.</p>
<div class="example-box">
<div class="label">Example</div>
<p>Accessing an array element by index: <code>arr[5]</code><br>
Whether the array has 10 elements or 10 billion, jumping to index 5 is instant. The computer calculates: address = start_address + 5 x element_size. One calculation, done.</p>
</div>
<h3>O(log n) -- Logarithmic Time</h3>
<p>Each step <strong>cuts the problem in half</strong>. This is the magic of binary search.</p>
<div class="example-box">
<div class="label">Why log₂(n)?</div>
<p>Start with n items. After step 1: n/2 items. After step 2: n/4. After step 3: n/8.<br>
After k steps: n / 2ᵏ items remaining.<br><br>
We stop when 1 item is left: n / 2ᵏ = 1<br>
Solving: 2ᵏ = n, so <strong>k = log₂(n)</strong><br><br>
For n = 1,000,000,000 (1 billion): log₂(1,000,000,000) ≈ <strong>30 steps</strong><br>
You can search through a BILLION items in just 30 steps. That's the power of logarithms.</p>
</div>
<h3>O(n) -- Linear Time</h3>
<p>You look at every element once. If the input doubles, the time doubles.</p>
<div class="example-box">
<div class="label">Example</div>
<p>Finding the sum of all elements in an array. You must visit each element exactly once. No shortcut.</p>
</div>
<pre><code><span class="keyword">def</span> <span class="function">find_sum</span>(arr):
total = <span class="number">0</span>
<span class="keyword">for</span> num <span class="keyword">in</span> arr: <span class="comment"># visits each element once = O(n)</span>
total += num
<span class="keyword">return</span> total</code></pre>
<h3>O(n²) -- Quadratic Time</h3>
<p>For every element, you look at every OTHER element. It's a nested loop.</p>
<div class="example-box">
<div class="label">Why It's n²</div>
<p>Imagine 100 students in a class need to shake hands with every other student.<br>
Student 1 shakes hands with 99 others.<br>
Student 2 shakes hands with 99 others.<br>
...<br>
Total handshakes ≈ 100 x 100 = 10,000.<br><br>
With 1,000 students: 1,000 x 1,000 = 1,000,000 handshakes.<br>
With 1,000,000 students: 1,000,000 x 1,000,000 = 1,000,000,000,000. That's a TRILLION. Way too slow.</p>
</div>
<pre><code><span class="comment"># This is O(n²) -- nested loop</span>
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(<span class="builtin">len</span>(arr)):
<span class="keyword">for</span> j <span class="keyword">in</span> <span class="builtin">range</span>(<span class="builtin">len</span>(arr)): <span class="comment"># for EACH i, we loop through ALL j</span>
<span class="keyword">if</span> arr[i] + arr[j] == target:
<span class="keyword">return</span> [i, j]</code></pre>
<h3>O(2ⁿ) -- Exponential Time</h3>
<p>The number of operations <strong>doubles</strong> every time you add one more element. This blows up incredibly fast.</p>
<div class="example-box">
<div class="label">Why It's So Bad</div>
<p>Think of a combination lock with n switches (on/off).<br>
1 switch: 2 combinations<br>
2 switches: 4 combinations<br>
3 switches: 8 combinations<br>
10 switches: 1,024 combinations<br>
20 switches: 1,048,576 (about 1 million)<br>
30 switches: 1,073,741,824 (about 1 billion)<br>
50 switches: 1,125,899,906,842,624 (over 1 quadrillion)<br><br>
This is why brute-force solutions to problems like "find the best subset" are impractical for large inputs.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 5: BIG-O MATH -->
<!-- ============================================================ -->
<section id="big-o-math">
<h2>5. The Math Behind Big-O (Why It Works)</h2>
<p>Big-O notation describes the <strong>upper bound</strong> on growth rate. Formally: f(n) = O(g(n)) means there exist constants c and n₀ such that f(n) ≤ c·g(n) for all n ≥ n₀.</p>
<p>In plain English: <strong>we only care about the fastest-growing term, and we drop constants</strong>.</p>
<h3>Rule 1: Drop Constants</h3>
<div class="formula-box">
3n + 5 → O(n)
100n → O(n)
n/2 → O(n)
Why? When n = 1,000,000, the difference between n and 3n doesn't change the CATEGORY of growth. They both grow linearly.
</div>
<h3>Rule 2: Drop Lower-Order Terms</h3>
<div class="formula-box">
n² + n → O(n²)
n³ + 100n² + 5000n → O(n³)
2ⁿ + n⁵ → O(2ⁿ)
Why? For large n, the biggest term dominates everything else.
When n = 1,000: n² = 1,000,000 but n = 1,000. The n term is irrelevant.
</div>
<h3>Rule 3: Different Steps Get Added</h3>
<div class="formula-box">
Loop through array A (size a): O(a)
Then loop through array B (size b): O(b)
Total: O(a + b) -- NOT O(n²)
Only if you nest them: O(a × b)
</div>
<div class="formula-box">
<strong>Nested Loop Rule (Multiplication):</strong><br><br>
If loop A runs O(f(n)) times and loop B runs O(g(n)) times <strong>inside</strong> loop A:<br>
Total = O(f(n) × g(n))<br><br>
If loop A runs O(f(n)) and loop B runs O(g(n)) <strong>after</strong> loop A (not nested):<br>
Total = O(f(n) + g(n)) = O(max(f(n), g(n)))
</div>
<h3>The Math Behind log₂(n)</h3>
<p>Logarithms answer the question: <em>"How many times do I need to divide n by 2 to get to 1?"</em></p>
<div class="formula-box">
log₂(8) = 3 because 2³ = 8 (divide 8 by 2 three times: 8→4→2→1)
log₂(16) = 4 because 2⁴ = 16 (divide 16 by 2 four times: 16→8→4→2→1)
log₂(1024) = 10 because 2¹⁰ = 1024
log₂(1,000,000) ≈ 20
log₂(1,000,000,000) ≈ 30
</div>
<p>This is why binary search is so powerful. Even for 1 billion elements, you only need ~30 steps. Each step cuts the search space in half.</p>
<h3>Why O(n log n) Is the Sorting Sweet Spot</h3>
<p>The best comparison-based sorting algorithms (merge sort, quick sort) are O(n log n). Here's the intuition:</p>
<div class="example-box">
<div class="label">Merge Sort Intuition</div>
<p>Merge sort splits the array in half, sorts each half, then merges them.<br><br>
<strong>How many times can you split?</strong> log₂(n) times (keep halving until you have individual elements).<br>
<strong>How much work at each level?</strong> n operations (to merge all the pieces at that level).<br><br>
Total: n work × log₂(n) levels = <strong>O(n log n)</strong></p>
</div>
<div class="tip-box">
<div class="label">Competitive Programming Rule of Thumb</div>
<p>A modern computer does roughly <strong>100,000,000 (10⁸) simple operations per second</strong>. Use this to estimate if your solution is fast enough:</p>
<p>
n ≤ 10: O(n!) is fine<br>
n ≤ 20: O(2ⁿ) is fine<br>
n ≤ 500: O(n³) is fine<br>
n ≤ 10,000: O(n²) is fine<br>
n ≤ 1,000,000: O(n log n) is fine<br>
n ≤ 100,000,000: O(n) is fine<br>
Any n: O(log n) or O(1) is fine
</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 6: SPACE COMPLEXITY -->
<!-- ============================================================ -->
<section id="space-complexity">
<h2>6. Space Complexity</h2>
<p>Space complexity is the same idea as time complexity, but for <strong>memory</strong> instead of time.</p>
<p>If your algorithm creates a new array of size n, that's O(n) space. If it only uses a few variables regardless of input size, that's O(1) space.</p>
<div class="formula-box">
O(1) space: Only uses a fixed number of variables (like counters, pointers)
O(n) space: Creates a copy of the input or a hash map of size n
O(n²) space: Creates a 2D grid of size n×n
</div>
<h3>The Time-Space Trade-Off</h3>
<p>Often, you can make code faster by using more memory, or save memory by being slower. This is one of the most fundamental trade-offs in CS.</p>
<div class="example-box">
<div class="label">Example: Two Sum</div>
<p><strong>Brute force:</strong> O(n²) time, O(1) space -- check every pair<br>
<strong>Hash map:</strong> O(n) time, O(n) space -- store seen numbers in a hash map</p>
<p>The hash map solution uses more memory but is MUCH faster. This is almost always worth it.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 7: EVERY DATA STRUCTURE -->
<!-- ============================================================ -->
<section id="ds-overview">
<h2>7. Every Data Structure Explained From Zero</h2>
<p>Now that you understand time complexity, let's learn each data structure. For each one, we'll cover: what it is, how it works internally, time complexity for every operation (and WHY), and when to use it.</p>
<p>For deep dives with code implementations, click through to each topic's dedicated page.</p>
<!-- ARRAYS -->
<h3>Arrays -- The Foundation of Everything</h3>
<p><strong>Analogy:</strong> A row of numbered lockers in a school hallway.</p>
<div class="memory-diagram">
Index: [0] [1] [2] [3] [4]
Value: [ 10 ] [ 20 ] [ 30 ] [ 40 ] [ 50 ]
</div>
<p>Elements are stored in <strong>consecutive memory locations</strong>. Because they're consecutive, the computer can calculate exactly where any element is:</p>
<div class="formula-box">
address of element[i] = start_address + i × element_size
</div>
<p>This is why <strong>accessing by index is O(1)</strong> -- it's just one multiplication and one addition, no matter how big the array is.</p>
<table>
<tr><th>Operation</th><th>Time</th><th>Why</th></tr>
<tr><td>Access by index</td><td>O(1)</td><td>Direct address calculation</td></tr>
<tr><td>Search (unsorted)</td><td>O(n)</td><td>Must check each element</td></tr>
<tr><td>Insert at end</td><td>O(1)*</td><td>Just place at next spot (*amortized)</td></tr>
<tr><td>Insert at beginning/middle</td><td>O(n)</td><td>Must shift all elements after</td></tr>
<tr><td>Delete from middle</td><td>O(n)</td><td>Must shift elements to fill gap</td></tr>
</table>
<p><strong>Deep dive:</strong> <a href="arrays.html" style="color: #000000; font-weight: 500;">Arrays & Strings page</a></p>
<!-- LINKED LISTS -->
<h3>Linked Lists -- The Treasure Hunt</h3>
<p><strong>Analogy:</strong> A treasure hunt where each clue tells you where the next clue is.</p>
<div class="memory-diagram">
[10 | →] → [20 | →] → [30 | →] → [40 | →] → [50 | null]
Head Tail
</div>
<p>Each element (called a <strong>node</strong>) stores two things: its value AND a pointer to the next node. Nodes can be scattered anywhere in memory -- they don't need to be consecutive.</p>
<table>
<tr><th>Operation</th><th>Time</th><th>Why</th></tr>
<tr><td>Access by index</td><td>O(n)</td><td>Must follow links from the start</td></tr>
<tr><td>Search</td><td>O(n)</td><td>Must follow links one by one</td></tr>
<tr><td>Insert at head</td><td>O(1)</td><td>Just create node, point to old head</td></tr>
<tr><td>Insert at position (given pointer)</td><td>O(1)</td><td>Just redirect pointers</td></tr>
<tr><td>Delete (given pointer)</td><td>O(1)</td><td>Just redirect pointers</td></tr>
</table>
<p><strong>Deep dive:</strong> <a href="linked-lists.html" style="color: #000000; font-weight: 500;">Linked Lists page</a></p>
<!-- STACKS -->
<h3>Stacks -- Last In, First Out (LIFO)</h3>
<p><strong>Analogy:</strong> A stack of plates. You can only add or remove from the <strong>top</strong>.</p>
<div class="memory-diagram">
| 50 | ← top (most recently added)
| 40 |
| 30 |
| 20 |
| 10 |
+----+
</div>
<p>Three operations, ALL O(1):</p>
<ul>
<li><strong>Push:</strong> Add to the top</li>
<li><strong>Pop:</strong> Remove from the top</li>
<li><strong>Peek:</strong> Look at the top without removing</li>
</ul>
<p><strong>Why O(1)?</strong> You always know exactly where the top is. No searching needed.</p>
<p><strong>Use cases:</strong> Undo/redo, browser back button, matching parentheses, function call stack, DFS.</p>
<p><strong>Deep dive:</strong> <a href="stacks-queues.html" style="color: #000000; font-weight: 500;">Stacks & Queues page</a></p>
<!-- QUEUES -->
<h3>Queues -- First In, First Out (FIFO)</h3>
<p><strong>Analogy:</strong> A line at a shop. First person in line gets served first.</p>
<div class="memory-diagram">
Front → [10] [20] [30] [40] [50] ← Back
Remove from here Add here
</div>
<p>Two operations, both O(1):</p>
<ul>
<li><strong>Enqueue:</strong> Add to the back</li>
<li><strong>Dequeue:</strong> Remove from the front</li>
</ul>
<p><strong>Use cases:</strong> BFS, task scheduling, printer queue, message queues.</p>
<!-- HASH MAPS -->
<h3>Hash Maps -- The Most Important Interview Data Structure</h3>
<p><strong>Analogy:</strong> A magical librarian who instantly knows exactly which shelf any book is on.</p>
<p>A hash map stores <strong>key-value pairs</strong> and can find any value by its key in O(1) average time. How?</p>
<div class="example-box">
<div class="label">How Hashing Works</div>
<p><strong>Step 1:</strong> Take the key (e.g., "Sean")<br>
<strong>Step 2:</strong> Run it through a <strong>hash function</strong> that converts it to a number (e.g., 7)<br>
<strong>Step 3:</strong> Use that number as the index in an array: <code>storage[7] = "Sean's data"</code><br><br>
To find "Sean" later, just hash the key again → get 7 → go directly to storage[7]. Instant.</p>
</div>
<table>
<tr><th>Operation</th><th>Average</th><th>Worst</th><th>Why Worst Case?</th></tr>
<tr><td>Insert</td><td>O(1)</td><td>O(n)</td><td>Hash collisions (many keys map to same index)</td></tr>
<tr><td>Lookup</td><td>O(1)</td><td>O(n)</td><td>Same reason</td></tr>
<tr><td>Delete</td><td>O(1)</td><td>O(n)</td><td>Same reason</td></tr>
</table>
<p><strong>Deep dive:</strong> <a href="hashmaps.html" style="color: #000000; font-weight: 500;">Hash Maps & Sets page</a></p>
<!-- TREES -->
<h3>Trees -- Hierarchical Data</h3>
<p><strong>Analogy:</strong> A family tree, or an org chart, or your file system (folders inside folders).</p>
<div class="memory-diagram">
[50] ← root
/ \
[30] [70] ← children of 50
/ \ / \
[20] [40] [60] [80] ← leaves
</div>
<p>A <strong>Binary Search Tree (BST)</strong> has a special rule: left child < parent < right child. This means searching is like binary search:</p>
<div class="example-box">
<div class="label">Why BST Search Is O(log n)</div>
<p>Looking for 60 in the tree above:<br>
Start at 50. 60 > 50, so go right.<br>
At 70. 60 < 70, so go left.<br>
At 60. Found it!<br><br>
Each comparison eliminates HALF the tree (either the left or right subtree). Same math as binary search: <strong>O(log n)</strong> for a balanced tree.</p>
</div>
<p><strong>Deep dive:</strong> <a href="trees.html" style="color: #000000; font-weight: 500;">Trees & BST page</a></p>
<!-- HEAPS -->
<h3>Heaps -- Tournament Brackets</h3>
<p><strong>Analogy:</strong> A tournament bracket where the winner always rises to the top.</p>
<p>A <strong>min-heap</strong> always keeps the smallest element at the root. A <strong>max-heap</strong> keeps the largest. Both support:</p>
<table>
<tr><th>Operation</th><th>Time</th><th>Why</th></tr>
<tr><td>Get min/max</td><td>O(1)</td><td>It's always at the root</td></tr>
<tr><td>Insert</td><td>O(log n)</td><td>Add at bottom, bubble up (tree height = log n)</td></tr>
<tr><td>Extract min/max</td><td>O(log n)</td><td>Remove root, bubble down replacement</td></tr>
</table>
<p><strong>Use cases:</strong> Priority queues, finding Kth largest/smallest, Dijkstra's algorithm, merge K sorted lists.</p>
<p><strong>Deep dive:</strong> <a href="advanced.html" style="color: #000000; font-weight: 500;">Advanced Topics page</a></p>
<!-- GRAPHS -->
<h3>Graphs -- Connections Between Things</h3>
<p><strong>Analogy:</strong> A social network (people are nodes, friendships are edges) or a road map (cities are nodes, roads are edges).</p>
<div class="memory-diagram">
[A] --- [B]
| \ |
| \ |
[C] --- [D]
</div>
<p>Graphs are the most general data structure. Trees are actually a special type of graph (connected, no cycles). Linked lists are a special type of tree (each node has at most one child).</p>
<p><strong>Two ways to explore graphs:</strong></p>
<ul>
<li><strong>BFS (Breadth-First Search):</strong> Explore level by level, like ripples in water. Uses a queue. Good for finding shortest paths.</li>
<li><strong>DFS (Depth-First Search):</strong> Go as deep as possible, then backtrack. Uses a stack (or recursion). Good for exploring all paths.</li>
</ul>
<p><strong>Deep dive:</strong> <a href="graphs.html" style="color: #000000; font-weight: 500;">Graphs page</a></p>
<!-- TRIES -->
<h3>Tries -- Autocomplete on Your Phone</h3>
<p><strong>Analogy:</strong> The autocomplete feature that shows suggestions as you type each letter.</p>
<p>Each node represents a letter. Paths from root to leaf form words. Finding all words that start with "ca" means just following c → a and then listing everything below.</p>
<p><strong>Deep dive:</strong> <a href="advanced.html" style="color: #000000; font-weight: 500;">Advanced Topics page</a></p>
</section>
<!-- ============================================================ -->
<!-- SECTION 8: ESSENTIAL ALGORITHMS -->
<!-- ============================================================ -->
<section id="algorithms">
<h2>8. Essential Algorithms Explained</h2>
<h3>Binary Search -- Halving Your Way to the Answer</h3>
<p><strong>Requirement:</strong> The data must be <strong>sorted</strong>.</p>
<p><strong>How it works:</strong> Compare the target with the middle element. If target is smaller, search the left half. If larger, search the right half. Repeat.</p>
<pre><code><span class="keyword">def</span> <span class="function">binary_search</span>(arr, target):
left, right = <span class="number">0</span>, <span class="builtin">len</span>(arr) - <span class="number">1</span>
<span class="keyword">while</span> left <= right:
mid = (left + right) // <span class="number">2</span>
<span class="keyword">if</span> arr[mid] == target:
<span class="keyword">return</span> mid
<span class="keyword">elif</span> arr[mid] < target:
left = mid + <span class="number">1</span> <span class="comment"># target is in right half</span>
<span class="keyword">else</span>:
right = mid - <span class="number">1</span> <span class="comment"># target is in left half</span>
<span class="keyword">return</span> -<span class="number">1</span> <span class="comment"># not found</span></code></pre>
<h3>Recursion -- Functions That Call Themselves</h3>
<p><strong>Analogy:</strong> Russian nesting dolls. Open a doll, find a smaller doll inside. Keep opening until you reach the smallest doll (the <strong>base case</strong>).</p>
<p>Every recursive function needs:</p>
<ol>
<li><strong>Base case:</strong> When to stop (the smallest doll)</li>
<li><strong>Recursive case:</strong> Break the problem into a smaller version of itself</li>
</ol>
<pre><code><span class="comment"># Factorial: 5! = 5 × 4 × 3 × 2 × 1</span>
<span class="keyword">def</span> <span class="function">factorial</span>(n):
<span class="keyword">if</span> n <= <span class="number">1</span>: <span class="comment"># base case</span>
<span class="keyword">return</span> <span class="number">1</span>
<span class="keyword">return</span> n * factorial(n - <span class="number">1</span>) <span class="comment"># recursive case</span></code></pre>
<h3>Two Pointers</h3>
<p><strong>Analogy:</strong> Reading a book from both ends simultaneously, moving inward.</p>
<p>Use two pointers (usually start and end) and move them toward each other based on conditions. Works on sorted arrays or when you need to find pairs.</p>
<p><strong>Deep dive:</strong> <a href="patterns.html" style="color: #000000; font-weight: 500;">LeetCode Patterns page</a></p>
<h3>Sliding Window</h3>
<p><strong>Analogy:</strong> A magnifying glass sliding across a page, looking at a fixed-width section at a time.</p>
<p>Maintain a "window" of elements and slide it across the array, adding/removing one element at a time instead of recalculating everything.</p>
<p><strong>Deep dive:</strong> <a href="patterns.html" style="color: #000000; font-weight: 500;">LeetCode Patterns page</a></p>
<h3>Dynamic Programming</h3>
<p><strong>Analogy:</strong> Instead of recalculating your monthly expenses every time someone asks, you write the total on a sticky note and just read it next time.</p>
<p>DP = solving a problem by breaking it into smaller overlapping subproblems and <strong>remembering</strong> (memoizing) the results so you never solve the same subproblem twice.</p>
<p><strong>Deep dive:</strong> <a href="dp.html" style="color: #000000; font-weight: 500;">Dynamic Programming page</a></p>
<h3>Sorting</h3>
<p>The most common sorting algorithms and when to use them:</p>
<table>
<tr><th>Algorithm</th><th>Time</th><th>Space</th><th>Key Idea</th></tr>
<tr><td>Bubble Sort</td><td>O(n²)</td><td>O(1)</td><td>Repeatedly swap adjacent elements. Simple but slow.</td></tr>
<tr><td>Merge Sort</td><td>O(n log n)</td><td>O(n)</td><td>Divide in half, sort each half, merge. Stable and consistent.</td></tr>
<tr><td>Quick Sort</td><td>O(n log n)*</td><td>O(log n)</td><td>Pick pivot, partition around it. Fast in practice.</td></tr>
<tr><td>Counting Sort</td><td>O(n + k)</td><td>O(k)</td><td>Count occurrences. Only works for integers in a known range.</td></tr>
</table>
<p><strong>Deep dive:</strong> <a href="sorting.html" style="color: #000000; font-weight: 500;">Sorting & Searching page</a></p>
</section>
<!-- ============================================================ -->
<!-- SECTION 9: RECURSION -->
<!-- ============================================================ -->
<section id="recursion">
<h2>9. Recursion -- Functions That Call Themselves</h2>
<p><strong>Analogy:</strong> Russian nesting dolls. Open a doll, find a smaller doll inside. Keep opening until you reach the smallest doll (the <strong>base case</strong>).</p>
<p>Every recursive function needs:</p>
<ol>
<li><strong>Base case:</strong> When to stop (the smallest doll) -- returns a value without further recursion</li>
<li><strong>Recursive case:</strong> Break the problem into a smaller version of itself and call itself</li>
</ol>
<div class="formula-box">
Recursion Template:<br>
def function(inputs):<br>
if base_case:<br>
return result<br>
return function(smaller_problem)
</div>
<h3>Why Recursion Works</h3>
<p>Each recursive call solves a <strong>smaller version</strong> of the same problem. Eventually you reach the base case, then the results "unwind" back up.</p>
<h3>Recursion Patterns (LeetCode Style)</h3>
<h4>Pattern 1: Linear Recursion</h4>
<p>Process elements one at a time, moving forward or backward.</p>
<pre><code><span class="lang-label">Python - Reverse a String</span>
<span class="keyword">class</span> <span class="function">Solution</span>:
<span class="keyword">def</span> <span class="function">reverse_string</span>(self, s: <span class="builtin">list</span>[<span class="builtin">str</span>]) -> <span class="keyword">None</span>:
<span class="keyword">def</span> <span class="function">solve</span>(left: <span class="builtin">int</span>, right: <span class="builtin">int</span>):
<span class="keyword">if</span> left >= right:
<span class="keyword">return</span>
s[left], s[right] = s[right], s[left]
<span class="function">solve</span>(left + <span class="number">1</span>, right - <span class="number">1</span>)
<span class="function">solve</span>(<span class="number">0</span>, <span class="builtin">len</span>(s) - <span class="number">1</span>)</code></pre>
<h4>Pattern 2: Binary Recursion</h4>
<p>Split problem into two halves, process each recursively.</p>
<pre><code><span class="lang-label">Python - Fibonacci</span>
<span class="keyword">class</span> <span class="function">Solution</span>:
<span class="keyword">def</span> <span class="function">fib</span>(self, n: <span class="builtin">int</span>) -> <span class="builtin">int</span>:
<span class="keyword">if</span> n <= <span class="number">1</span>:
<span class="keyword">return</span> n
<span class="keyword">return</span> self.<span class="function">fib</span>(n - <span class="number">1</span>) + self.<span class="function">fib</span>(n - <span class="number">2</span>)</code></pre>
<h4>Pattern 3: Recursion with Memoization</h4>
<p>Add caching to avoid recalculating the same subproblems.</p>
<pre><code><span class="lang-label">Python - Fibonacci with Memo</span>
<span class="keyword">class</span> <span class="function">Solution</span>:
<span class="keyword">def</span> <span class="function">fib</span>(self, n: <span class="builtin">int</span>) -> <span class="builtin">int</span>:
cache = {}
<span class="keyword">def</span> <span class="function">solve</span>(x: <span class="builtin">int</span>) -> <span class="builtin">int</span>:
<span class="keyword">if</span> x <span class="keyword">in</span> cache:
<span class="keyword">return</span> cache[x]
<span class="keyword">if</span> x <= <span class="number">1</span>:
<span class="keyword">return</span> x
cache[x] = <span class="function">solve</span>(x - <span class="number">1</span>) + <span class="function">solve</span>(x - <span class="number">2</span>)
<span class="keyword">return</span> cache[x]
<span class="keyword">return</span> <span class="function">solve</span>(n)</code></pre>
<h4>Pattern 4: Tree Recursion</h4>
<p>Recursively process left and right subtrees.</p>
<pre><code><span class="lang-label">Python - Binary Tree Inorder Traversal</span>
<span class="keyword">class</span> <span class="function">Solution</span>:
<span class="keyword">def</span> <span class="function">inorder_traversal</span>(self, root) -> <span class="builtin">list</span>[<span class="builtin">int</span>]:
result = []
<span class="keyword">def</span> <span class="function">solve</span>(node):
<span class="keyword">if</span> <span class="keyword">not</span> node:
<span class="keyword">return</span>
<span class="function">solve</span>(node.left)
result.append(node.val)
<span class="function">solve</span>(node.right)
<span class="function">solve</span>(root)
<span class="keyword">return</span> result</code></pre>
<div class="tip-box">
<div class="label">Key Insight</div>
<p>When writing recursive functions, ask: "What is the smallest version of this problem I can solve directly?" That's your base case. Then ask: "How do I reduce the current problem to a smaller one?" That's your recursive case.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 10: BACKTRACKING -->
<!-- ============================================================ -->
<section id="backtracking">
<h2>10. Backtracking -- Try All Possibilities</h2>
<p><strong>Analogy:</strong> Exploring a maze. You try a path, if it hits a dead end, you backtrack to the last junction and try a different path.</p>
<p>Backtracking = Recursion + Choice + Undo Choice. You explore all possibilities by making a choice, recursing, then undoing that choice to try another.</p>
<div class="formula-box">
Backtracking Template:<br>
def backtrack(path, choices):<br>
if valid solution:<br>
record solution<br>
for each choice in choices:<br>
make choice<br>
backtrack(path, remaining_choices)<br>
undo choice (backtrack)
</div>
<h3>Backtracking Patterns (LeetCode Style)</h3>
<h4>Pattern 1: Subsets (Include/Exclude)</h4>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">Solution</span>:
<span class="keyword">def</span> <span class="function">subsets</span>(self, nums: <span class="builtin">list</span>[<span class="builtin">int</span>]) -> <span class="builtin">list</span>[<span class="builtin">list</span>[<span class="builtin">int</span>]]:
result = []
<span class="keyword">def</span> <span class="function">backtrack</span>(start: <span class="builtin">int</span>, path: <span class="builtin">list</span>[<span class="builtin">int</span>]):
result.append(path[:])
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(start, <span class="builtin">len</span>(nums)):
path.append(nums[i])
<span class="function">backtrack</span>(i + <span class="number">1</span>, path)
path.pop()
<span class="function">backtrack</span>(<span class="number">0</span>, [])
<span class="keyword">return</span> result</code></pre>
<h4>Pattern 2: Permutations</h4>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">Solution</span>:
<span class="keyword">def</span> <span class="function">permute</span>(self, nums: <span class="builtin">list</span>[<span class="builtin">int</span>]) -> <span class="builtin">list</span>[<span class="builtin">list</span>[<span class="builtin">int</span>]]:
result = []
used = [<span class="keyword">False</span>] * <span class="builtin">len</span>(nums)
<span class="keyword">def</span> <span class="function">backtrack</span>(path: <span class="builtin">list</span>[<span class="builtin">int</span>]):
<span class="keyword">if</span> <span class="builtin">len</span>(path) == <span class="builtin">len</span>(nums):
result.append(path[:])
<span class="keyword">return</span>
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(<span class="builtin">len</span>(nums)):
<span class="keyword">if</span> <span class="keyword">not</span> used[i]:
used[i] = <span class="keyword">True</span>
path.append(nums[i])
<span class="function">backtrack</span>(path)
path.pop()
used[i] = <span class="keyword">False</span>
<span class="function">backtrack</span>([])
<span class="keyword">return</span> result</code></pre>
<h4>Pattern 3: Combination Sum</h4>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">Solution</span>:
<span class="keyword">def</span> <span class="function">combination_sum</span>(self, candidates: <span class="builtin">list</span>[<span class="builtin">int</span>], target: <span class="builtin">int</span>) -> <span class="builtin">list</span>[<span class="builtin">list</span>[<span class="builtin">int</span>]]:
result = []
<span class="keyword">def</span> <span class="function">backtrack</span>(start: <span class="builtin">int</span>, path: <span class="builtin">list</span>[<span class="builtin">int</span>], remaining: <span class="builtin">int</span>):
<span class="keyword">if</span> remaining == <span class="number">0</span>:
result.append(path[:])
<span class="keyword">return</span>
<span class="keyword">if</span> remaining < <span class="number">0</span>:
<span class="keyword">return</span>
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(start, <span class="builtin">len</span>(candidates)):
path.append(candidates[i])
<span class="function">backtrack</span>(i, path, remaining - candidates[i])
path.pop()
<span class="function">backtrack</span>(<span class="number">0</span>, [], target)
<span class="keyword">return</span> result</code></pre>
<h4>Pattern 4: N-Queens</h4>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">Solution</span>:
<span class="keyword">def</span> <span class="function">solve_n_queens</span>(self, n: <span class="builtin">int</span>) -> <span class="builtin">list</span>[<span class="builtin">list</span>[<span class="builtin">str</span>]]:
result = []
cols = <span class="builtin">set</span>()
diag1 = <span class="builtin">set</span>()
diag2 = <span class="builtin">set</span>()
<span class="keyword">def</span> <span class="function">backtrack</span>(row: <span class="builtin">int</span>, path: <span class="builtin">list</span>[<span class="builtin">str</span>]):
<span class="keyword">if</span> row == n:
result.append(path[:])
<span class="keyword">return</span>
<span class="keyword">for</span> col <span class="keyword">in</span> <span class="builtin">range</span>(n):
<span class="keyword">if</span> col <span class="keyword">in</span> cols <span class="keyword">or</span> (row - col) <span class="keyword">in</span> diag1 <span class="keyword">or</span> (row + col) <span class="keyword">in</span> diag2:
<span class="keyword">continue</span>
cols.add(col)
diag1.add(row - col)
diag2.add(row + col)
path.append(<span class="string">"."</span> * col + <span class="string">"Q"</span> + <span class="string">"."</span> * (n - col - <span class="number">1</span>))
<span class="function">backtrack</span>(row + <span class="number">1</span>, path)
path.pop()
cols.remove(col)
diag1.remove(row - col)
diag2.remove(row + col)
<span class="function">backtrack</span>(<span class="number">0</span>, [])
<span class="keyword">return</span> result</code></pre>
<div class="formula-box">
When to use Backtracking:<br>
- Generate all combinations/permutations<br>
- Solve puzzles (N-Queens, Sudoku)<br>
- Find all paths in a grid<br>
- Subset selection problems<br>
- Constraint satisfaction problems
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 11: PREFIX SUM -->
<!-- ============================================================ -->
<section id="prefix-sum">
<h2>11. Prefix Sum -- Precompute Cumulative Sums</h2>
<p><strong>Analogy:</strong> Instead of counting books on each shelf every time someone asks, you precompute cumulative totals and just subtract to get any range.</p>
<p>Precompute a running sum array so you can answer any "sum from index i to j" query in O(1).</p>
<div class="formula-box">
prefix[i] = arr[0] + arr[1] + ... + arr[i]<br>
sum(arr[l..r]) = prefix[r] - prefix[l-1] (if l > 0)
</div>
<h3>Prefix Sum Patterns (LeetCode Style)</h3>
<h4>Pattern 1: Range Sum Query</h4>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">Solution</span>:
<span class="keyword">def</span> <span class="function">range_sum</span>(self, nums: <span class="builtin">list</span>[<span class="builtin">int</span>], queries: <span class="builtin">list</span>[<span class="builtin">list</span>[<span class="builtin">int</span>]]) -> <span class="builtin">list</span>[<span class="builtin">int</span>]:
prefix = [<span class="number">0</span>] * (<span class="builtin">len</span>(nums) + <span class="number">1</span>)
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(<span class="builtin">len</span>(nums)):
prefix[i + <span class="number">1</span>] = prefix[i] + nums[i]
result = []
<span class="keyword">for</span> l, r <span class="keyword">in</span> queries:
result.append(prefix[r + <span class="number">1</span>] - prefix[l])
<span class="keyword">return</span> result</code></pre>
<h4>Pattern 2: Subarray Sum Equals K</h4>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">Solution</span>: