-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpatterns.html
More file actions
2770 lines (2484 loc) · 159 KB
/
patterns.html
File metadata and controls
2770 lines (2484 loc) · 159 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>Algorithm Patterns — DSA - Better Dev</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<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">
<!-- Page Header -->
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> / Patterns</div>
<h1>Algorithm Patterns</h1>
<p>The KEY to solving LeetCode. Learn these patterns and you can solve hundreds of problems.</p>
</div>
<!-- Table of Contents -->
<div class="toc">
<h4>On This Page</h4>
<a href="#why-patterns">1. Why Patterns Matter</a>
<a href="#two-pointers">2. Two Pointers</a>
<a href="#sliding-window">3. Sliding Window</a>
<a href="#binary-search">4. Binary Search Pattern</a>
<a href="#bfs">5. BFS Pattern</a>
<a href="#dfs">6. DFS & Backtracking</a>
<a href="#prefix-sum">7. Prefix Sum</a>
<a href="#monotonic-stack">8. Monotonic Stack</a>
<a href="#greedy">9. Greedy</a>
<a href="#intervals">10. Interval Problems</a>
<a href="#sweep-line">11. Sweep Line</a>
<a href="#hashmap">12. HashMap Patterns</a>
<a href="#kadanes">13. Kadane's Algorithm</a>
<a href="#top-k">14. Top K Elements</a>
<a href="#topo-sort">15. Topological Sort</a>
<a href="#dijkstra">16. Dijkstra's Algorithm</a>
<a href="#bipartite">17. Bipartite Graph</a>
<a href="#sieve">18. Sieve of Eratosthenes</a>
<a href="#dp-patterns">19. DP Patterns</a>
<a href="#floyd-bellman">20. Floyd Warshall & Bellman Ford</a>
<a href="#bitmask-dp">21. Bitmask DP</a>
<a href="#digit-dp">22. Digit DP</a>
<a href="#fenwick">23. Fenwick Tree (BIT)</a>
<a href="#segment-tree">24. Segment Tree</a>
<a href="#kmp-rolling-hash">25. KMP & Rolling Hash</a>
<a href="#nlogn-lis">26. NlogN LIS</a>
<a href="#eulerian">27. Eulerian Paths</a>
<a href="#fft">28. FFT</a>
<a href="#cheat-sheet">29. Pattern Recognition Cheat Sheet</a>
<a href="#quiz">30. Practice Quiz</a>
</div>
<!-- ============================================================ -->
<!-- 1. WHY PATTERNS MATTER -->
<!-- ============================================================ -->
<section id="why-patterns">
<h2>1. Why Patterns Matter</h2>
<p>
LeetCode is not about memorizing 500 solutions. If you memorize solutions, you will blank the moment a problem changes even one detail. The real skill is <strong>recognizing patterns</strong> and knowing which technique applies to which type of problem.
</p>
<ul>
<li>There are roughly <strong>15 core patterns</strong> that cover the vast majority of interview problems.</li>
<li>Once you learn a pattern, every problem that uses it becomes a variation -- not a brand new puzzle.</li>
<li>Patterns give you a <strong>starting framework</strong> so you are never staring at a blank screen.</li>
<li>Interviewers do not expect novel algorithms -- they expect you to recognize and apply known techniques.</li>
</ul>
<div class="tip-box">
<div class="label">The Goal</div>
<p>Read a problem, identify which pattern it belongs to, then apply that pattern's template and adapt it. That is the entire strategy. This page teaches you the most important patterns with full solutions so you can practice exactly that.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- 2. TWO POINTERS -->
<!-- ============================================================ -->
<section id="two-pointers">
<h2>2. Two Pointers</h2>
<p>
Use two pointers to scan a data structure (usually an array) from different positions. This often reduces an O(n^2) brute force to O(n).
</p>
<div class="formula-box">
When to use: sorted arrays, find pairs with a condition, in-place operations, palindrome checks
</div>
<p><strong>Two main types:</strong></p>
<ul>
<li><strong>Converging pointers</strong> -- one at the start, one at the end, moving toward each other.</li>
<li><strong>Same direction pointers</strong> -- both start at the beginning; one moves fast, one moves slow.</li>
</ul>
<!-- Converging Two Pointers -->
<h3>Converging Two Pointers</h3>
<p><strong>Two Sum II (Sorted Array)</strong> -- Given a sorted array and a target, find two numbers that add up to the target.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">two_sum</span>(numbers, target):
left, right = <span class="number">0</span>, len(numbers) - <span class="number">1</span>
<span class="keyword">while</span> left < right:
curr_sum = numbers[left] + numbers[right]
<span class="keyword">if</span> curr_sum == target:
<span class="keyword">return</span> [left + <span class="number">1</span>, right + <span class="number">1</span>] <span class="comment"># 1-indexed</span>
<span class="keyword">elif</span> curr_sum < target:
left += <span class="number">1</span> <span class="comment"># need bigger sum</span>
<span class="keyword">else</span>:
right -= <span class="number">1</span> <span class="comment"># need smaller sum</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">twoSum</span>(numbers, target) {
<span class="keyword">let</span> left = <span class="number">0</span>, right = numbers.length - <span class="number">1</span>;
<span class="keyword">while</span> (left < right) {
<span class="keyword">const</span> sum = numbers[left] + numbers[right];
<span class="keyword">if</span> (sum === target) <span class="keyword">return</span> [left + <span class="number">1</span>, right + <span class="number">1</span>];
<span class="keyword">else if</span> (sum < target) left++;
<span class="keyword">else</span> right--;
}
}</code></pre>
<div class="example-box">
<div class="label">Why it works</div>
<p>Because the array is sorted, if the sum is too small we move <code>left</code> right to increase it. If the sum is too large we move <code>right</code> left to decrease it. We never miss a valid pair because we only eliminate values that cannot be part of the answer.</p>
</div>
<p><strong>Container With Most Water</strong> -- Given height array, find two lines that form the container holding the most water.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">max_area</span>(height):
left, right = <span class="number">0</span>, len(height) - <span class="number">1</span>
best = <span class="number">0</span>
<span class="keyword">while</span> left < right:
width = right - left
h = min(height[left], height[right])
best = max(best, width * h)
<span class="comment"># Move the shorter side -- it's the bottleneck</span>
<span class="keyword">if</span> height[left] < height[right]:
left += <span class="number">1</span>
<span class="keyword">else</span>:
right -= <span class="number">1</span>
<span class="keyword">return</span> best</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">maxArea</span>(height) {
<span class="keyword">let</span> left = <span class="number">0</span>, right = height.length - <span class="number">1</span>, best = <span class="number">0</span>;
<span class="keyword">while</span> (left < right) {
<span class="keyword">const</span> w = right - left;
<span class="keyword">const</span> h = Math.min(height[left], height[right]);
best = Math.max(best, w * h);
<span class="keyword">if</span> (height[left] < height[right]) left++;
<span class="keyword">else</span> right--;
}
<span class="keyword">return</span> best;
}</code></pre>
<p><strong>3Sum</strong> -- Find all unique triplets that sum to zero. Sort the array, fix one number, then use converging two pointers on the remainder. Skip duplicates to avoid repeats. Time O(n^2), Space O(1) extra.</p>
<!-- Same Direction -->
<h3>Same Direction (Fast / Slow)</h3>
<p><strong>Remove Duplicates from Sorted Array</strong> -- Keep a slow pointer at the position to write, fast pointer scans ahead. When fast finds a new value, write it at slow and advance slow.</p>
<p><strong>Move Zeroes</strong> -- Same idea: slow pointer tracks the next position for a nonzero value. Fast pointer scans the array. Swap nonzero values to the front.</p>
<h3>Two Pointers Templates</h3>
<pre><code><span class="lang-label">Python</span>
<span class="comment"># Template: Converging Two Pointers</span>
<span class="keyword">def</span> <span class="function">converging</span>(arr, target):
left, right = <span class="number">0</span>, len(arr) - <span class="number">1</span>
<span class="keyword">while</span> left < right:
<span class="comment"># compute current value from arr[left], arr[right]</span>
<span class="keyword">if</span> condition_met:
<span class="keyword">return</span> result
<span class="keyword">elif</span> need_larger:
left += <span class="number">1</span>
<span class="keyword">else</span>:
right -= <span class="number">1</span>
<span class="comment"># Template: Same Direction (partition / remove)</span>
<span class="keyword">def</span> <span class="function">same_direction</span>(arr):
slow = <span class="number">0</span>
<span class="keyword">for</span> fast <span class="keyword">in</span> range(len(arr)):
<span class="keyword">if</span> arr[fast] meets_condition:
arr[slow] = arr[fast]
slow += <span class="number">1</span>
<span class="keyword">return</span> slow <span class="comment"># new length</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Template: Converging Two Pointers</span>
<span class="keyword">function</span> <span class="function">converging</span>(arr, target) {
<span class="keyword">let</span> left = <span class="number">0</span>, right = arr.length - <span class="number">1</span>;
<span class="keyword">while</span> (left < right) {
<span class="comment">// compute current value from arr[left], arr[right]</span>
<span class="keyword">if</span> (conditionMet) <span class="keyword">return</span> result;
<span class="keyword">else if</span> (needLarger) left++;
<span class="keyword">else</span> right--;
}
}
<span class="comment">// Template: Same Direction (partition / remove)</span>
<span class="keyword">function</span> <span class="function">sameDirection</span>(arr) {
<span class="keyword">let</span> slow = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">let</span> fast = <span class="number">0</span>; fast < arr.length; fast++) {
<span class="keyword">if</span> (arr[fast] meets condition) {
arr[slow] = arr[fast];
slow++;
}
}
<span class="keyword">return</span> slow;
}</code></pre>
</section>
<!-- ============================================================ -->
<!-- 3. SLIDING WINDOW -->
<!-- ============================================================ -->
<section id="sliding-window">
<h2>3. Sliding Window</h2>
<p>
Maintain a "window" over a contiguous subarray or substring and slide it across the input. This avoids recomputing from scratch each time -- you add the new element and remove the old one.
</p>
<div class="formula-box">
When to use: contiguous subarray/substring problems, "maximum/minimum of size k", "longest/shortest with condition"
</div>
<p><strong>Two types:</strong></p>
<ul>
<li><strong>Fixed size window</strong> -- window size k is given. Slide it one position at a time.</li>
<li><strong>Variable size window</strong> -- expand until condition breaks, then shrink from the left.</li>
</ul>
<!-- Fixed Size -->
<h3>Fixed Size Window</h3>
<p><strong>Maximum Sum Subarray of Size K</strong></p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">max_sum_subarray</span>(arr, k):
window_sum = sum(arr[:k])
best = window_sum
<span class="keyword">for</span> i <span class="keyword">in</span> range(k, len(arr)):
window_sum += arr[i] - arr[i - k] <span class="comment"># slide: add right, remove left</span>
best = max(best, window_sum)
<span class="keyword">return</span> best</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">maxSumSubarray</span>(arr, k) {
<span class="keyword">let</span> windowSum = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < k; i++) windowSum += arr[i];
<span class="keyword">let</span> best = windowSum;
<span class="keyword">for</span> (<span class="keyword">let</span> i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
best = Math.max(best, windowSum);
}
<span class="keyword">return</span> best;
}</code></pre>
<!-- Variable Size -->
<h3>Variable Size Window</h3>
<p><strong>Minimum Size Subarray Sum</strong> -- Find the smallest subarray whose sum is at least the target. Expand right to grow the window, shrink left when the sum is big enough.</p>
<p><strong>Longest Substring Without Repeating Characters</strong> -- Classic variable window problem. Expand right, if duplicate found, shrink left until valid again.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">length_of_longest_substring</span>(s):
seen = {} <span class="comment"># char -> most recent index</span>
left = <span class="number">0</span>
best = <span class="number">0</span>
<span class="keyword">for</span> right <span class="keyword">in</span> range(len(s)):
<span class="keyword">if</span> s[right] <span class="keyword">in</span> seen <span class="keyword">and</span> seen[s[right]] >= left:
left = seen[s[right]] + <span class="number">1</span> <span class="comment"># shrink past the duplicate</span>
seen[s[right]] = right
best = max(best, right - left + <span class="number">1</span>)
<span class="keyword">return</span> best</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">lengthOfLongestSubstring</span>(s) {
<span class="keyword">const</span> seen = <span class="keyword">new</span> Map();
<span class="keyword">let</span> left = <span class="number">0</span>, best = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">let</span> right = <span class="number">0</span>; right < s.length; right++) {
<span class="keyword">if</span> (seen.has(s[right]) && seen.get(s[right]) >= left) {
left = seen.get(s[right]) + <span class="number">1</span>;
}
seen.set(s[right], right);
best = Math.max(best, right - left + <span class="number">1</span>);
}
<span class="keyword">return</span> best;
}</code></pre>
<div class="example-box">
<div class="label">Example</div>
<p><code>s = "abcabcbb"</code> -- The longest substring without repeating characters is <code>"abc"</code>, length <strong>3</strong>. As we scan, when we hit the second 'a', we jump left past the first 'a'.</p>
</div>
<h3>Sliding Window Templates</h3>
<pre><code><span class="lang-label">Python</span>
<span class="comment"># Template: Fixed Size Window</span>
<span class="keyword">def</span> <span class="function">fixed_window</span>(arr, k):
<span class="comment"># Initialize window with first k elements</span>
window = compute(arr[<span class="number">0</span>:k])
best = window
<span class="keyword">for</span> i <span class="keyword">in</span> range(k, len(arr)):
window = window + arr[i] - arr[i - k] <span class="comment"># add new, remove old</span>
best = update(best, window)
<span class="keyword">return</span> best
<span class="comment"># Template: Variable Size Window</span>
<span class="keyword">def</span> <span class="function">variable_window</span>(arr):
left = <span class="number">0</span>
best = <span class="number">0</span>
state = {} <span class="comment"># track window contents</span>
<span class="keyword">for</span> right <span class="keyword">in</span> range(len(arr)):
<span class="comment"># Expand: add arr[right] to state</span>
<span class="keyword">while</span> window_is_invalid(state):
<span class="comment"># Shrink: remove arr[left] from state</span>
left += <span class="number">1</span>
best = max(best, right - left + <span class="number">1</span>)
<span class="keyword">return</span> best</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Template: Fixed Size Window</span>
<span class="keyword">function</span> <span class="function">fixedWindow</span>(arr, k) {
<span class="keyword">let</span> window = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < k; i++) window += arr[i];
<span class="keyword">let</span> best = window;
<span class="keyword">for</span> (<span class="keyword">let</span> i = k; i < arr.length; i++) {
window += arr[i] - arr[i - k];
best = Math.max(best, window);
}
<span class="keyword">return</span> best;
}
<span class="comment">// Template: Variable Size Window</span>
<span class="keyword">function</span> <span class="function">variableWindow</span>(arr) {
<span class="keyword">let</span> left = <span class="number">0</span>, best = <span class="number">0</span>;
<span class="keyword">const</span> state = <span class="keyword">new</span> Map();
<span class="keyword">for</span> (<span class="keyword">let</span> right = <span class="number">0</span>; right < arr.length; right++) {
<span class="comment">// Expand: add arr[right] to state</span>
<span class="keyword">while</span> (windowIsInvalid(state)) {
<span class="comment">// Shrink: remove arr[left] from state</span>
left++;
}
best = Math.max(best, right - left + <span class="number">1</span>);
}
<span class="keyword">return</span> best;
}</code></pre>
</section>
<!-- ============================================================ -->
<!-- 4. BINARY SEARCH PATTERN -->
<!-- ============================================================ -->
<section id="binary-search">
<h2>4. Binary Search Pattern</h2>
<p>
Binary search is not just for finding an element in a sorted array. The deeper insight is: <strong>any time you can halve a search space</strong>, you can binary search. This includes searching on the answer itself.
</p>
<div class="formula-box">
When to use: sorted data, "minimum/maximum that satisfies condition", search space that can be halved
</div>
<h3>Standard Binary Search Template</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">binary_search</span>(arr, target):
left, right = <span class="number">0</span>, len(arr) - <span class="number">1</span>
<span class="keyword">while</span> left <= right:
mid = left + (right - left) // <span class="number">2</span> <span class="comment"># avoids overflow</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="keyword">else</span>:
right = mid - <span class="number">1</span>
<span class="keyword">return</span> -<span class="number">1</span> <span class="comment"># not found</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">binarySearch</span>(arr, target) {
<span class="keyword">let</span> left = <span class="number">0</span>, right = arr.length - <span class="number">1</span>;
<span class="keyword">while</span> (left <= right) {
<span class="keyword">const</span> mid = left + Math.floor((right - left) / <span class="number">2</span>);
<span class="keyword">if</span> (arr[mid] === target) <span class="keyword">return</span> mid;
<span class="keyword">else if</span> (arr[mid] < target) left = mid + <span class="number">1</span>;
<span class="keyword">else</span> right = mid - <span class="number">1</span>;
}
<span class="keyword">return</span> -<span class="number">1</span>;
}</code></pre>
<h3>Binary Search on the Answer</h3>
<p>
Sometimes you are not searching an array -- you are searching a <strong>range of possible answers</strong>. If you can write a function <code>canAchieve(x)</code> that returns true/false, and the answers are monotonic (once true, always true), you can binary search on the answer.
</p>
<p><strong>Koko Eating Bananas</strong> -- Koko has piles of bananas and h hours. Find the minimum eating speed k so she finishes all piles in h hours.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> math
<span class="keyword">def</span> <span class="function">min_eating_speed</span>(piles, h):
<span class="keyword">def</span> <span class="function">can_finish</span>(speed):
hours = sum(math.ceil(p / speed) <span class="keyword">for</span> p <span class="keyword">in</span> piles)
<span class="keyword">return</span> hours <= h
left, right = <span class="number">1</span>, max(piles)
<span class="keyword">while</span> left < right:
mid = (left + right) // <span class="number">2</span>
<span class="keyword">if</span> can_finish(mid):
right = mid <span class="comment"># try slower</span>
<span class="keyword">else</span>:
left = mid + <span class="number">1</span> <span class="comment"># too slow, go faster</span>
<span class="keyword">return</span> left</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">minEatingSpeed</span>(piles, h) {
<span class="keyword">function</span> <span class="function">canFinish</span>(speed) {
<span class="keyword">let</span> hours = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">const</span> p <span class="keyword">of</span> piles) hours += Math.ceil(p / speed);
<span class="keyword">return</span> hours <= h;
}
<span class="keyword">let</span> left = <span class="number">1</span>, right = Math.max(...piles);
<span class="keyword">while</span> (left < right) {
<span class="keyword">const</span> mid = Math.floor((left + right) / <span class="number">2</span>);
<span class="keyword">if</span> (canFinish(mid)) right = mid;
<span class="keyword">else</span> left = mid + <span class="number">1</span>;
}
<span class="keyword">return</span> left;
}</code></pre>
<div class="example-box">
<div class="label">Example</div>
<p><code>piles = [3, 6, 7, 11], h = 8</code> -- Answer is <strong>4</strong>. At speed 4: ceil(3/4)+ceil(6/4)+ceil(7/4)+ceil(11/4) = 1+2+2+3 = 8 hours. Speed 3 would take 10 hours (too slow).</p>
</div>
<p><strong>Capacity to Ship Packages Within D Days</strong> -- Same idea. Binary search on the ship capacity. The <code>canShip(capacity)</code> function simulates loading packages greedily and checks if it fits in D days.</p>
<h3>Binary Search on Answer Template</h3>
<pre><code><span class="lang-label">Python</span>
<span class="comment"># Template: Binary Search on the Answer</span>
<span class="keyword">def</span> <span class="function">search_answer</span>(data):
<span class="keyword">def</span> <span class="function">is_feasible</span>(x):
<span class="comment"># return True if x is a valid answer</span>
<span class="keyword">pass</span>
left, right = min_possible, max_possible
<span class="keyword">while</span> left < right:
mid = (left + right) // <span class="number">2</span>
<span class="keyword">if</span> is_feasible(mid):
right = mid <span class="comment"># try smaller (for minimum)</span>
<span class="keyword">else</span>:
left = mid + <span class="number">1</span>
<span class="keyword">return</span> left</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Template: Binary Search on the Answer</span>
<span class="keyword">function</span> <span class="function">searchAnswer</span>(data) {
<span class="keyword">function</span> <span class="function">isFeasible</span>(x) {
<span class="comment">// return true if x is a valid answer</span>
}
<span class="keyword">let</span> left = minPossible, right = maxPossible;
<span class="keyword">while</span> (left < right) {
<span class="keyword">const</span> mid = Math.floor((left + right) / <span class="number">2</span>);
<span class="keyword">if</span> (isFeasible(mid)) right = mid;
<span class="keyword">else</span> left = mid + <span class="number">1</span>;
}
<span class="keyword">return</span> left;
}</code></pre>
</section>
<!-- ============================================================ -->
<!-- 5. BFS PATTERN -->
<!-- ============================================================ -->
<section id="bfs">
<h2>5. BFS Pattern</h2>
<p>
Breadth-First Search processes nodes level by level using a queue. It is the go-to for <strong>shortest path in unweighted graphs/grids</strong> and level-order traversal in trees.
</p>
<div class="formula-box">
When to use: shortest path (unweighted), level-by-level processing, graph/grid exploration from a source
</div>
<h3>Core BFS Template</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> deque
<span class="keyword">def</span> <span class="function">bfs</span>(graph, start):
queue = deque([start])
visited = {start}
<span class="keyword">while</span> queue:
node = queue.popleft()
<span class="keyword">for</span> neighbor <span class="keyword">in</span> graph[node]:
<span class="keyword">if</span> neighbor <span class="keyword">not in</span> visited:
visited.add(neighbor)
queue.append(neighbor)</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">bfs</span>(graph, start) {
<span class="keyword">const</span> queue = [start];
<span class="keyword">const</span> visited = <span class="keyword">new</span> Set([start]);
<span class="keyword">while</span> (queue.length > <span class="number">0</span>) {
<span class="keyword">const</span> node = queue.shift();
<span class="keyword">for</span> (<span class="keyword">const</span> neighbor <span class="keyword">of</span> graph[node]) {
<span class="keyword">if</span> (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
}</code></pre>
<h3>Multi-Source BFS</h3>
<p>
Start BFS from <strong>multiple sources at once</strong> by putting them all in the queue initially. This is key for problems like "distance from nearest X" or "simultaneous spread."
</p>
<p><strong>Rotting Oranges</strong> -- All rotten oranges spread simultaneously. Find the time for all fresh oranges to rot (or -1 if impossible).</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> deque
<span class="keyword">def</span> <span class="function">oranges_rotting</span>(grid):
rows, cols = len(grid), len(grid[<span class="number">0</span>])
queue = deque()
fresh = <span class="number">0</span>
<span class="comment"># Collect all rotten oranges as starting points</span>
<span class="keyword">for</span> r <span class="keyword">in</span> range(rows):
<span class="keyword">for</span> c <span class="keyword">in</span> range(cols):
<span class="keyword">if</span> grid[r][c] == <span class="number">2</span>:
queue.append((r, c))
<span class="keyword">elif</span> grid[r][c] == <span class="number">1</span>:
fresh += <span class="number">1</span>
minutes = <span class="number">0</span>
directions = [(<span class="number">0</span>,<span class="number">1</span>), (<span class="number">0</span>,-<span class="number">1</span>), (<span class="number">1</span>,<span class="number">0</span>), (-<span class="number">1</span>,<span class="number">0</span>)]
<span class="keyword">while</span> queue <span class="keyword">and</span> fresh > <span class="number">0</span>:
minutes += <span class="number">1</span>
<span class="keyword">for</span> _ <span class="keyword">in</span> range(len(queue)): <span class="comment"># process current level</span>
r, c = queue.popleft()
<span class="keyword">for</span> dr, dc <span class="keyword">in</span> directions:
nr, nc = r + dr, c + dc
<span class="keyword">if</span> <span class="number">0</span> <= nr < rows <span class="keyword">and</span> <span class="number">0</span> <= nc < cols <span class="keyword">and</span> grid[nr][nc] == <span class="number">1</span>:
grid[nr][nc] = <span class="number">2</span>
fresh -= <span class="number">1</span>
queue.append((nr, nc))
<span class="keyword">return</span> minutes <span class="keyword">if</span> fresh == <span class="number">0</span> <span class="keyword">else</span> -<span class="number">1</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">orangesRotting</span>(grid) {
<span class="keyword">const</span> rows = grid.length, cols = grid[<span class="number">0</span>].length;
<span class="keyword">const</span> queue = [];
<span class="keyword">let</span> fresh = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">let</span> r = <span class="number">0</span>; r < rows; r++) {
<span class="keyword">for</span> (<span class="keyword">let</span> c = <span class="number">0</span>; c < cols; c++) {
<span class="keyword">if</span> (grid[r][c] === <span class="number">2</span>) queue.push([r, c]);
<span class="keyword">else if</span> (grid[r][c] === <span class="number">1</span>) fresh++;
}
}
<span class="keyword">const</span> dirs = [[<span class="number">0</span>,<span class="number">1</span>],[<span class="number">0</span>,-<span class="number">1</span>],[<span class="number">1</span>,<span class="number">0</span>],[-<span class="number">1</span>,<span class="number">0</span>]];
<span class="keyword">let</span> minutes = <span class="number">0</span>;
<span class="keyword">while</span> (queue.length > <span class="number">0</span> && fresh > <span class="number">0</span>) {
minutes++;
<span class="keyword">const</span> size = queue.length;
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < size; i++) {
<span class="keyword">const</span> [r, c] = queue.shift();
<span class="keyword">for</span> (<span class="keyword">const</span> [dr, dc] <span class="keyword">of</span> dirs) {
<span class="keyword">const</span> nr = r + dr, nc = c + dc;
<span class="keyword">if</span> (nr >= <span class="number">0</span> && nr < rows && nc >= <span class="number">0</span> && nc < cols && grid[nr][nc] === <span class="number">1</span>) {
grid[nr][nc] = <span class="number">2</span>;
fresh--;
queue.push([nr, nc]);
}
}
}
}
<span class="keyword">return</span> fresh === <span class="number">0</span> ? minutes : -<span class="number">1</span>;
}</code></pre>
<h3>Grid BFS</h3>
<p>
<strong>Number of Islands</strong> -- For each unvisited land cell, run BFS to mark the entire island. Count how many times you start a new BFS.
</p>
<p>
<strong>Shortest Path in Grid</strong> -- BFS naturally finds the shortest path because it explores all cells at distance d before distance d+1. Track distance by processing one level at a time.
</p>
<h3>Grid BFS Template</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> deque
<span class="keyword">def</span> <span class="function">grid_bfs</span>(grid, start_r, start_c):
rows, cols = len(grid), len(grid[<span class="number">0</span>])
queue = deque([(start_r, start_c, <span class="number">0</span>)]) <span class="comment"># row, col, distance</span>
visited = {(start_r, start_c)}
directions = [(<span class="number">0</span>,<span class="number">1</span>), (<span class="number">0</span>,-<span class="number">1</span>), (<span class="number">1</span>,<span class="number">0</span>), (-<span class="number">1</span>,<span class="number">0</span>)]
<span class="keyword">while</span> queue:
r, c, dist = queue.popleft()
<span class="keyword">for</span> dr, dc <span class="keyword">in</span> directions:
nr, nc = r + dr, c + dc
<span class="keyword">if</span> (<span class="number">0</span> <= nr < rows <span class="keyword">and</span> <span class="number">0</span> <= nc < cols
<span class="keyword">and</span> (nr, nc) <span class="keyword">not in</span> visited
<span class="keyword">and</span> grid[nr][nc] != obstacle):
visited.add((nr, nc))
queue.append((nr, nc, dist + <span class="number">1</span>))</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">gridBFS</span>(grid, startR, startC) {
<span class="keyword">const</span> rows = grid.length, cols = grid[<span class="number">0</span>].length;
<span class="keyword">const</span> queue = [[startR, startC, <span class="number">0</span>]];
<span class="keyword">const</span> visited = <span class="keyword">new</span> Set([<span class="string">`${startR},${startC}`</span>]);
<span class="keyword">const</span> dirs = [[<span class="number">0</span>,<span class="number">1</span>],[<span class="number">0</span>,-<span class="number">1</span>],[<span class="number">1</span>,<span class="number">0</span>],[-<span class="number">1</span>,<span class="number">0</span>]];
<span class="keyword">while</span> (queue.length > <span class="number">0</span>) {
<span class="keyword">const</span> [r, c, dist] = queue.shift();
<span class="keyword">for</span> (<span class="keyword">const</span> [dr, dc] <span class="keyword">of</span> dirs) {
<span class="keyword">const</span> nr = r + dr, nc = c + dc;
<span class="keyword">const</span> key = <span class="string">`${nr},${nc}`</span>;
<span class="keyword">if</span> (nr >= <span class="number">0</span> && nr < rows && nc >= <span class="number">0</span> && nc < cols
&& !visited.has(key) && grid[nr][nc] !== obstacle) {
visited.add(key);
queue.push([nr, nc, dist + <span class="number">1</span>]);
}
}
}
}</code></pre>
</section>
<!-- ============================================================ -->
<!-- 6. DFS & BACKTRACKING -->
<!-- ============================================================ -->
<section id="dfs">
<h2>6. DFS & Backtracking</h2>
<p>
Depth-First Search explores as deep as possible before backtracking. It is the natural choice for tree problems, exploring all paths, and generating combinations/permutations.
</p>
<div class="formula-box">
When to use: tree traversals, explore all paths, check connectivity, backtracking (all combinations, permutations, subsets)
</div>
<!-- Tree DFS -->
<h3>Tree DFS</h3>
<pre><code><span class="lang-label">Python</span>
<span class="comment"># Recursive DFS Template for Binary Trees</span>
<span class="keyword">def</span> <span class="function">dfs</span>(node):
<span class="keyword">if not</span> node:
<span class="keyword">return</span> base_case
left = dfs(node.left)
right = dfs(node.right)
<span class="keyword">return</span> combine(node.val, left, right)
<span class="comment"># Maximum Depth of Binary Tree</span>
<span class="keyword">def</span> <span class="function">max_depth</span>(root):
<span class="keyword">if not</span> root:
<span class="keyword">return</span> <span class="number">0</span>
<span class="keyword">return</span> <span class="number">1</span> + max(max_depth(root.left), max_depth(root.right))</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Recursive DFS Template for Binary Trees</span>
<span class="keyword">function</span> <span class="function">dfs</span>(node) {
<span class="keyword">if</span> (!node) <span class="keyword">return</span> baseCase;
<span class="keyword">const</span> left = dfs(node.left);
<span class="keyword">const</span> right = dfs(node.right);
<span class="keyword">return</span> combine(node.val, left, right);
}
<span class="comment">// Maximum Depth of Binary Tree</span>
<span class="keyword">function</span> <span class="function">maxDepth</span>(root) {
<span class="keyword">if</span> (!root) <span class="keyword">return</span> <span class="number">0</span>;
<span class="keyword">return</span> <span class="number">1</span> + Math.max(maxDepth(root.left), maxDepth(root.right));
}</code></pre>
<!-- Graph DFS -->
<h3>Graph DFS</h3>
<p><strong>Connected Components</strong> -- Run DFS from each unvisited node. Each DFS call discovers one connected component.</p>
<p><strong>Cycle Detection</strong> -- In directed graphs, track nodes in the current DFS path. If you visit a node already on the path, there is a cycle. Use three states: unvisited, in-progress, done.</p>
<!-- Backtracking -->
<h3>Backtracking</h3>
<p>
Backtracking is DFS with a twist: you <strong>make a choice, recurse, then undo the choice</strong> to try the next option. It generates all valid combinations, permutations, or subsets.
</p>
<p><strong>Subsets</strong> -- Generate all subsets of a set. At each index, choose to include or exclude the element.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">subsets</span>(nums):
result = []
<span class="keyword">def</span> <span class="function">backtrack</span>(start, current):
result.append(current[:]) <span class="comment"># snapshot current state</span>
<span class="keyword">for</span> i <span class="keyword">in</span> range(start, len(nums)):
current.append(nums[i]) <span class="comment"># choose</span>
backtrack(i + <span class="number">1</span>, current) <span class="comment"># explore</span>
current.pop() <span class="comment"># un-choose</span>
backtrack(<span class="number">0</span>, [])
<span class="keyword">return</span> result</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">subsets</span>(nums) {
<span class="keyword">const</span> result = [];
<span class="keyword">function</span> <span class="function">backtrack</span>(start, current) {
result.push([...current]);
<span class="keyword">for</span> (<span class="keyword">let</span> i = start; i < nums.length; i++) {
current.push(nums[i]); <span class="comment">// choose</span>
backtrack(i + <span class="number">1</span>, current); <span class="comment">// explore</span>
current.pop(); <span class="comment">// un-choose</span>
}
}
backtrack(<span class="number">0</span>, []);
<span class="keyword">return</span> result;
}</code></pre>
<p><strong>Permutations</strong> -- Generate all orderings of the input.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">permute</span>(nums):
result = []
<span class="keyword">def</span> <span class="function">backtrack</span>(current, remaining):
<span class="keyword">if not</span> remaining:
result.append(current[:])
<span class="keyword">return</span>
<span class="keyword">for</span> i <span class="keyword">in</span> range(len(remaining)):
current.append(remaining[i])
backtrack(current, remaining[:i] + remaining[i+<span class="number">1</span>:])
current.pop()
backtrack([], nums)
<span class="keyword">return</span> result</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">permute</span>(nums) {
<span class="keyword">const</span> result = [];
<span class="keyword">function</span> <span class="function">backtrack</span>(current, remaining) {
<span class="keyword">if</span> (remaining.length === <span class="number">0</span>) {
result.push([...current]);
<span class="keyword">return</span>;
}
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < remaining.length; i++) {
current.push(remaining[i]);
backtrack(current, [...remaining.slice(<span class="number">0</span>, i), ...remaining.slice(i + <span class="number">1</span>)]);
current.pop();
}
}
backtrack([], nums);
<span class="keyword">return</span> result;
}</code></pre>
<p><strong>Combination Sum</strong> -- Find all combinations that sum to a target, where each number can be used unlimited times. Same backtracking structure, but pass the same <code>start</code> index (not <code>i+1</code>) to allow reuse, and prune when the running sum exceeds the target.</p>
<h3>Backtracking Template</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">backtrack_template</span>(candidates):
result = []
<span class="keyword">def</span> <span class="function">backtrack</span>(start, current, remaining_state):
<span class="keyword">if</span> is_valid_solution(current):
result.append(current[:])
<span class="keyword">return</span>
<span class="keyword">for</span> i <span class="keyword">in</span> range(start, len(candidates)):
<span class="keyword">if</span> should_prune(candidates[i]):
<span class="keyword">continue</span>
current.append(candidates[i]) <span class="comment"># choose</span>
backtrack(i + <span class="number">1</span>, current, new_state) <span class="comment"># explore</span>
current.pop() <span class="comment"># un-choose</span>
backtrack(<span class="number">0</span>, [], initial_state)
<span class="keyword">return</span> result</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">backtrackTemplate</span>(candidates) {
<span class="keyword">const</span> result = [];
<span class="keyword">function</span> <span class="function">backtrack</span>(start, current, remainingState) {
<span class="keyword">if</span> (isValidSolution(current)) {
result.push([...current]);
<span class="keyword">return</span>;
}
<span class="keyword">for</span> (<span class="keyword">let</span> i = start; i < candidates.length; i++) {
<span class="keyword">if</span> (shouldPrune(candidates[i])) <span class="keyword">continue</span>;
current.push(candidates[i]);
backtrack(i + <span class="number">1</span>, current, newState);
current.pop();
}
}
backtrack(<span class="number">0</span>, [], initialState);
<span class="keyword">return</span> result;
}</code></pre>
</section>
<!-- ============================================================ -->
<!-- 7. PREFIX SUM -->
<!-- ============================================================ -->
<section id="prefix-sum">
<h2>7. Prefix Sum</h2>
<p>
Precompute a running sum array so you can answer any "sum of subarray from i to j" query in O(1). The prefix sum at index i is the sum of all elements from index 0 through i.
</p>
<div class="formula-box">
prefix[i] = arr[0] + arr[1] + ... + arr[i]<br>
sum(arr[left..right]) = prefix[right] - prefix[left - 1]
</div>
<div class="formula-box">
When to use: range sum queries, subarray sum equals k, any problem asking about contiguous subarray sums
</div>
<h3>Subarray Sum Equals K</h3>
<p>
Count the number of subarrays that sum to k. The brute force is O(n^2). The trick: use a hash map to store how many times each prefix sum has occurred. If <code>current_prefix - k</code> has been seen before, those are valid subarrays.
</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">subarray_sum</span>(nums, k):
count = <span class="number">0</span>
prefix = <span class="number">0</span>
prefix_counts = {<span class="number">0</span>: <span class="number">1</span>} <span class="comment"># empty prefix sum = 0 seen once</span>
<span class="keyword">for</span> num <span class="keyword">in</span> nums:
prefix += num
<span class="comment"># If (prefix - k) was seen before, those are valid subarrays</span>
count += prefix_counts.get(prefix - k, <span class="number">0</span>)
prefix_counts[prefix] = prefix_counts.get(prefix, <span class="number">0</span>) + <span class="number">1</span>
<span class="keyword">return</span> count</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">subarraySum</span>(nums, k) {
<span class="keyword">let</span> count = <span class="number">0</span>, prefix = <span class="number">0</span>;
<span class="keyword">const</span> prefixCounts = <span class="keyword">new</span> Map([[<span class="number">0</span>, <span class="number">1</span>]]);
<span class="keyword">for</span> (<span class="keyword">const</span> num <span class="keyword">of</span> nums) {
prefix += num;
count += (prefixCounts.get(prefix - k) || <span class="number">0</span>);
prefixCounts.set(prefix, (prefixCounts.get(prefix) || <span class="number">0</span>) + <span class="number">1</span>);
}
<span class="keyword">return</span> count;
}</code></pre>
<div class="example-box">
<div class="label">Example</div>
<p><code>nums = [1, 2, 3], k = 3</code> -- Prefix sums: [1, 3, 6]. At prefix=3, we check 3-3=0 which exists (count 1). At prefix=6, we check 6-3=3 which exists (count 1). Result: <strong>2</strong> subarrays ([1,2] and [3]).</p>
</div>
<h3>Prefix Sum Template</h3>
<pre><code><span class="lang-label">Python</span>
<span class="comment"># Build prefix array</span>
prefix = [<span class="number">0</span>] * (len(arr) + <span class="number">1</span>)
<span class="keyword">for</span> i <span class="keyword">in</span> range(len(arr)):
prefix[i + <span class="number">1</span>] = prefix[i] + arr[i]
<span class="comment"># Range sum query: sum from index l to r (inclusive)</span>
range_sum = prefix[r + <span class="number">1</span>] - prefix[l]
<span class="comment"># Prefix sum + hash map (for subarray sum = k)</span>
prefix = <span class="number">0</span>
seen = {<span class="number">0</span>: <span class="number">1</span>}
<span class="keyword">for</span> num <span class="keyword">in</span> arr:
prefix += num
<span class="keyword">if</span> prefix - k <span class="keyword">in</span> seen:
<span class="comment"># found valid subarrays</span>
<span class="keyword">pass</span>
seen[prefix] = seen.get(prefix, <span class="number">0</span>) + <span class="number">1</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Build prefix array</span>
<span class="keyword">const</span> prefix = <span class="keyword">new</span> Array(arr.length + <span class="number">1</span>).fill(<span class="number">0</span>);
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < arr.length; i++) {
prefix[i + <span class="number">1</span>] = prefix[i] + arr[i];
}
<span class="comment">// Range sum query: sum from index l to r (inclusive)</span>
<span class="keyword">const</span> rangeSum = prefix[r + <span class="number">1</span>] - prefix[l];
<span class="comment">// Prefix sum + hash map (for subarray sum = k)</span>
<span class="keyword">let</span> pre = <span class="number">0</span>;
<span class="keyword">const</span> seen = <span class="keyword">new</span> Map([[<span class="number">0</span>, <span class="number">1</span>]]);
<span class="keyword">for</span> (<span class="keyword">const</span> num <span class="keyword">of</span> arr) {
pre += num;
<span class="keyword">if</span> (seen.has(pre - k)) {
<span class="comment">// found valid subarrays</span>
}
seen.set(pre, (seen.get(pre) || <span class="number">0</span>) + <span class="number">1</span>);
}</code></pre>
</section>
<!-- ============================================================ -->
<!-- 8. MONOTONIC STACK -->
<!-- ============================================================ -->
<section id="monotonic-stack">
<h2>8. Monotonic Stack</h2>
<p>
A monotonic stack maintains elements in strictly increasing or decreasing order. When a new element violates the order, you pop from the stack -- and the popped elements have found their answer (the new element is their "next greater" or "next smaller").
</p>
<div class="formula-box">
When to use: next greater/smaller element, stock span, histogram area, trapping rain water
</div>
<h3>Daily Temperatures</h3>
<p>Given daily temperatures, for each day find how many days until a warmer temperature (or 0 if none).</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">daily_temperatures</span>(temperatures):
n = len(temperatures)
result = [<span class="number">0</span>] * n
stack = [] <span class="comment"># stores indices, monotonically decreasing temps</span>
<span class="keyword">for</span> i <span class="keyword">in</span> range(n):
<span class="keyword">while</span> stack <span class="keyword">and</span> temperatures[i] > temperatures[stack[-<span class="number">1</span>]]:
prev = stack.pop()
result[prev] = i - prev
stack.append(i)
<span class="keyword">return</span> result</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">dailyTemperatures</span>(temperatures) {
<span class="keyword">const</span> n = temperatures.length;
<span class="keyword">const</span> result = <span class="keyword">new</span> Array(n).fill(<span class="number">0</span>);
<span class="keyword">const</span> stack = [];