-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstacks-queues.html
More file actions
1326 lines (1124 loc) · 77.1 KB
/
stacks-queues.html
File metadata and controls
1326 lines (1124 loc) · 77.1 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>Stacks & Queues | Learn 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> / Stacks & Queues</div>
<h1>Stacks & Queues</h1>
<p>Linear data structures with restricted access patterns -- the backbone of parsing, traversal, and scheduling algorithms.</p>
</div>
<!-- Table of Contents -->
<div class="toc">
<h4>On This Page</h4>
<a href="#stacks">1. Stacks (LIFO)</a>
<a href="#stack-impl">2. Stack Implementations</a>
<a href="#stack-problems">3. Common Stack Problems</a>
<a href="#queues">4. Queues (FIFO)</a>
<a href="#queue-impl">5. Queue Implementations</a>
<a href="#queue-problems">6. Common Queue Problems</a>
<a href="#deque">7. Deque (Double-Ended Queue)</a>
<a href="#priority-queue">8. Priority Queue / Heap</a>
<a href="#complexity">9. Time Complexity Table</a>
<a href="#applications">10. Real-World Applications</a>
<a href="#leetcode">11. LeetCode Problems</a>
<a href="#quiz">12. Practice Quiz</a>
</div>
<!-- ============================================ -->
<!-- SECTION 1: STACKS -->
<!-- ============================================ -->
<section id="stacks">
<h2>1. Stacks (LIFO - Last In, First Out)</h2>
<p>
A <strong>stack</strong> is a linear data structure that follows the <strong>LIFO</strong> principle: the last element added is the first one removed. Think of a stack of plates -- you can only add or remove plates from the top.
</p>
<div class="formula-box"> | 3 | ← top (last in, first out)
| 2 |
| 1 |
+---+</div>
<p>Every stack supports these core operations, and they all run in <strong>O(1)</strong> time:</p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Description</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr><td><code>push(x)</code></td><td>Add element <code>x</code> to the top</td><td>O(1)</td></tr>
<tr><td><code>pop()</code></td><td>Remove and return the top element</td><td>O(1)</td></tr>
<tr><td><code>peek()</code> / <code>top()</code></td><td>Return the top element without removing it</td><td>O(1)</td></tr>
<tr><td><code>isEmpty()</code></td><td>Check if the stack is empty</td><td>O(1)</td></tr>
<tr><td><code>size()</code></td><td>Return the number of elements</td><td>O(1)</td></tr>
</tbody>
</table>
<div class="example-box">
<div class="label">Analogy</div>
<p>
Imagine a stack of plates in a cafeteria. You always grab the plate on top (pop), and new clean plates go on top (push). You never pull from the middle or bottom -- that would collapse the stack. This restricted access is what makes stacks powerful for tracking "most recent" state.
</p>
</div>
<div class="formula-box">
<strong>When to Use a Stack -- Precise Trigger Conditions:</strong><br><br>
1. <strong>Matching/nesting:</strong> Valid parentheses, HTML tags, nested structures<br>
2. <strong>Nearest greater/smaller element:</strong> Monotonic stack pattern<br>
3. <strong>Undo/redo state:</strong> Most recent action needs to be reversed first<br>
4. <strong>DFS iteratively:</strong> Replace recursion stack with explicit stack<br>
5. <strong>Expression evaluation:</strong> Reverse Polish Notation, infix to postfix<br><br>
<strong>Invariant:</strong> The answer at position i depends on the most recently seen unmatched element.
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 2: STACK IMPLEMENTATIONS -->
<!-- ============================================ -->
<section id="stack-impl">
<h2>2. Stack Implementations</h2>
<h3>Python: Using a List</h3>
<p>Python lists support <code>append()</code> and <code>pop()</code> at the end in amortized O(1). This is the simplest stack implementation.</p>
<pre><code><span class="lang-label">Python</span>
<span class="comment"># Stack using a Python list</span>
stack = []
stack.<span class="function">append</span>(<span class="number">1</span>) <span class="comment"># push 1</span>
stack.<span class="function">append</span>(<span class="number">2</span>) <span class="comment"># push 2</span>
stack.<span class="function">append</span>(<span class="number">3</span>) <span class="comment"># push 3</span>
<span class="builtin">print</span>(stack[<span class="number">-1</span>]) <span class="comment"># peek: 3</span>
<span class="builtin">print</span>(stack.<span class="function">pop</span>()) <span class="comment"># pop: 3</span>
<span class="builtin">print</span>(stack) <span class="comment"># [1, 2]</span>
<span class="builtin">print</span>(<span class="builtin">len</span>(stack)) <span class="comment"># size: 2</span>
<span class="builtin">print</span>(<span class="keyword">not</span> stack) <span class="comment"># isEmpty: False</span></code></pre>
<h3>Python: Using collections.deque</h3>
<p>A <code>deque</code> (double-ended queue) gives guaranteed O(1) for both ends. Slightly more robust than a plain list.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> deque
stack = <span class="function">deque</span>()
stack.<span class="function">append</span>(<span class="number">1</span>) <span class="comment"># push</span>
stack.<span class="function">append</span>(<span class="number">2</span>)
stack.<span class="function">append</span>(<span class="number">3</span>)
<span class="builtin">print</span>(stack[<span class="number">-1</span>]) <span class="comment"># peek: 3</span>
<span class="builtin">print</span>(stack.<span class="function">pop</span>()) <span class="comment"># pop: 3</span>
<span class="builtin">print</span>(<span class="builtin">len</span>(stack)) <span class="comment"># size: 2</span></code></pre>
<h3>JavaScript: Using an Array</h3>
<p>JavaScript arrays have built-in <code>push()</code> and <code>pop()</code> methods that work in O(1).</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Stack using a JavaScript array</span>
<span class="keyword">const</span> stack = [];
stack.<span class="function">push</span>(<span class="number">1</span>); <span class="comment">// push 1</span>
stack.<span class="function">push</span>(<span class="number">2</span>); <span class="comment">// push 2</span>
stack.<span class="function">push</span>(<span class="number">3</span>); <span class="comment">// push 3</span>
console.<span class="function">log</span>(stack[stack.length - <span class="number">1</span>]); <span class="comment">// peek: 3</span>
console.<span class="function">log</span>(stack.<span class="function">pop</span>()); <span class="comment">// pop: 3</span>
console.<span class="function">log</span>(stack); <span class="comment">// [1, 2]</span>
console.<span class="function">log</span>(stack.length); <span class="comment">// size: 2</span>
console.<span class="function">log</span>(stack.length === <span class="number">0</span>); <span class="comment">// isEmpty: false</span></code></pre>
<h3>Full Stack Class: Python</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">Stack</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(<span class="builtin">self</span>):
<span class="builtin">self</span>._data = []
<span class="keyword">def</span> <span class="function">push</span>(<span class="builtin">self</span>, val):
<span class="builtin">self</span>._data.<span class="function">append</span>(val)
<span class="keyword">def</span> <span class="function">pop</span>(<span class="builtin">self</span>):
<span class="keyword">if</span> <span class="builtin">self</span>.<span class="function">is_empty</span>():
<span class="keyword">raise</span> <span class="builtin">IndexError</span>(<span class="string">"pop from empty stack"</span>)
<span class="keyword">return</span> <span class="builtin">self</span>._data.<span class="function">pop</span>()
<span class="keyword">def</span> <span class="function">peek</span>(<span class="builtin">self</span>):
<span class="keyword">if</span> <span class="builtin">self</span>.<span class="function">is_empty</span>():
<span class="keyword">raise</span> <span class="builtin">IndexError</span>(<span class="string">"peek from empty stack"</span>)
<span class="keyword">return</span> <span class="builtin">self</span>._data[<span class="number">-1</span>]
<span class="keyword">def</span> <span class="function">is_empty</span>(<span class="builtin">self</span>):
<span class="keyword">return</span> <span class="builtin">len</span>(<span class="builtin">self</span>._data) == <span class="number">0</span>
<span class="keyword">def</span> <span class="function">size</span>(<span class="builtin">self</span>):
<span class="keyword">return</span> <span class="builtin">len</span>(<span class="builtin">self</span>._data)
<span class="keyword">def</span> <span class="function">__repr__</span>(<span class="builtin">self</span>):
<span class="keyword">return</span> <span class="string">f"Stack(</span>{<span class="builtin">self</span>._data}<span class="string">)"</span>
<span class="comment"># Usage</span>
s = <span class="function">Stack</span>()
s.<span class="function">push</span>(<span class="number">10</span>)
s.<span class="function">push</span>(<span class="number">20</span>)
s.<span class="function">push</span>(<span class="number">30</span>)
<span class="builtin">print</span>(s.<span class="function">peek</span>()) <span class="comment"># 30</span>
<span class="builtin">print</span>(s.<span class="function">pop</span>()) <span class="comment"># 30</span>
<span class="builtin">print</span>(s.<span class="function">size</span>()) <span class="comment"># 2</span>
<span class="builtin">print</span>(s.<span class="function">is_empty</span>()) <span class="comment"># False</span></code></pre>
<h3>Full Stack Class: JavaScript</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="function">Stack</span> {
<span class="function">constructor</span>() {
<span class="keyword">this</span>._data = [];
}
<span class="function">push</span>(val) {
<span class="keyword">this</span>._data.<span class="function">push</span>(val);
}
<span class="function">pop</span>() {
<span class="keyword">if</span> (<span class="keyword">this</span>.<span class="function">isEmpty</span>()) {
<span class="keyword">throw</span> <span class="keyword">new</span> <span class="builtin">Error</span>(<span class="string">"pop from empty stack"</span>);
}
<span class="keyword">return</span> <span class="keyword">this</span>._data.<span class="function">pop</span>();
}
<span class="function">peek</span>() {
<span class="keyword">if</span> (<span class="keyword">this</span>.<span class="function">isEmpty</span>()) {
<span class="keyword">throw</span> <span class="keyword">new</span> <span class="builtin">Error</span>(<span class="string">"peek from empty stack"</span>);
}
<span class="keyword">return</span> <span class="keyword">this</span>._data[<span class="keyword">this</span>._data.length - <span class="number">1</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">size</span>() {
<span class="keyword">return</span> <span class="keyword">this</span>._data.length;
}
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> s = <span class="keyword">new</span> <span class="function">Stack</span>();
s.<span class="function">push</span>(<span class="number">10</span>);
s.<span class="function">push</span>(<span class="number">20</span>);
s.<span class="function">push</span>(<span class="number">30</span>);
console.<span class="function">log</span>(s.<span class="function">peek</span>()); <span class="comment">// 30</span>
console.<span class="function">log</span>(s.<span class="function">pop</span>()); <span class="comment">// 30</span>
console.<span class="function">log</span>(s.<span class="function">size</span>()); <span class="comment">// 2</span>
console.<span class="function">log</span>(s.<span class="function">isEmpty</span>()); <span class="comment">// false</span></code></pre>
</section>
<!-- ============================================ -->
<!-- SECTION 3: COMMON STACK PROBLEMS -->
<!-- ============================================ -->
<section id="stack-problems">
<h2>3. Common Stack Problems</h2>
<!-- Valid Parentheses -->
<h3>Problem 1: Valid Parentheses</h3>
<p>
Given a string containing just the characters <code>(</code>, <code>)</code>, <code>{</code>, <code>}</code>, <code>[</code>, and <code>]</code>, determine if the input string is valid. An input string is valid if every open bracket is closed by the same type, and in the correct order.
</p>
<div class="example-box">
<div class="label">Approach</div>
<p>
Use a stack. For every opening bracket, push it. For every closing bracket, check that the stack is not empty and that the top of the stack is the matching opening bracket. If it does not match or the stack is empty, return false. At the end, the stack must be empty.
</p>
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">isValid</span>(s: <span class="builtin">str</span>) -> <span class="builtin">bool</span>:
stack = []
pairs = {<span class="string">')'</span>: <span class="string">'('</span>, <span class="string">'}'</span>: <span class="string">'{'</span>, <span class="string">']'</span>: <span class="string">'['</span>}
<span class="keyword">for</span> char <span class="keyword">in</span> s:
<span class="keyword">if</span> char <span class="keyword">in</span> pairs:
<span class="comment"># Closing bracket -- check the top of stack</span>
<span class="keyword">if</span> <span class="keyword">not</span> stack <span class="keyword">or</span> stack[<span class="number">-1</span>] != pairs[char]:
<span class="keyword">return</span> <span class="keyword">False</span>
stack.<span class="function">pop</span>()
<span class="keyword">else</span>:
<span class="comment"># Opening bracket -- push onto stack</span>
stack.<span class="function">append</span>(char)
<span class="keyword">return</span> <span class="builtin">len</span>(stack) == <span class="number">0</span>
<span class="comment"># Examples</span>
<span class="builtin">print</span>(<span class="function">isValid</span>(<span class="string">"()"</span>)) <span class="comment"># True</span>
<span class="builtin">print</span>(<span class="function">isValid</span>(<span class="string">"()[]{}"</span>)) <span class="comment"># True</span>
<span class="builtin">print</span>(<span class="function">isValid</span>(<span class="string">"(]"</span>)) <span class="comment"># False</span>
<span class="builtin">print</span>(<span class="function">isValid</span>(<span class="string">"([)]"</span>)) <span class="comment"># False</span>
<span class="builtin">print</span>(<span class="function">isValid</span>(<span class="string">"{[]}"</span>)) <span class="comment"># True</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">isValid</span>(s) {
<span class="keyword">const</span> stack = [];
<span class="keyword">const</span> pairs = { <span class="string">')'</span>: <span class="string">'('</span>, <span class="string">'}'</span>: <span class="string">'{'</span>, <span class="string">']'</span>: <span class="string">'['</span> };
<span class="keyword">for</span> (<span class="keyword">const</span> char <span class="keyword">of</span> s) {
<span class="keyword">if</span> (pairs[char]) {
<span class="comment">// Closing bracket -- check the top of stack</span>
<span class="keyword">if</span> (!stack.length || stack[stack.length - <span class="number">1</span>] !== pairs[char]) {
<span class="keyword">return</span> <span class="keyword">false</span>;
}
stack.<span class="function">pop</span>();
} <span class="keyword">else</span> {
<span class="comment">// Opening bracket -- push onto stack</span>
stack.<span class="function">push</span>(char);
}
}
<span class="keyword">return</span> stack.length === <span class="number">0</span>;
}
<span class="comment">// Examples</span>
console.<span class="function">log</span>(<span class="function">isValid</span>(<span class="string">"()"</span>)); <span class="comment">// true</span>
console.<span class="function">log</span>(<span class="function">isValid</span>(<span class="string">"()[]{}"</span>)); <span class="comment">// true</span>
console.<span class="function">log</span>(<span class="function">isValid</span>(<span class="string">"(]"</span>)); <span class="comment">// false</span>
console.<span class="function">log</span>(<span class="function">isValid</span>(<span class="string">"([)]"</span>)); <span class="comment">// false</span>
console.<span class="function">log</span>(<span class="function">isValid</span>(<span class="string">"{[]}"</span>)); <span class="comment">// true</span></code></pre>
<div class="tip-box">
<div class="label">Complexity</div>
<p><strong>Time:</strong> O(n) -- single pass through the string. <strong>Space:</strong> O(n) -- worst case the entire string is opening brackets.</p>
</div>
<!-- Min Stack -->
<h3>Problem 2: Min Stack</h3>
<p>
Design a stack that supports <code>push</code>, <code>pop</code>, <code>top</code>, and retrieving the minimum element -- all in O(1) time.
</p>
<div class="example-box">
<div class="label">Approach</div>
<p>
Maintain two stacks: the main stack and a <strong>min stack</strong>. Whenever you push, also push the current minimum onto the min stack. When you pop, pop from both. The top of the min stack always holds the current minimum.
</p>
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">MinStack</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(<span class="builtin">self</span>):
<span class="builtin">self</span>.stack = []
<span class="builtin">self</span>.min_stack = []
<span class="keyword">def</span> <span class="function">push</span>(<span class="builtin">self</span>, val: <span class="builtin">int</span>) -> <span class="keyword">None</span>:
<span class="builtin">self</span>.stack.<span class="function">append</span>(val)
<span class="comment"># Push the new minimum onto min_stack</span>
current_min = <span class="builtin">min</span>(val, <span class="builtin">self</span>.min_stack[<span class="number">-1</span>] <span class="keyword">if</span> <span class="builtin">self</span>.min_stack <span class="keyword">else</span> <span class="builtin">float</span>(<span class="string">'inf'</span>))
<span class="builtin">self</span>.min_stack.<span class="function">append</span>(current_min)
<span class="keyword">def</span> <span class="function">pop</span>(<span class="builtin">self</span>) -> <span class="keyword">None</span>:
<span class="builtin">self</span>.stack.<span class="function">pop</span>()
<span class="builtin">self</span>.min_stack.<span class="function">pop</span>()
<span class="keyword">def</span> <span class="function">top</span>(<span class="builtin">self</span>) -> <span class="builtin">int</span>:
<span class="keyword">return</span> <span class="builtin">self</span>.stack[<span class="number">-1</span>]
<span class="keyword">def</span> <span class="function">getMin</span>(<span class="builtin">self</span>) -> <span class="builtin">int</span>:
<span class="keyword">return</span> <span class="builtin">self</span>.min_stack[<span class="number">-1</span>]
<span class="comment"># Usage</span>
ms = <span class="function">MinStack</span>()
ms.<span class="function">push</span>(<span class="number">-2</span>)
ms.<span class="function">push</span>(<span class="number">0</span>)
ms.<span class="function">push</span>(<span class="number">-3</span>)
<span class="builtin">print</span>(ms.<span class="function">getMin</span>()) <span class="comment"># -3</span>
ms.<span class="function">pop</span>()
<span class="builtin">print</span>(ms.<span class="function">top</span>()) <span class="comment"># 0</span>
<span class="builtin">print</span>(ms.<span class="function">getMin</span>()) <span class="comment"># -2</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="function">MinStack</span> {
<span class="function">constructor</span>() {
<span class="keyword">this</span>.stack = [];
<span class="keyword">this</span>.minStack = [];
}
<span class="function">push</span>(val) {
<span class="keyword">this</span>.stack.<span class="function">push</span>(val);
<span class="keyword">const</span> currentMin = <span class="keyword">this</span>.minStack.length
? Math.<span class="function">min</span>(val, <span class="keyword">this</span>.minStack[<span class="keyword">this</span>.minStack.length - <span class="number">1</span>])
: val;
<span class="keyword">this</span>.minStack.<span class="function">push</span>(currentMin);
}
<span class="function">pop</span>() {
<span class="keyword">this</span>.stack.<span class="function">pop</span>();
<span class="keyword">this</span>.minStack.<span class="function">pop</span>();
}
<span class="function">top</span>() {
<span class="keyword">return</span> <span class="keyword">this</span>.stack[<span class="keyword">this</span>.stack.length - <span class="number">1</span>];
}
<span class="function">getMin</span>() {
<span class="keyword">return</span> <span class="keyword">this</span>.minStack[<span class="keyword">this</span>.minStack.length - <span class="number">1</span>];
}
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> ms = <span class="keyword">new</span> <span class="function">MinStack</span>();
ms.<span class="function">push</span>(<span class="number">-2</span>);
ms.<span class="function">push</span>(<span class="number">0</span>);
ms.<span class="function">push</span>(<span class="number">-3</span>);
console.<span class="function">log</span>(ms.<span class="function">getMin</span>()); <span class="comment">// -3</span>
ms.<span class="function">pop</span>();
console.<span class="function">log</span>(ms.<span class="function">top</span>()); <span class="comment">// 0</span>
console.<span class="function">log</span>(ms.<span class="function">getMin</span>()); <span class="comment">// -2</span></code></pre>
<!-- Evaluate Reverse Polish Notation -->
<h3>Problem 3: Evaluate Reverse Polish Notation</h3>
<p>
Evaluate an expression in Reverse Polish Notation (postfix). Valid operators are <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>. Each operand may be an integer or another expression. Division truncates toward zero.
</p>
<div class="example-box">
<div class="label">Approach</div>
<p>
Iterate through the tokens. If the token is a number, push it onto the stack. If it is an operator, pop two operands, apply the operator (second popped is the left operand), and push the result back. At the end, the stack holds the final answer.
</p>
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">evalRPN</span>(tokens: <span class="builtin">list</span>[<span class="builtin">str</span>]) -> <span class="builtin">int</span>:
stack = []
<span class="keyword">for</span> token <span class="keyword">in</span> tokens:
<span class="keyword">if</span> token <span class="keyword">in</span> {<span class="string">'+'</span>, <span class="string">'-'</span>, <span class="string">'*'</span>, <span class="string">'/'</span>}:
b = stack.<span class="function">pop</span>() <span class="comment"># right operand</span>
a = stack.<span class="function">pop</span>() <span class="comment"># left operand</span>
<span class="keyword">if</span> token == <span class="string">'+'</span>:
stack.<span class="function">append</span>(a + b)
<span class="keyword">elif</span> token == <span class="string">'-'</span>:
stack.<span class="function">append</span>(a - b)
<span class="keyword">elif</span> token == <span class="string">'*'</span>:
stack.<span class="function">append</span>(a * b)
<span class="keyword">else</span>:
<span class="comment"># Truncate toward zero (not floor division)</span>
stack.<span class="function">append</span>(<span class="builtin">int</span>(a / b))
<span class="keyword">else</span>:
stack.<span class="function">append</span>(<span class="builtin">int</span>(token))
<span class="keyword">return</span> stack[<span class="number">0</span>]
<span class="comment"># Example: ["2","1","+","3","*"] = ((2 + 1) * 3) = 9</span>
<span class="builtin">print</span>(<span class="function">evalRPN</span>([<span class="string">"2"</span>,<span class="string">"1"</span>,<span class="string">"+"</span>,<span class="string">"3"</span>,<span class="string">"*"</span>])) <span class="comment"># 9</span>
<span class="comment"># Example: ["4","13","5","/","+"] = (4 + (13 / 5)) = 6</span>
<span class="builtin">print</span>(<span class="function">evalRPN</span>([<span class="string">"4"</span>,<span class="string">"13"</span>,<span class="string">"5"</span>,<span class="string">"/"</span>,<span class="string">"+"</span>])) <span class="comment"># 6</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">evalRPN</span>(tokens) {
<span class="keyword">const</span> stack = [];
<span class="keyword">for</span> (<span class="keyword">const</span> token <span class="keyword">of</span> tokens) {
<span class="keyword">if</span> ([<span class="string">"+"</span>, <span class="string">"-"</span>, <span class="string">"*"</span>, <span class="string">"/"</span>].<span class="function">includes</span>(token)) {
<span class="keyword">const</span> b = stack.<span class="function">pop</span>(); <span class="comment">// right operand</span>
<span class="keyword">const</span> a = stack.<span class="function">pop</span>(); <span class="comment">// left operand</span>
<span class="keyword">switch</span> (token) {
<span class="keyword">case</span> <span class="string">"+"</span>: stack.<span class="function">push</span>(a + b); <span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">"-"</span>: stack.<span class="function">push</span>(a - b); <span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">"*"</span>: stack.<span class="function">push</span>(a * b); <span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">"/"</span>: stack.<span class="function">push</span>(Math.<span class="function">trunc</span>(a / b)); <span class="keyword">break</span>;
}
} <span class="keyword">else</span> {
stack.<span class="function">push</span>(Number(token));
}
}
<span class="keyword">return</span> stack[<span class="number">0</span>];
}
<span class="comment">// Example</span>
console.<span class="function">log</span>(<span class="function">evalRPN</span>([<span class="string">"2"</span>,<span class="string">"1"</span>,<span class="string">"+"</span>,<span class="string">"3"</span>,<span class="string">"*"</span>])); <span class="comment">// 9</span></code></pre>
</section>
<!-- ============================================ -->
<!-- SECTION 4: QUEUES -->
<!-- ============================================ -->
<section id="queues">
<h2>4. Queues (FIFO - First In, First Out)</h2>
<p>
A <strong>queue</strong> is a linear data structure that follows the <strong>FIFO</strong> principle: the first element added is the first one removed. Think of a line at a store -- the first person in line gets served first.
</p>
<div class="formula-box"> front → [1] [2] [3] ← back
dequeue enqueue</div>
<p>Every queue supports these core operations, all in <strong>O(1)</strong> time:</p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Description</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr><td><code>enqueue(x)</code></td><td>Add element <code>x</code> to the back</td><td>O(1)</td></tr>
<tr><td><code>dequeue()</code></td><td>Remove and return the front element</td><td>O(1)</td></tr>
<tr><td><code>front()</code> / <code>peek()</code></td><td>Return the front element without removing it</td><td>O(1)</td></tr>
<tr><td><code>isEmpty()</code></td><td>Check if the queue is empty</td><td>O(1)</td></tr>
<tr><td><code>size()</code></td><td>Return the number of elements</td><td>O(1)</td></tr>
</tbody>
</table>
<div class="example-box">
<div class="label">Analogy</div>
<p>
A queue is like a line at a grocery store. The first customer in line is the first to be served. New customers join at the back. Nobody cuts the line -- that is the FIFO guarantee.
</p>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 5: QUEUE IMPLEMENTATIONS -->
<!-- ============================================ -->
<section id="queue-impl">
<h2>5. Queue Implementations</h2>
<div class="warning-box">
<div class="label">Warning</div>
<p>In Python, do NOT use <code>list.pop(0)</code> as a dequeue operation. Removing from the front of a list is <strong>O(n)</strong> because every remaining element must shift left. Always use <code>collections.deque</code> for queues.</p>
</div>
<h3>Python: Using collections.deque</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> deque
queue = <span class="function">deque</span>()
queue.<span class="function">append</span>(<span class="number">1</span>) <span class="comment"># enqueue 1</span>
queue.<span class="function">append</span>(<span class="number">2</span>) <span class="comment"># enqueue 2</span>
queue.<span class="function">append</span>(<span class="number">3</span>) <span class="comment"># enqueue 3</span>
<span class="builtin">print</span>(queue[<span class="number">0</span>]) <span class="comment"># front/peek: 1</span>
<span class="builtin">print</span>(queue.<span class="function">popleft</span>()) <span class="comment"># dequeue: 1 (O(1)!)</span>
<span class="builtin">print</span>(queue) <span class="comment"># deque([2, 3])</span>
<span class="builtin">print</span>(<span class="builtin">len</span>(queue)) <span class="comment"># size: 2</span></code></pre>
<h3>JavaScript: Using an Array</h3>
<p>JavaScript arrays do not have a built-in O(1) dequeue. <code>shift()</code> is O(n) but works fine for small inputs. For performance-critical code, use a linked-list based queue.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Simple queue with array (shift is O(n) but fine for small sizes)</span>
<span class="keyword">const</span> queue = [];
queue.<span class="function">push</span>(<span class="number">1</span>); <span class="comment">// enqueue 1</span>
queue.<span class="function">push</span>(<span class="number">2</span>); <span class="comment">// enqueue 2</span>
queue.<span class="function">push</span>(<span class="number">3</span>); <span class="comment">// enqueue 3</span>
console.<span class="function">log</span>(queue[<span class="number">0</span>]); <span class="comment">// front: 1</span>
console.<span class="function">log</span>(queue.<span class="function">shift</span>()); <span class="comment">// dequeue: 1 (O(n))</span>
console.<span class="function">log</span>(queue); <span class="comment">// [2, 3]</span>
console.<span class="function">log</span>(queue.length); <span class="comment">// 2</span></code></pre>
<h3>Full Queue Class: Python</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> deque
<span class="keyword">class</span> <span class="function">Queue</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(<span class="builtin">self</span>):
<span class="builtin">self</span>._data = <span class="function">deque</span>()
<span class="keyword">def</span> <span class="function">enqueue</span>(<span class="builtin">self</span>, val):
<span class="builtin">self</span>._data.<span class="function">append</span>(val)
<span class="keyword">def</span> <span class="function">dequeue</span>(<span class="builtin">self</span>):
<span class="keyword">if</span> <span class="builtin">self</span>.<span class="function">is_empty</span>():
<span class="keyword">raise</span> <span class="builtin">IndexError</span>(<span class="string">"dequeue from empty queue"</span>)
<span class="keyword">return</span> <span class="builtin">self</span>._data.<span class="function">popleft</span>()
<span class="keyword">def</span> <span class="function">front</span>(<span class="builtin">self</span>):
<span class="keyword">if</span> <span class="builtin">self</span>.<span class="function">is_empty</span>():
<span class="keyword">raise</span> <span class="builtin">IndexError</span>(<span class="string">"front from empty queue"</span>)
<span class="keyword">return</span> <span class="builtin">self</span>._data[<span class="number">0</span>]
<span class="keyword">def</span> <span class="function">is_empty</span>(<span class="builtin">self</span>):
<span class="keyword">return</span> <span class="builtin">len</span>(<span class="builtin">self</span>._data) == <span class="number">0</span>
<span class="keyword">def</span> <span class="function">size</span>(<span class="builtin">self</span>):
<span class="keyword">return</span> <span class="builtin">len</span>(<span class="builtin">self</span>._data)
<span class="keyword">def</span> <span class="function">__repr__</span>(<span class="builtin">self</span>):
<span class="keyword">return</span> <span class="string">f"Queue(</span>{<span class="builtin">list</span>(<span class="builtin">self</span>._data)}<span class="string">)"</span>
<span class="comment"># Usage</span>
q = <span class="function">Queue</span>()
q.<span class="function">enqueue</span>(<span class="number">10</span>)
q.<span class="function">enqueue</span>(<span class="number">20</span>)
q.<span class="function">enqueue</span>(<span class="number">30</span>)
<span class="builtin">print</span>(q.<span class="function">front</span>()) <span class="comment"># 10</span>
<span class="builtin">print</span>(q.<span class="function">dequeue</span>()) <span class="comment"># 10</span>
<span class="builtin">print</span>(q.<span class="function">size</span>()) <span class="comment"># 2</span></code></pre>
<h3>Full Queue Class: JavaScript</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="function">Queue</span> {
<span class="function">constructor</span>() {
<span class="keyword">this</span>._data = {};
<span class="keyword">this</span>._head = <span class="number">0</span>;
<span class="keyword">this</span>._tail = <span class="number">0</span>;
}
<span class="function">enqueue</span>(val) {
<span class="keyword">this</span>._data[<span class="keyword">this</span>._tail] = val;
<span class="keyword">this</span>._tail++;
}
<span class="function">dequeue</span>() {
<span class="keyword">if</span> (<span class="keyword">this</span>.<span class="function">isEmpty</span>()) {
<span class="keyword">throw</span> <span class="keyword">new</span> <span class="builtin">Error</span>(<span class="string">"dequeue from empty queue"</span>);
}
<span class="keyword">const</span> val = <span class="keyword">this</span>._data[<span class="keyword">this</span>._head];
<span class="keyword">delete</span> <span class="keyword">this</span>._data[<span class="keyword">this</span>._head];
<span class="keyword">this</span>._head++;
<span class="keyword">return</span> val;
}
<span class="function">front</span>() {
<span class="keyword">if</span> (<span class="keyword">this</span>.<span class="function">isEmpty</span>()) {
<span class="keyword">throw</span> <span class="keyword">new</span> <span class="builtin">Error</span>(<span class="string">"front from empty queue"</span>);
}
<span class="keyword">return</span> <span class="keyword">this</span>._data[<span class="keyword">this</span>._head];
}
<span class="function">isEmpty</span>() {
<span class="keyword">return</span> <span class="keyword">this</span>._tail - <span class="keyword">this</span>._head === <span class="number">0</span>;
}
<span class="function">size</span>() {
<span class="keyword">return</span> <span class="keyword">this</span>._tail - <span class="keyword">this</span>._head;
}
}
<span class="comment">// Usage -- O(1) enqueue and dequeue using object index trick</span>
<span class="keyword">const</span> q = <span class="keyword">new</span> <span class="function">Queue</span>();
q.<span class="function">enqueue</span>(<span class="number">10</span>);
q.<span class="function">enqueue</span>(<span class="number">20</span>);
q.<span class="function">enqueue</span>(<span class="number">30</span>);
console.<span class="function">log</span>(q.<span class="function">front</span>()); <span class="comment">// 10</span>
console.<span class="function">log</span>(q.<span class="function">dequeue</span>()); <span class="comment">// 10</span>
console.<span class="function">log</span>(q.<span class="function">size</span>()); <span class="comment">// 2</span></code></pre>
<div class="tip-box">
<div class="label">Why the object trick?</div>
<p>
The JS <code>Queue</code> class above uses an object with numeric keys and a head/tail pointer instead of an array. This gives true O(1) dequeue -- no shifting elements. The trade-off is slightly more code, but it is the correct approach for performance-sensitive applications.
</p>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 6: QUEUE PROBLEMS -->
<!-- ============================================ -->
<section id="queue-problems">
<h2>6. Common Queue Problems</h2>
<h3>BFS Traversal (Breadth-First Search)</h3>
<p>
Queues are the backbone of BFS. You start at a source node, enqueue it, then repeatedly dequeue a node, process it, and enqueue its unvisited neighbors. This guarantees level-by-level exploration.
</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">bfs</span>(graph, start):
visited = {start}
queue = <span class="function">deque</span>([start])
order = []
<span class="keyword">while</span> queue:
node = queue.<span class="function">popleft</span>()
order.<span class="function">append</span>(node)
<span class="keyword">for</span> neighbor <span class="keyword">in</span> graph[node]:
<span class="keyword">if</span> neighbor <span class="keyword">not</span> <span class="keyword">in</span> visited:
visited.<span class="function">add</span>(neighbor)
queue.<span class="function">append</span>(neighbor)
<span class="keyword">return</span> order
<span class="comment"># Example graph (adjacency list)</span>
graph = {
<span class="string">'A'</span>: [<span class="string">'B'</span>, <span class="string">'C'</span>],
<span class="string">'B'</span>: [<span class="string">'A'</span>, <span class="string">'D'</span>, <span class="string">'E'</span>],
<span class="string">'C'</span>: [<span class="string">'A'</span>, <span class="string">'F'</span>],
<span class="string">'D'</span>: [<span class="string">'B'</span>],
<span class="string">'E'</span>: [<span class="string">'B'</span>, <span class="string">'F'</span>],
<span class="string">'F'</span>: [<span class="string">'C'</span>, <span class="string">'E'</span>],
}
<span class="builtin">print</span>(<span class="function">bfs</span>(graph, <span class="string">'A'</span>)) <span class="comment"># ['A', 'B', 'C', 'D', 'E', 'F']</span></code></pre>
<div class="tip-box">
<div class="label">Deep Dive</div>
<p>BFS is covered in depth on the <a href="trees.html" class="resource-link">Trees</a> and <a href="graphs.html" class="resource-link">Graphs</a> pages. The key takeaway here: <strong>BFS uses a queue, DFS uses a stack.</strong></p>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 7: DEQUE -->
<!-- ============================================ -->
<section id="deque">
<h2>7. Deque (Double-Ended Queue)</h2>
<p>
A <strong>deque</strong> (pronounced "deck") allows insertion and removal from <strong>both ends</strong> in O(1). It combines the powers of a stack and a queue.
</p>
<div class="formula-box"> ← pop_front / push_front [1] [2] [3] push_back / pop_back →</div>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Description</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr><td><code>push_front(x)</code></td><td>Add to the front</td><td>O(1)</td></tr>
<tr><td><code>push_back(x)</code></td><td>Add to the back</td><td>O(1)</td></tr>
<tr><td><code>pop_front()</code></td><td>Remove from the front</td><td>O(1)</td></tr>
<tr><td><code>pop_back()</code></td><td>Remove from the back</td><td>O(1)</td></tr>
<tr><td><code>front()</code> / <code>back()</code></td><td>Peek at either end</td><td>O(1)</td></tr>
</tbody>
</table>
<h3>Python: collections.deque</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> deque
dq = <span class="function">deque</span>()
dq.<span class="function">append</span>(<span class="number">2</span>) <span class="comment"># push_back: [2]</span>
dq.<span class="function">append</span>(<span class="number">3</span>) <span class="comment"># push_back: [2, 3]</span>
dq.<span class="function">appendleft</span>(<span class="number">1</span>) <span class="comment"># push_front: [1, 2, 3]</span>
<span class="builtin">print</span>(dq[<span class="number">0</span>]) <span class="comment"># front: 1</span>
<span class="builtin">print</span>(dq[<span class="number">-1</span>]) <span class="comment"># back: 3</span>
<span class="builtin">print</span>(dq.<span class="function">popleft</span>()) <span class="comment"># pop_front: 1 -> [2, 3]</span>
<span class="builtin">print</span>(dq.<span class="function">pop</span>()) <span class="comment"># pop_back: 3 -> [2]</span></code></pre>
<h3>JavaScript: Array or Custom Implementation</h3>
<p>JavaScript does not have a built-in deque. You can use an array (with <code>unshift</code>/<code>shift</code> being O(n)) or implement with a doubly linked list for O(1) on both ends.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Simple deque using array (unshift/shift are O(n))</span>
<span class="keyword">const</span> dq = [];
dq.<span class="function">push</span>(<span class="number">2</span>); <span class="comment">// push_back: [2]</span>
dq.<span class="function">push</span>(<span class="number">3</span>); <span class="comment">// push_back: [2, 3]</span>
dq.<span class="function">unshift</span>(<span class="number">1</span>); <span class="comment">// push_front: [1, 2, 3] (O(n))</span>
console.<span class="function">log</span>(dq[<span class="number">0</span>]); <span class="comment">// front: 1</span>
console.<span class="function">log</span>(dq[dq.length - <span class="number">1</span>]); <span class="comment">// back: 3</span>
console.<span class="function">log</span>(dq.<span class="function">shift</span>()); <span class="comment">// pop_front: 1 (O(n))</span>
console.<span class="function">log</span>(dq.<span class="function">pop</span>()); <span class="comment">// pop_back: 3</span></code></pre>
<h3>When to Use a Deque</h3>
<p>The classic use case is the <strong>Sliding Window Maximum</strong> problem. You maintain a monotonic deque where the front always holds the index of the current window's maximum. As the window slides, you pop from both ends to maintain the invariant.</p>
<div class="tip-box">
<div class="label">Interview Pattern</div>
<p>Whenever you see "sliding window" combined with "maximum" or "minimum," think <strong>monotonic deque</strong>. This pattern appears in problems like Sliding Window Maximum (LC 239) and Shortest Subarray with Sum at Least K (LC 862).</p>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 8: PRIORITY QUEUE -->
<!-- ============================================ -->
<section id="priority-queue">
<h2>8. Priority Queue / Heap (Brief Intro)</h2>
<p>
A <strong>priority queue</strong> is not technically a queue -- it does not follow FIFO. Instead, elements are dequeued in <strong>priority order</strong> (smallest or largest first). Under the hood, it is typically implemented as a <strong>binary heap</strong>.
</p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr><td>Insert</td><td>O(log n)</td></tr>
<tr><td>Extract min/max</td><td>O(log n)</td></tr>
<tr><td>Peek min/max</td><td>O(1)</td></tr>
</tbody>
</table>
<h3>Python: heapq Module</h3>
<p>Python's <code>heapq</code> provides a min-heap. To get a max-heap, negate the values.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> heapq
<span class="comment"># Min-heap</span>
heap = []
heapq.<span class="function">heappush</span>(heap, <span class="number">3</span>)
heapq.<span class="function">heappush</span>(heap, <span class="number">1</span>)
heapq.<span class="function">heappush</span>(heap, <span class="number">2</span>)
<span class="builtin">print</span>(heap[<span class="number">0</span>]) <span class="comment"># peek min: 1</span>
<span class="builtin">print</span>(heapq.<span class="function">heappop</span>(heap)) <span class="comment"># extract min: 1</span>
<span class="builtin">print</span>(heapq.<span class="function">heappop</span>(heap)) <span class="comment"># extract min: 2</span>
<span class="comment"># Max-heap trick: negate values</span>
max_heap = []
heapq.<span class="function">heappush</span>(max_heap, <span class="number">-3</span>)
heapq.<span class="function">heappush</span>(max_heap, <span class="number">-1</span>)
heapq.<span class="function">heappush</span>(max_heap, <span class="number">-2</span>)
<span class="builtin">print</span>(-heapq.<span class="function">heappop</span>(max_heap)) <span class="comment"># extract max: 3</span></code></pre>
<div class="tip-box">
<div class="label">Full Coverage</div>
<p>Heaps, priority queues, and heap sort are covered in depth on the <a href="advanced.html" class="resource-link">Advanced</a> page. This section is just to show you the concept and API.</p>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 9: TIME COMPLEXITY TABLE -->
<!-- ============================================ -->
<section id="complexity">
<h2>9. Time Complexity Comparison</h2>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Stack</th>
<th>Queue</th>
<th>Deque</th>
</tr>
</thead>
<tbody>
<tr>
<td>Push / Enqueue</td>
<td>O(1)</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Pop / Dequeue</td>
<td>O(1)</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Peek / Front</td>
<td>O(1)</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Search</td>
<td>O(n)</td>
<td>O(n)</td>
<td>O(n)</td>
</tr>
<tr>
<td>isEmpty</td>
<td>O(1)</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr>
<td>Size</td>
<td>O(1)</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
</tbody>
</table>
<div class="tip-box">
<div class="label">Key Takeaway</div>
<p>Stacks, queues, and deques all give you O(1) for their primary operations. The only O(n) operation is searching -- which you rarely need to do. If you are searching a stack or queue, you probably need a different data structure (like a hash set).</p>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 10: REAL-WORLD APPLICATIONS -->
<!-- ============================================ -->
<section id="applications">
<h2>10. Real-World Applications</h2>
<h3>Stack Applications</h3>
<ul>
<li><strong>Undo/Redo</strong> -- Text editors push each action onto a stack. Undo pops the last action; redo pops from a separate stack.</li>
<li><strong>Browser Back Button</strong> -- Each page you visit is pushed onto a stack. Clicking back pops the current page and shows the previous one.</li>
<li><strong>Call Stack</strong> -- When a function calls another function, the return address is pushed onto the call stack. When the function returns, the address is popped.</li>
<li><strong>DFS (Depth-First Search)</strong> -- Uses a stack (or recursion, which uses the call stack) to explore as deep as possible before backtracking.</li>
<li><strong>Expression Parsing</strong> -- Compilers use stacks to evaluate arithmetic expressions, convert infix to postfix, and match brackets.</li>
</ul>
<h3>Queue Applications</h3>
<ul>
<li><strong>BFS (Breadth-First Search)</strong> -- Uses a queue to explore nodes level by level, finding shortest paths in unweighted graphs.</li>
<li><strong>Task Scheduling</strong> -- Operating systems use queues to schedule processes (FIFO scheduling, round-robin with time slices).</li>
<li><strong>Print Queue</strong> -- Documents sent to a printer are processed in the order they arrive.</li>
<li><strong>Message Queues</strong> -- Systems like RabbitMQ and Kafka use queues to decouple producers from consumers in distributed systems.</li>
<li><strong>Web Server Request Handling</strong> -- Incoming HTTP requests are queued and processed in order.</li>
</ul>
<h3>Deque Applications</h3>
<ul>
<li><strong>Sliding Window Problems</strong> -- Maintaining a monotonic deque for efficient window maximum/minimum queries.</li>
<li><strong>Work Stealing</strong> -- In parallel computing, threads steal tasks from the back of other threads' deques.</li>
<li><strong>Palindrome Checking</strong> -- Compare characters from both ends simultaneously.</li>
</ul>
</section>
<!-- ============================================ -->
<!-- SECTION 11: LEETCODE PROBLEMS -->