-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathadvanced.html
More file actions
1495 lines (1252 loc) · 86 KB
/
advanced.html
File metadata and controls
1495 lines (1252 loc) · 86 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>Advanced Data Structures & Techniques | 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> / Advanced</div>
<h1>Advanced Data Structures & Techniques</h1>
<p>Heaps, tries, union-find, monotonic stacks, segment trees, bit manipulation, and math tricks. Everything that doesn't fit neatly into the other pages but is still important for interviews.</p>
</div>
<!-- Table of Contents -->
<div class="toc">
<h4>Table of Contents</h4>
<a href="#heaps">1. Heaps / Priority Queue</a>
<a href="#tries">2. Tries (Prefix Trees)</a>
<a href="#union-find">3. Union-Find (Disjoint Set Union)</a>
<a href="#monotonic">4. Monotonic Stack / Monotonic Queue</a>
<a href="#segment-tree">5. Segment Tree</a>
<a href="#bit-manipulation">6. Bit Manipulation</a>
<a href="#math">7. Math for Interviews</a>
<a href="#quiz">8. Practice Quiz</a>
</div>
<!-- ============================================================ -->
<!-- 1. HEAPS / PRIORITY QUEUE -->
<!-- ============================================================ -->
<section id="heaps">
<h2>1. Heaps / Priority Queue</h2>
<h3>What is a Heap?</h3>
<p>
A <strong>heap</strong> is a <strong>complete binary tree</strong> that satisfies the heap property. It is the data structure behind a priority queue -- it lets you efficiently access, insert, and remove the minimum (or maximum) element.
</p>
<ul>
<li><strong>Min-heap:</strong> Every parent node is less than or equal to its children. The smallest element is always at the root.</li>
<li><strong>Max-heap:</strong> Every parent node is greater than or equal to its children. The largest element is always at the root.</li>
<li><strong>Complete binary tree:</strong> Every level is fully filled except possibly the last, which is filled left to right.</li>
<li><strong>Array storage:</strong> Heaps are stored as arrays. For a node at index <code>i</code>:
<ul>
<li>Parent: <code>Math.floor((i - 1) / 2)</code></li>
<li>Left child: <code>2 * i + 1</code></li>
<li>Right child: <code>2 * i + 2</code></li>
</ul>
</li>
</ul>
<div class="example-box">
<div class="label">Visual: Min-Heap</div>
<pre><code> 1 Array: [1, 3, 5, 7, 8, 9, 6]
/ \
3 5 Index: 0 1 2 3 4 5 6
/ \ / \
7 8 9 6 Parent of index 4 (value 8):
floor((4-1)/2) = index 1 (value 3)
Children of index 1 (value 3):
2*1+1 = index 3 (value 7)
2*1+2 = index 4 (value 8)</code></pre>
</div>
<h3>Time Complexity</h3>
<table>
<thead>
<tr><th>Operation</th><th>Time</th><th>Notes</th></tr>
</thead>
<tbody>
<tr><td>Insert (push)</td><td><code>O(log n)</code></td><td>Add at end, bubble up</td></tr>
<tr><td>Extract min/max (pop)</td><td><code>O(log n)</code></td><td>Remove root, bubble down</td></tr>
<tr><td>Peek min/max</td><td><code>O(1)</code></td><td>Root element</td></tr>
<tr><td>Build heap from array</td><td><code>O(n)</code></td><td>Not O(n log n) -- sift down approach</td></tr>
<tr><td>Search</td><td><code>O(n)</code></td><td>No ordering guarantee beyond parent-child</td></tr>
</tbody>
</table>
<div class="formula-box">
<strong>Heap Array Index Formulas (0-indexed):</strong><br><br>
• Parent of node i: floor((i - 1) / 2)<br>
• Left child of node i: 2i + 1<br>
• Right child of node i: 2i + 2<br><br>
<strong>Heap invariant:</strong> arr[parent(i)] ≤ arr[i] for min-heap (≥ for max-heap), for all i.
</div>
<h3>Using Heaps in Python</h3>
<p>
Python provides the <code>heapq</code> module which implements a <strong>min-heap</strong> by default. There is no built-in max-heap, but you can negate values as a workaround.
</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> heapq
<span class="comment"># --- Min-Heap ---</span>
heap = []
<span class="comment"># Push elements</span>
heapq.heappush(heap, <span class="number">5</span>)
heapq.heappush(heap, <span class="number">2</span>)
heapq.heappush(heap, <span class="number">8</span>)
heapq.heappush(heap, <span class="number">1</span>)
<span class="builtin">print</span>(heap) <span class="comment"># [1, 2, 8, 5]</span>
<span class="comment"># Peek at smallest</span>
<span class="builtin">print</span>(heap[<span class="number">0</span>]) <span class="comment"># 1</span>
<span class="comment"># Pop smallest</span>
smallest = heapq.heappop(heap)
<span class="builtin">print</span>(smallest) <span class="comment"># 1</span>
<span class="builtin">print</span>(heap) <span class="comment"># [2, 5, 8]</span>
<span class="comment"># Build heap from existing list (in-place, O(n))</span>
nums = [<span class="number">5</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">1</span>, <span class="number">2</span>]
heapq.heapify(nums)
<span class="builtin">print</span>(nums) <span class="comment"># [1, 2, 8, 5, 3]</span>
<span class="comment"># --- Max-Heap (negate values) ---</span>
max_heap = []
<span class="keyword">for</span> val <span class="keyword">in</span> [<span class="number">5</span>, <span class="number">2</span>, <span class="number">8</span>, <span class="number">1</span>]:
heapq.heappush(max_heap, -val)
largest = -heapq.heappop(max_heap)
<span class="builtin">print</span>(largest) <span class="comment"># 8</span>
<span class="comment"># --- Heap with tuples (priority, value) ---</span>
tasks = []
heapq.heappush(tasks, (<span class="number">3</span>, <span class="string">"low priority"</span>))
heapq.heappush(tasks, (<span class="number">1</span>, <span class="string">"high priority"</span>))
heapq.heappush(tasks, (<span class="number">2</span>, <span class="string">"medium priority"</span>))
<span class="builtin">print</span>(heapq.heappop(tasks)) <span class="comment"># (1, 'high priority')</span></code></pre>
<h3>Using Heaps in JavaScript</h3>
<p>
JavaScript has <strong>no built-in heap</strong>. You need to implement one yourself. Here is a clean MinHeap class you can use in interviews.
</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="function">MinHeap</span> {
<span class="function">constructor</span>() {
<span class="keyword">this</span>.data = [];
}
<span class="function">size</span>() { <span class="keyword">return</span> <span class="keyword">this</span>.data.length; }
<span class="function">peek</span>() { <span class="keyword">return</span> <span class="keyword">this</span>.data[<span class="number">0</span>]; }
<span class="function">isEmpty</span>() { <span class="keyword">return</span> <span class="keyword">this</span>.data.length === <span class="number">0</span>; }
<span class="function">push</span>(val) {
<span class="keyword">this</span>.data.push(val);
<span class="keyword">this</span>._bubbleUp(<span class="keyword">this</span>.data.length - <span class="number">1</span>);
}
<span class="function">pop</span>() {
<span class="keyword">const</span> top = <span class="keyword">this</span>.data[<span class="number">0</span>];
<span class="keyword">const</span> last = <span class="keyword">this</span>.data.pop();
<span class="keyword">if</span> (<span class="keyword">this</span>.data.length > <span class="number">0</span>) {
<span class="keyword">this</span>.data[<span class="number">0</span>] = last;
<span class="keyword">this</span>._sinkDown(<span class="number">0</span>);
}
<span class="keyword">return</span> top;
}
<span class="function">_bubbleUp</span>(i) {
<span class="keyword">while</span> (i > <span class="number">0</span>) {
<span class="keyword">const</span> parent = Math.floor((i - <span class="number">1</span>) / <span class="number">2</span>);
<span class="keyword">if</span> (<span class="keyword">this</span>.data[i] >= <span class="keyword">this</span>.data[parent]) <span class="keyword">break</span>;
[<span class="keyword">this</span>.data[i], <span class="keyword">this</span>.data[parent]] =
[<span class="keyword">this</span>.data[parent], <span class="keyword">this</span>.data[i]];
i = parent;
}
}
<span class="function">_sinkDown</span>(i) {
<span class="keyword">const</span> n = <span class="keyword">this</span>.data.length;
<span class="keyword">while</span> (<span class="keyword">true</span>) {
<span class="keyword">let</span> smallest = i;
<span class="keyword">const</span> left = <span class="number">2</span> * i + <span class="number">1</span>;
<span class="keyword">const</span> right = <span class="number">2</span> * i + <span class="number">2</span>;
<span class="keyword">if</span> (left < n && <span class="keyword">this</span>.data[left] < <span class="keyword">this</span>.data[smallest]) smallest = left;
<span class="keyword">if</span> (right < n && <span class="keyword">this</span>.data[right] < <span class="keyword">this</span>.data[smallest]) smallest = right;
<span class="keyword">if</span> (smallest === i) <span class="keyword">break</span>;
[<span class="keyword">this</span>.data[i], <span class="keyword">this</span>.data[smallest]] =
[<span class="keyword">this</span>.data[smallest], <span class="keyword">this</span>.data[i]];
i = smallest;
}
}
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> heap = <span class="keyword">new</span> <span class="function">MinHeap</span>();
heap.push(<span class="number">5</span>);
heap.push(<span class="number">2</span>);
heap.push(<span class="number">8</span>);
heap.push(<span class="number">1</span>);
console.log(heap.peek()); <span class="comment">// 1</span>
console.log(heap.pop()); <span class="comment">// 1</span>
console.log(heap.pop()); <span class="comment">// 2</span></code></pre>
<h3>Common Heap Problems</h3>
<h3>Kth Largest Element in an Array</h3>
<p>
Given an integer array <code>nums</code> and an integer <code>k</code>, return the <code>k</code>th largest element. Use a min-heap of size <code>k</code> -- the top is always the kth largest.
</p>
<div class="formula-box">Time: O(n log k) | Space: O(k)</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> heapq
<span class="keyword">def</span> <span class="function">findKthLargest</span>(nums, k):
<span class="comment"># Min-heap of size k</span>
heap = nums[:k]
heapq.heapify(heap) <span class="comment"># O(k)</span>
<span class="keyword">for</span> num <span class="keyword">in</span> nums[k:]:
<span class="keyword">if</span> num > heap[<span class="number">0</span>]: <span class="comment"># bigger than current kth largest?</span>
heapq.heapreplace(heap, num) <span class="comment"># pop smallest, push num</span>
<span class="keyword">return</span> heap[<span class="number">0</span>] <span class="comment"># root = kth largest</span>
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">findKthLargest</span>([<span class="number">3</span>,<span class="number">2</span>,<span class="number">1</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">4</span>], <span class="number">2</span>)) <span class="comment"># 5</span>
<span class="builtin">print</span>(<span class="function">findKthLargest</span>([<span class="number">3</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">5</span>,<span class="number">6</span>], <span class="number">4</span>)) <span class="comment"># 4</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">findKthLargest</span>(nums, k) {
<span class="keyword">const</span> heap = <span class="keyword">new</span> <span class="function">MinHeap</span>();
<span class="keyword">for</span> (<span class="keyword">const</span> num <span class="keyword">of</span> nums) {
heap.push(num);
<span class="keyword">if</span> (heap.size() > k) {
heap.pop(); <span class="comment">// remove smallest, keep k largest</span>
}
}
<span class="keyword">return</span> heap.peek(); <span class="comment">// kth largest</span>
}
console.log(<span class="function">findKthLargest</span>([<span class="number">3</span>,<span class="number">2</span>,<span class="number">1</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">4</span>], <span class="number">2</span>)); <span class="comment">// 5</span></code></pre>
<h3>Top K Frequent Elements</h3>
<p>
Given an integer array <code>nums</code> and an integer <code>k</code>, return the <code>k</code> most frequent elements. Count frequencies with a hash map, then use a min-heap of size <code>k</code>.
</p>
<div class="formula-box">Time: O(n log k) | Space: O(n)</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> heapq
<span class="keyword">from</span> collections <span class="keyword">import</span> Counter
<span class="keyword">def</span> <span class="function">topKFrequent</span>(nums, k):
count = Counter(nums)
<span class="comment"># nlargest returns k items with highest count</span>
<span class="keyword">return</span> heapq.nlargest(k, count.keys(), key=count.get)
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">topKFrequent</span>([<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">2</span>,<span class="number">3</span>], <span class="number">2</span>)) <span class="comment"># [1, 2]</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">topKFrequent</span>(nums, k) {
<span class="keyword">const</span> freq = <span class="keyword">new</span> Map();
<span class="keyword">for</span> (<span class="keyword">const</span> n <span class="keyword">of</span> nums) {
freq.set(n, (freq.get(n) || <span class="number">0</span>) + <span class="number">1</span>);
}
<span class="comment">// Bucket sort approach: index = frequency</span>
<span class="keyword">const</span> buckets = Array.from({ length: nums.length + <span class="number">1</span> }, () => []);
<span class="keyword">for</span> (<span class="keyword">const</span> [num, count] <span class="keyword">of</span> freq) {
buckets[count].push(num);
}
<span class="keyword">const</span> result = [];
<span class="keyword">for</span> (<span class="keyword">let</span> i = buckets.length - <span class="number">1</span>; i >= <span class="number">0</span> && result.length < k; i--) {
result.push(...buckets[i]);
}
<span class="keyword">return</span> result.slice(<span class="number">0</span>, k);
}
console.log(<span class="function">topKFrequent</span>([<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">2</span>,<span class="number">3</span>], <span class="number">2</span>)); <span class="comment">// [1, 2]</span></code></pre>
<h3>Merge K Sorted Lists</h3>
<p>
Push the head of each list into a min-heap. Pop the smallest, add it to the result, and push the next node from that list. Repeat until the heap is empty.
</p>
<div class="formula-box">Time: O(n log k) where n = total nodes, k = number of lists</div>
<h3>Find Median from Data Stream</h3>
<p>
Use <strong>two heaps</strong>: a max-heap for the lower half and a min-heap for the upper half. Keep them balanced (sizes differ by at most 1). The median is the top of the larger heap, or the average of both tops.
</p>
<div class="tip-box">
<div class="label">Tip</div>
<p>The two-heap pattern is extremely common. Any time you need to track the median or partition data into "small" and "large" halves, think two heaps.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- 2. TRIES (PREFIX TREES) -->
<!-- ============================================================ -->
<section id="tries">
<h2>2. Tries (Prefix Trees)</h2>
<h3>What is a Trie?</h3>
<p>
A <strong>trie</strong> (pronounced "try") is a tree-like data structure where each path from the root to a node represents a prefix of a word. Each node has children (one per character), and nodes can be marked as the end of a word.
</p>
<ul>
<li>The root node is empty (represents the empty string).</li>
<li>Each edge represents a single character.</li>
<li>Words that share a prefix share the same path from the root.</li>
<li>Lookup, insert, and prefix search are all <code>O(m)</code> where <code>m</code> is the length of the word.</li>
</ul>
<div class="example-box">
<div class="label">Visual: Trie with "cat", "car", "card"</div>
<pre><code> (root)
|
c
|
a
/ \
t r
* *
|
d
*
* = end of word
"cat" : root -> c -> a -> t*
"car" : root -> c -> a -> r*
"card" : root -> c -> a -> r -> d*
Searching "ca" : root -> c -> a (found prefix, not a complete word)
Searching "cab": root -> c -> a -> b (no 'b' child -- not found)</code></pre>
</div>
<h3>Implementation</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">TrieNode</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self):
self.children = {} <span class="comment"># char -> TrieNode</span>
self.is_end = <span class="keyword">False</span> <span class="comment"># marks end of a word</span>
<span class="keyword">class</span> <span class="function">Trie</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self):
self.root = TrieNode()
<span class="keyword">def</span> <span class="function">insert</span>(self, word):
<span class="string">"""Insert a word into the trie. O(m)"""</span>
node = self.root
<span class="keyword">for</span> ch <span class="keyword">in</span> word:
<span class="keyword">if</span> ch <span class="keyword">not</span> <span class="keyword">in</span> node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = <span class="keyword">True</span>
<span class="keyword">def</span> <span class="function">search</span>(self, word):
<span class="string">"""Return True if the exact word is in the trie. O(m)"""</span>
node = self._find(word)
<span class="keyword">return</span> node <span class="keyword">is not</span> <span class="keyword">None</span> <span class="keyword">and</span> node.is_end
<span class="keyword">def</span> <span class="function">startsWith</span>(self, prefix):
<span class="string">"""Return True if any word starts with the prefix. O(m)"""</span>
<span class="keyword">return</span> self._find(prefix) <span class="keyword">is not</span> <span class="keyword">None</span>
<span class="keyword">def</span> <span class="function">_find</span>(self, prefix):
<span class="string">"""Traverse trie following the prefix. Return last node or None."""</span>
node = self.root
<span class="keyword">for</span> ch <span class="keyword">in</span> prefix:
<span class="keyword">if</span> ch <span class="keyword">not</span> <span class="keyword">in</span> node.children:
<span class="keyword">return</span> <span class="keyword">None</span>
node = node.children[ch]
<span class="keyword">return</span> node
<span class="comment"># Usage</span>
trie = Trie()
trie.insert(<span class="string">"cat"</span>)
trie.insert(<span class="string">"car"</span>)
trie.insert(<span class="string">"card"</span>)
<span class="builtin">print</span>(trie.search(<span class="string">"car"</span>)) <span class="comment"># True</span>
<span class="builtin">print</span>(trie.search(<span class="string">"ca"</span>)) <span class="comment"># False (not a complete word)</span>
<span class="builtin">print</span>(trie.startsWith(<span class="string">"ca"</span>)) <span class="comment"># True</span>
<span class="builtin">print</span>(trie.startsWith(<span class="string">"dog"</span>)) <span class="comment"># False</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="function">TrieNode</span> {
<span class="function">constructor</span>() {
<span class="keyword">this</span>.children = {}; <span class="comment">// char -> TrieNode</span>
<span class="keyword">this</span>.isEnd = <span class="keyword">false</span>; <span class="comment">// marks end of a word</span>
}
}
<span class="keyword">class</span> <span class="function">Trie</span> {
<span class="function">constructor</span>() {
<span class="keyword">this</span>.root = <span class="keyword">new</span> <span class="function">TrieNode</span>();
}
<span class="comment">/** Insert a word into the trie. O(m) */</span>
<span class="function">insert</span>(word) {
<span class="keyword">let</span> node = <span class="keyword">this</span>.root;
<span class="keyword">for</span> (<span class="keyword">const</span> ch <span class="keyword">of</span> word) {
<span class="keyword">if</span> (!node.children[ch]) {
node.children[ch] = <span class="keyword">new</span> <span class="function">TrieNode</span>();
}
node = node.children[ch];
}
node.isEnd = <span class="keyword">true</span>;
}
<span class="comment">/** Return true if the exact word is in the trie. O(m) */</span>
<span class="function">search</span>(word) {
<span class="keyword">const</span> node = <span class="keyword">this</span>._find(word);
<span class="keyword">return</span> node !== <span class="keyword">null</span> && node.isEnd;
}
<span class="comment">/** Return true if any word starts with the prefix. O(m) */</span>
<span class="function">startsWith</span>(prefix) {
<span class="keyword">return</span> <span class="keyword">this</span>._find(prefix) !== <span class="keyword">null</span>;
}
<span class="function">_find</span>(prefix) {
<span class="keyword">let</span> node = <span class="keyword">this</span>.root;
<span class="keyword">for</span> (<span class="keyword">const</span> ch <span class="keyword">of</span> prefix) {
<span class="keyword">if</span> (!node.children[ch]) <span class="keyword">return</span> <span class="keyword">null</span>;
node = node.children[ch];
}
<span class="keyword">return</span> node;
}
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> trie = <span class="keyword">new</span> <span class="function">Trie</span>();
trie.insert(<span class="string">"cat"</span>);
trie.insert(<span class="string">"car"</span>);
trie.insert(<span class="string">"card"</span>);
console.log(trie.search(<span class="string">"car"</span>)); <span class="comment">// true</span>
console.log(trie.search(<span class="string">"ca"</span>)); <span class="comment">// false</span>
console.log(trie.startsWith(<span class="string">"ca"</span>)); <span class="comment">// true</span>
console.log(trie.startsWith(<span class="string">"dog"</span>)); <span class="comment">// false</span></code></pre>
<h3>Applications</h3>
<ul>
<li><strong>Autocomplete:</strong> Traverse to the prefix node, then DFS to find all completions.</li>
<li><strong>Spell checking:</strong> Check if a word exists; suggest corrections via similar paths.</li>
<li><strong>IP routing:</strong> Longest prefix matching in routers (binary trie).</li>
<li><strong>Word search problems:</strong> Build a trie of target words, then DFS on the board.</li>
</ul>
<h3>LeetCode: Implement Trie (Medium)</h3>
<p>The implementation above is the complete solution for <strong>LeetCode 208: Implement Trie</strong>. The key insight is using a dictionary (or object) of children at each node, plus a boolean flag for word endings.</p>
<h3>LeetCode: Word Search II (Hard)</h3>
<p>
Build a trie from all target words. Then for each cell in the board, DFS while following the trie. This prunes invalid paths early instead of searching for each word separately. The trie turns an O(words * cells * 4^L) brute force into something much faster.
</p>
<div class="tip-box">
<div class="label">Tip</div>
<p>For Word Search II, also remove trie nodes once all words through them are found. This optimization (pruning found words from the trie) prevents redundant exploration.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- 3. UNION-FIND (DISJOINT SET UNION) -->
<!-- ============================================================ -->
<section id="union-find">
<h2>3. Union-Find (Disjoint Set Union)</h2>
<h3>What is Union-Find?</h3>
<p>
<strong>Union-Find</strong> (also called Disjoint Set Union or DSU) is a data structure that tracks a set of elements partitioned into disjoint (non-overlapping) groups. It supports two operations efficiently:
</p>
<ul>
<li><strong>Find(x):</strong> Which group does element x belong to? (Returns the group's representative/root.)</li>
<li><strong>Union(x, y):</strong> Merge the groups containing x and y into one group.</li>
</ul>
<p>
With <strong>path compression</strong> and <strong>union by rank</strong>, both operations run in nearly <code>O(1)</code> amortized time -- specifically <code>O(alpha(n))</code> where alpha is the inverse Ackermann function, which is effectively constant for any practical input size.
</p>
<div class="formula-box">
Find: O(alpha(n)) ~ O(1) amortized | Union: O(alpha(n)) ~ O(1) amortized
</div>
<h3>Implementation</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">UnionFind</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, n):
self.parent = <span class="builtin">list</span>(<span class="builtin">range</span>(n)) <span class="comment"># each element is its own root</span>
self.rank = [<span class="number">0</span>] * n <span class="comment"># rank for union by rank</span>
self.count = n <span class="comment"># number of disjoint sets</span>
<span class="keyword">def</span> <span class="function">find</span>(self, x):
<span class="string">"""Find root of x with path compression."""</span>
<span class="keyword">if</span> self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) <span class="comment"># path compression</span>
<span class="keyword">return</span> self.parent[x]
<span class="keyword">def</span> <span class="function">union</span>(self, x, y):
<span class="string">"""Merge sets containing x and y. Return False if already same set."""</span>
rx, ry = self.find(x), self.find(y)
<span class="keyword">if</span> rx == ry:
<span class="keyword">return</span> <span class="keyword">False</span> <span class="comment"># already connected</span>
<span class="comment"># Union by rank: attach smaller tree under larger</span>
<span class="keyword">if</span> self.rank[rx] < self.rank[ry]:
rx, ry = ry, rx
self.parent[ry] = rx
<span class="keyword">if</span> self.rank[rx] == self.rank[ry]:
self.rank[rx] += <span class="number">1</span>
self.count -= <span class="number">1</span>
<span class="keyword">return</span> <span class="keyword">True</span>
<span class="keyword">def</span> <span class="function">connected</span>(self, x, y):
<span class="string">"""Check if x and y are in the same set."""</span>
<span class="keyword">return</span> self.find(x) == self.find(y)
<span class="comment"># Usage</span>
uf = UnionFind(<span class="number">5</span>) <span class="comment"># elements: 0, 1, 2, 3, 4</span>
uf.union(<span class="number">0</span>, <span class="number">1</span>) <span class="comment"># merge {0} and {1}</span>
uf.union(<span class="number">2</span>, <span class="number">3</span>) <span class="comment"># merge {2} and {3}</span>
<span class="builtin">print</span>(uf.connected(<span class="number">0</span>, <span class="number">1</span>)) <span class="comment"># True</span>
<span class="builtin">print</span>(uf.connected(<span class="number">0</span>, <span class="number">2</span>)) <span class="comment"># False</span>
uf.union(<span class="number">1</span>, <span class="number">3</span>) <span class="comment"># merge {0,1} and {2,3}</span>
<span class="builtin">print</span>(uf.connected(<span class="number">0</span>, <span class="number">2</span>)) <span class="comment"># True</span>
<span class="builtin">print</span>(uf.count) <span class="comment"># 2 (groups: {0,1,2,3} and {4})</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="function">UnionFind</span> {
<span class="function">constructor</span>(n) {
<span class="keyword">this</span>.parent = Array.from({ length: n }, (_, i) => i);
<span class="keyword">this</span>.rank = <span class="keyword">new</span> Array(n).fill(<span class="number">0</span>);
<span class="keyword">this</span>.count = n; <span class="comment">// number of disjoint sets</span>
}
<span class="function">find</span>(x) {
<span class="keyword">if</span> (<span class="keyword">this</span>.parent[x] !== x) {
<span class="keyword">this</span>.parent[x] = <span class="keyword">this</span>.find(<span class="keyword">this</span>.parent[x]); <span class="comment">// path compression</span>
}
<span class="keyword">return</span> <span class="keyword">this</span>.parent[x];
}
<span class="function">union</span>(x, y) {
<span class="keyword">let</span> rx = <span class="keyword">this</span>.find(x), ry = <span class="keyword">this</span>.find(y);
<span class="keyword">if</span> (rx === ry) <span class="keyword">return</span> <span class="keyword">false</span>; <span class="comment">// already connected</span>
<span class="comment">// Union by rank</span>
<span class="keyword">if</span> (<span class="keyword">this</span>.rank[rx] < <span class="keyword">this</span>.rank[ry]) [rx, ry] = [ry, rx];
<span class="keyword">this</span>.parent[ry] = rx;
<span class="keyword">if</span> (<span class="keyword">this</span>.rank[rx] === <span class="keyword">this</span>.rank[ry]) <span class="keyword">this</span>.rank[rx]++;
<span class="keyword">this</span>.count--;
<span class="keyword">return</span> <span class="keyword">true</span>;
}
<span class="function">connected</span>(x, y) {
<span class="keyword">return</span> <span class="keyword">this</span>.find(x) === <span class="keyword">this</span>.find(y);
}
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> uf = <span class="keyword">new</span> <span class="function">UnionFind</span>(<span class="number">5</span>);
uf.union(<span class="number">0</span>, <span class="number">1</span>);
uf.union(<span class="number">2</span>, <span class="number">3</span>);
console.log(uf.connected(<span class="number">0</span>, <span class="number">1</span>)); <span class="comment">// true</span>
console.log(uf.connected(<span class="number">0</span>, <span class="number">2</span>)); <span class="comment">// false</span>
uf.union(<span class="number">1</span>, <span class="number">3</span>);
console.log(uf.connected(<span class="number">0</span>, <span class="number">2</span>)); <span class="comment">// true</span>
console.log(uf.count); <span class="comment">// 2</span></code></pre>
<h3>Applications</h3>
<ul>
<li><strong>Number of connected components:</strong> Union all edges, then check <code>uf.count</code>.</li>
<li><strong>Cycle detection in undirected graph:</strong> If <code>union(u, v)</code> returns false, there is a cycle (u and v are already connected).</li>
<li><strong>Kruskal's MST algorithm:</strong> Sort edges by weight, union vertices; skip if already connected.</li>
</ul>
<h3>LeetCode: Number of Provinces (Medium)</h3>
<p>
Given an adjacency matrix <code>isConnected</code> where <code>isConnected[i][j] = 1</code> means city i and city j are directly connected, return the number of provinces (connected components).
</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">findCircleNum</span>(isConnected):
n = <span class="builtin">len</span>(isConnected)
uf = UnionFind(n)
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(n):
<span class="keyword">for</span> j <span class="keyword">in</span> <span class="builtin">range</span>(i + <span class="number">1</span>, n):
<span class="keyword">if</span> isConnected[i][j] == <span class="number">1</span>:
uf.union(i, j)
<span class="keyword">return</span> uf.count
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">findCircleNum</span>([[<span class="number">1</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">0</span>,<span class="number">0</span>,<span class="number">1</span>]])) <span class="comment"># 2</span>
<span class="builtin">print</span>(<span class="function">findCircleNum</span>([[<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>],[<span class="number">0</span>,<span class="number">1</span>,<span class="number">0</span>],[<span class="number">0</span>,<span class="number">0</span>,<span class="number">1</span>]])) <span class="comment"># 3</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">findCircleNum</span>(isConnected) {
<span class="keyword">const</span> n = isConnected.length;
<span class="keyword">const</span> uf = <span class="keyword">new</span> <span class="function">UnionFind</span>(n);
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < n; i++) {
<span class="keyword">for</span> (<span class="keyword">let</span> j = i + <span class="number">1</span>; j < n; j++) {
<span class="keyword">if</span> (isConnected[i][j] === <span class="number">1</span>) {
uf.union(i, j);
}
}
}
<span class="keyword">return</span> uf.count;
}
console.log(<span class="function">findCircleNum</span>([[<span class="number">1</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">0</span>,<span class="number">0</span>,<span class="number">1</span>]])); <span class="comment">// 2</span></code></pre>
<h3>LeetCode: Redundant Connection (Medium)</h3>
<p>
Given a graph that was a tree plus one extra edge, find that extra edge. Process edges in order; the first edge where <code>union(u, v)</code> returns false (both already connected) is the answer. This is a direct application of cycle detection with Union-Find.
</p>
<div class="formula-box">
<strong>Union-Find Complexity:</strong><br><br>
With path compression + union by rank: O(α(n)) per operation (amortized), where α is the inverse Ackermann function. For all practical purposes, α(n) ≤ 4, so this is effectively O(1).
</div>
</section>
<!-- ============================================================ -->
<!-- 4. MONOTONIC STACK / MONOTONIC QUEUE -->
<!-- ============================================================ -->
<section id="monotonic">
<h2>4. Monotonic Stack / Monotonic Queue</h2>
<h3>Monotonic Stack</h3>
<p>
A <strong>monotonic stack</strong> is a stack that maintains its elements in either strictly increasing or strictly decreasing order. When you push a new element, you first pop all elements that violate the monotonic property.
</p>
<p>
<strong>When to use:</strong> Any problem asking for the "next greater element", "next smaller element", "previous greater/smaller", or "how many days until a warmer temperature". The key pattern is: <em>for each element, find the nearest element that is larger/smaller</em>.
</p>
<div class="formula-box">Time: O(n) -- each element is pushed and popped at most once</div>
<div class="formula-box">
<strong>Monotonic Stack -- Invariant:</strong><br><br>
• <strong>Monotonic increasing stack:</strong> stack[i] < stack[i+1] at all times. Pop when arr[j] < stack.top().<br>
• <strong>Monotonic decreasing stack:</strong> stack[i] > stack[i+1] at all times. Pop when arr[j] > stack.top().<br><br>
<strong>Key insight:</strong> The pop event means "found the next smaller/greater element for all popped items."<br>
<strong>Time:</strong> O(n) -- each element enters and leaves the stack at most once.
</div>
<h3>Template: Next Greater Element</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">nextGreaterElement</span>(nums):
<span class="string">"""For each element, find the next element that is strictly greater.
Return -1 if no such element exists."""</span>
n = <span class="builtin">len</span>(nums)
result = [-<span class="number">1</span>] * n
stack = [] <span class="comment"># stores indices, values decrease from bottom to top</span>
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(n):
<span class="comment"># While current element is greater than stack top</span>
<span class="keyword">while</span> stack <span class="keyword">and</span> nums[i] > nums[stack[-<span class="number">1</span>]]:
idx = stack.pop()
result[idx] = nums[i] <span class="comment"># nums[i] is the next greater for nums[idx]</span>
stack.append(i)
<span class="keyword">return</span> result
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">nextGreaterElement</span>([<span class="number">2</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">3</span>]))
<span class="comment"># [4, 2, 4, -1, -1]</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">nextGreaterElement</span>(nums) {
<span class="keyword">const</span> n = nums.length;
<span class="keyword">const</span> result = <span class="keyword">new</span> Array(n).fill(-<span class="number">1</span>);
<span class="keyword">const</span> stack = []; <span class="comment">// stores indices</span>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < n; i++) {
<span class="keyword">while</span> (stack.length && nums[i] > nums[stack[stack.length - <span class="number">1</span>]]) {
<span class="keyword">const</span> idx = stack.pop();
result[idx] = nums[i];
}
stack.push(i);
}
<span class="keyword">return</span> result;
}
console.log(<span class="function">nextGreaterElement</span>([<span class="number">2</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">3</span>]));
<span class="comment">// [4, 2, 4, -1, -1]</span></code></pre>
<h3>Daily Temperatures</h3>
<p>
Given an array of daily temperatures, return an array where <code>answer[i]</code> is the number of days until a warmer temperature. This is the "next greater element" pattern but returning the index distance instead of the value.
</p>
<h3>Monotonic Deque (Sliding Window Maximum)</h3>
<p>
A <strong>monotonic deque</strong> maintains elements in decreasing order. The front of the deque is always the maximum in the current window. When the window slides, we remove elements that fall out of the window from the front and maintain the decreasing order from the back.
</p>
<h3>Sliding Window Maximum -- Full Solution</h3>
<p>
Given an array <code>nums</code> and window size <code>k</code>, return the maximum value in each sliding window of size <code>k</code>.
</p>
<div class="formula-box">Time: O(n) | Space: O(k)</div>
<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">maxSlidingWindow</span>(nums, k):
dq = deque() <span class="comment"># stores indices, values decreasing front-to-back</span>
result = []
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(<span class="builtin">len</span>(nums)):
<span class="comment"># Remove elements outside the window</span>
<span class="keyword">while</span> dq <span class="keyword">and</span> dq[<span class="number">0</span>] < i - k + <span class="number">1</span>:
dq.popleft()
<span class="comment"># Remove elements smaller than current (they can't be max)</span>
<span class="keyword">while</span> dq <span class="keyword">and</span> nums[dq[-<span class="number">1</span>]] < nums[i]:
dq.pop()
dq.append(i)
<span class="comment"># Window is fully formed starting at i = k - 1</span>
<span class="keyword">if</span> i >= k - <span class="number">1</span>:
result.append(nums[dq[<span class="number">0</span>]])
<span class="keyword">return</span> result
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">maxSlidingWindow</span>([<span class="number">1</span>,<span class="number">3</span>,-<span class="number">1</span>,-<span class="number">3</span>,<span class="number">5</span>,<span class="number">3</span>,<span class="number">6</span>,<span class="number">7</span>], <span class="number">3</span>))
<span class="comment"># [3, 3, 5, 5, 6, 7]</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">maxSlidingWindow</span>(nums, k) {
<span class="keyword">const</span> dq = []; <span class="comment">// indices, values decreasing front-to-back</span>
<span class="keyword">const</span> result = [];
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < nums.length; i++) {
<span class="comment">// Remove elements outside window</span>
<span class="keyword">while</span> (dq.length && dq[<span class="number">0</span>] < i - k + <span class="number">1</span>) {
dq.shift();
}
<span class="comment">// Remove elements smaller than current</span>
<span class="keyword">while</span> (dq.length && nums[dq[dq.length - <span class="number">1</span>]] < nums[i]) {
dq.pop();
}
dq.push(i);
<span class="keyword">if</span> (i >= k - <span class="number">1</span>) {
result.push(nums[dq[<span class="number">0</span>]]);
}
}
<span class="keyword">return</span> result;
}
console.log(<span class="function">maxSlidingWindow</span>([<span class="number">1</span>,<span class="number">3</span>,-<span class="number">1</span>,-<span class="number">3</span>,<span class="number">5</span>,<span class="number">3</span>,<span class="number">6</span>,<span class="number">7</span>], <span class="number">3</span>));
<span class="comment">// [3, 3, 5, 5, 6, 7]</span></code></pre>
<div class="tip-box">
<div class="label">Tip</div>
<p>The monotonic stack/deque pattern feels unnatural at first. The key insight: the stack stores <strong>indices of candidates</strong> that might still be useful. Once an element can never be the answer (because a better candidate arrived), it gets popped. Each element enters and leaves the stack at most once, giving O(n) total.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- 5. SEGMENT TREE -->
<!-- ============================================================ -->
<section id="segment-tree">
<h2>5. Segment Tree (Brief)</h2>
<p>
A <strong>segment tree</strong> is a binary tree used for storing information about intervals (segments) of an array. It allows for efficient range queries (sum, min, max over a subarray) and point updates.
</p>
<ul>
<li><strong>Query</strong> (range sum/min/max): <code>O(log n)</code></li>
<li><strong>Update</strong> (change a single element): <code>O(log n)</code></li>
<li><strong>Build:</strong> <code>O(n)</code></li>
<li><strong>Space:</strong> <code>O(n)</code></li>
</ul>
<p>
<strong>When you need it:</strong> When a problem requires both range queries (sum of subarray, minimum in range) AND point updates. If you only need range queries without updates, a prefix sum array works. If you only need updates without queries, a simple array works. Segment trees solve the case where you need <em>both</em>.
</p>
<div class="formula-box">
Prefix sum: O(1) query, O(n) update<br>
Segment tree: O(log n) query, O(log n) update -- the best of both worlds
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">SegmentTree</span>:
<span class="string">"""Segment tree for range sum queries with point updates."""</span>
<span class="keyword">def</span> <span class="function">__init__</span>(self, nums):
self.n = <span class="builtin">len</span>(nums)
self.tree = [<span class="number">0</span>] * (<span class="number">2</span> * self.n)
<span class="comment"># Build: place values in leaves, then fill parents</span>
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(self.n):
self.tree[self.n + i] = nums[i]
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(self.n - <span class="number">1</span>, <span class="number">0</span>, -<span class="number">1</span>):
self.tree[i] = self.tree[<span class="number">2</span> * i] + self.tree[<span class="number">2</span> * i + <span class="number">1</span>]
<span class="keyword">def</span> <span class="function">update</span>(self, index, value):
<span class="string">"""Set nums[index] = value. O(log n)"""</span>
i = index + self.n
self.tree[i] = value
<span class="keyword">while</span> i > <span class="number">1</span>:
i //= <span class="number">2</span>
self.tree[i] = self.tree[<span class="number">2</span> * i] + self.tree[<span class="number">2</span> * i + <span class="number">1</span>]
<span class="keyword">def</span> <span class="function">query</span>(self, left, right):
<span class="string">"""Sum of nums[left..right] inclusive. O(log n)"""</span>
res = <span class="number">0</span>
l, r = left + self.n, right + self.n + <span class="number">1</span>
<span class="keyword">while</span> l < r:
<span class="keyword">if</span> l & <span class="number">1</span>:
res += self.tree[l]
l += <span class="number">1</span>
<span class="keyword">if</span> r & <span class="number">1</span>:
r -= <span class="number">1</span>
res += self.tree[r]
l >>= <span class="number">1</span>
r >>= <span class="number">1</span>
<span class="keyword">return</span> res
<span class="comment"># Usage</span>
nums = [<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>, <span class="number">11</span>]
st = SegmentTree(nums)
<span class="builtin">print</span>(st.query(<span class="number">1</span>, <span class="number">3</span>)) <span class="comment"># 15 (3 + 5 + 7)</span>
st.update(<span class="number">2</span>, <span class="number">10</span>) <span class="comment"># change index 2 from 5 to 10</span>
<span class="builtin">print</span>(st.query(<span class="number">1</span>, <span class="number">3</span>)) <span class="comment"># 20 (3 + 10 + 7)</span></code></pre>
<div class="warning-box">
<div class="label">Interview Note</div>
<p>Segment trees are <strong>rarely asked in interviews</strong> at most companies. They appear more in competitive programming and at companies with algorithm-heavy interviews. Know what they are and when to use them, but don't prioritize implementing one from scratch unless you are targeting competitive programming roles.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- 6. BIT MANIPULATION -->
<!-- ============================================================ -->
<section id="bit-manipulation">
<h2>6. Bit Manipulation</h2>
<h3>Binary Representation</h3>
<p>
Computers store numbers in binary (base 2). Each digit is a <strong>bit</strong> (0 or 1). Understanding how to work with bits directly lets you solve certain problems with extreme efficiency -- O(1) space and blazing fast operations.
</p>
<div class="example-box">
<div class="label">Binary Basics</div>
<pre><code>Decimal Binary How to read it
0 0000 no bits set
1 0001 2^0 = 1
5 0101 2^2 + 2^0 = 4 + 1 = 5
10 1010 2^3 + 2^1 = 8 + 2 = 10
15 1111 2^3 + 2^2 + 2^1 + 2^0 = 8+4+2+1 = 15
255 11111111 all 8 bits set</code></pre>
</div>
<h3>Common Bitwise Operators</h3>
<table>
<thead>
<tr><th>Operator</th><th>Name</th><th>Example</th><th>Result</th></tr>
</thead>
<tbody>
<tr><td><code>&</code></td><td>AND</td><td><code>5 & 3</code> (0101 & 0011)</td><td><code>1</code> (0001)</td></tr>
<tr><td><code>|</code></td><td>OR</td><td><code>5 | 3</code> (0101 | 0011)</td><td><code>7</code> (0111)</td></tr>
<tr><td><code>^</code></td><td>XOR</td><td><code>5 ^ 3</code> (0101 ^ 0011)</td><td><code>6</code> (0110)</td></tr>
<tr><td><code>~</code></td><td>NOT</td><td><code>~5</code></td><td><code>-6</code> (flips all bits)</td></tr>
<tr><td><code><<</code></td><td>Left shift</td><td><code>3 << 2</code></td><td><code>12</code> (multiply by 4)</td></tr>
<tr><td><code>>></code></td><td>Right shift</td><td><code>12 >> 2</code></td><td><code>3</code> (divide by 4)</td></tr>
</tbody>
</table>
<h3>Useful Bit Tricks</h3>
<h3>Check if Power of 2</h3>
<p>A power of 2 has exactly one bit set. <code>n & (n - 1)</code> clears the lowest set bit. If the result is 0, only one bit was set.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">isPowerOfTwo</span>(n):