-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhashmaps.html
More file actions
1258 lines (1033 loc) · 68.3 KB
/
hashmaps.html
File metadata and controls
1258 lines (1033 loc) · 68.3 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>Hash Maps & Sets | 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> / Hash Maps & Sets</div>
<h1>Hash Maps & Sets</h1>
<p>Master the most versatile data structure in coding interviews — O(1) lookups, frequency counting, complement patterns, and more.</p>
</div>
<!-- ===== TABLE OF CONTENTS ===== -->
<div class="toc">
<h4>Table of Contents</h4>
<a href="#what-is-hashmap">1. What is a Hash Map?</a>
<a href="#time-complexity">2. Time Complexity</a>
<a href="#hashmaps-python-js">3. Hash Maps in Python and JS</a>
<a href="#hash-sets">4. Hash Sets</a>
<a href="#common-patterns">5. Common Hash Map Patterns</a>
<a href="#when-to-use">6. When to Use Hash Maps</a>
<a href="#leetcode-problems">7. LeetCode Problems</a>
<a href="#implement-from-scratch">8. Implementing a Hash Map from Scratch</a>
<a href="#quiz">9. Practice Quiz</a>
</div>
<!-- ================================================================== -->
<!-- SECTION 1 : WHAT IS A HASH MAP? -->
<!-- ================================================================== -->
<section id="what-is-hashmap">
<h2>1. What is a Hash Map?</h2>
<p>A <strong>hash map</strong> (also called a <strong>hash table</strong>) is a data structure that stores <strong>key-value pairs</strong>. It allows you to associate a value with a unique key and retrieve that value later in near-constant time.</p>
<div class="tip-box">
<div class="label">Different names, same idea</div>
<ul>
<li><strong>Python</strong> — <code>dict</code> (dictionary)</li>
<li><strong>JavaScript</strong> — plain <code>Object</code> or <code>Map</code></li>
<li><strong>Java</strong> — <code>HashMap</code></li>
<li><strong>C++</strong> — <code>unordered_map</code></li>
<li><strong>General CS</strong> — hash table, associative array</li>
</ul>
</div>
<h3>How Hashing Works</h3>
<p>Under the hood a hash map is backed by an <strong>array</strong>. When you insert a key, a <strong>hash function</strong> converts the key into an integer, and that integer is mapped to an index in the array (usually via modulo). The value is then stored at that index.</p>
<div class="formula-box">
index = hash(key) % array_length
</div>
<div class="example-box">
<div class="label">Step-by-step example</div>
<p>Suppose our internal array has 8 slots and we want to store <code>"alice" -> 90</code>.</p>
<ol>
<li>Compute hash: <code>hash("alice")</code> returns, say, <code>7572839183</code></li>
<li>Find index: <code>7572839183 % 8 = 7</code></li>
<li>Store the pair <code>("alice", 90)</code> at slot 7</li>
</ol>
<p>Later, to look up <code>"alice"</code>, we repeat the same hash and go directly to slot 7 — <strong>O(1)</strong>.</p>
</div>
<h3>Visual Representation</h3>
<pre><code><span class="comment">/* Hash Table with 8 buckets */</span>
Key hash(key) % 8 Bucket
------- -------------- ----------------------------
"alice" 7 [0] ->
"bob" 3 [1] ->
"charlie" 1 [2] ->
"diana" 3 (collision!) [3] -> ("bob",85) -> ("diana",92)
"eve" 5 [4] ->
[5] -> ("eve",78)
[6] ->
[7] -> ("alice",90)
Bucket 1: ("charlie", 88)
Bucket 3: ("bob", 85) -> ("diana", 92) <span class="comment">// chained</span></code></pre>
<h3>Collision Handling</h3>
<p>A <strong>collision</strong> occurs when two different keys hash to the same index. There are two main strategies for resolving collisions:</p>
<h3>1. Chaining (Separate Chaining)</h3>
<p>Each bucket holds a <strong>linked list</strong> (or another collection). When a collision happens, the new key-value pair is appended to the list at that bucket.</p>
<ul>
<li><strong>Pros:</strong> Simple to implement. Never "runs out" of space.</li>
<li><strong>Cons:</strong> Uses extra memory for pointers. If many keys hash to the same bucket, lookups degrade to O(n).</li>
</ul>
<pre><code><span class="comment"># Chaining: bucket 3 has two entries</span>
bucket[3] -> [("bob", 85)] -> [("diana", 92)] -> None</code></pre>
<h3>2. Open Addressing (Linear Probing)</h3>
<p>All entries live directly in the array. When a collision occurs, the algorithm <strong>probes</strong> forward to the next empty slot.</p>
<ul>
<li><strong>Pros:</strong> Better cache performance (everything in one array). No extra memory for pointers.</li>
<li><strong>Cons:</strong> Clustering can degrade performance. The table needs to be resized before it gets too full (load factor).</li>
</ul>
<pre><code><span class="comment"># Open Addressing: "diana" finds slot 3 taken, probes to slot 4</span>
[0] [1] charlie [2] [3] bob [4] diana [5] eve [6] [7] alice</code></pre>
<div class="warning-box">
<div class="label">Load Factor</div>
<p>The <strong>load factor</strong> = (number of entries) / (number of buckets). When it exceeds a threshold (often 0.75), the hash map <strong>resizes</strong> (typically doubles) and rehashes all entries. This keeps operations near O(1) on average.</p>
</div>
</section>
<!-- ================================================================== -->
<!-- SECTION 2 : TIME COMPLEXITY -->
<!-- ================================================================== -->
<section id="time-complexity">
<h2>2. Time Complexity</h2>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Average</th>
<th>Worst Case</th>
</tr>
</thead>
<tbody>
<tr><td>Insert</td><td><strong>O(1)</strong></td><td>O(n)</td></tr>
<tr><td>Lookup</td><td><strong>O(1)</strong></td><td>O(n)</td></tr>
<tr><td>Delete</td><td><strong>O(1)</strong></td><td>O(n)</td></tr>
<tr><td>Space</td><td><strong>O(n)</strong></td><td>O(n)</td></tr>
</tbody>
</table>
<h3>Why Worst Case is O(n)</h3>
<p>If every single key hashes to the <strong>same bucket</strong>, the hash map degrades into a linked list. Every lookup would need to traverse all <em>n</em> elements — hence O(n).</p>
<div class="example-box">
<div class="label">Worst-case scenario</div>
<pre><code><span class="comment"># All keys hash to bucket 0:</span>
bucket[0] -> ("a", 1) -> ("b", 2) -> ("c", 3) -> ... -> ("z", 26)
<span class="comment"># Looking up "z" requires traversing all 26 entries</span></code></pre>
</div>
<h3>Why We Usually Say O(1)</h3>
<p>In practice, a good hash function distributes keys <strong>uniformly</strong> across buckets. With a reasonable load factor, the expected number of items per bucket is a small constant. This is called <strong>amortized O(1)</strong> — on average, each operation takes constant time.</p>
<div class="formula-box">
Average time per operation = O(1 + load_factor) = O(1) when load_factor is bounded
</div>
<div class="tip-box">
<div class="label">Interview tip</div>
<p>For coding interviews, always state hash map operations as <strong>O(1) average, O(n) worst case</strong>. Most interviewers accept O(1) unless they specifically ask about worst case.</p>
</div>
</section>
<!-- ================================================================== -->
<!-- SECTION 3 : HASH MAPS IN PYTHON AND JS -->
<!-- ================================================================== -->
<section id="hashmaps-python-js">
<h2>3. Hash Maps in Python and JS</h2>
<!-- ---- PYTHON ---- -->
<h3>Python: <code>dict</code></h3>
<pre><code><span class="lang-label">Python</span>
<span class="comment"># --- Creating ---</span>
d = {} <span class="comment"># empty dict</span>
d = {<span class="string">"name"</span>: <span class="string">"Alice"</span>, <span class="string">"age"</span>: <span class="number">25</span>} <span class="comment"># with initial values</span>
d = dict(name=<span class="string">"Alice"</span>, age=<span class="number">25</span>) <span class="comment"># using dict() constructor</span>
<span class="comment"># --- Accessing ---</span>
d[<span class="string">"name"</span>] <span class="comment"># "Alice" (KeyError if missing)</span>
d.get(<span class="string">"name"</span>) <span class="comment"># "Alice" (None if missing)</span>
d.get(<span class="string">"gpa"</span>, <span class="number">0.0</span>) <span class="comment"># 0.0 (default if missing)</span>
<span class="comment"># --- Inserting / Updating ---</span>
d[<span class="string">"grade"</span>] = <span class="string">"A"</span> <span class="comment"># add new key</span>
d[<span class="string">"age"</span>] = <span class="number">26</span> <span class="comment"># update existing key</span>
<span class="comment"># --- Deleting ---</span>
<span class="keyword">del</span> d[<span class="string">"grade"</span>] <span class="comment"># remove key (KeyError if missing)</span>
d.pop(<span class="string">"grade"</span>, <span class="keyword">None</span>) <span class="comment"># remove key (no error if missing)</span>
<span class="comment"># --- Checking membership ---</span>
<span class="string">"name"</span> <span class="keyword">in</span> d <span class="comment"># True</span>
<span class="string">"gpa"</span> <span class="keyword">not in</span> d <span class="comment"># True</span>
<span class="comment"># --- Iterating ---</span>
<span class="keyword">for</span> key <span class="keyword">in</span> d:
<span class="builtin">print</span>(key) <span class="comment"># "name", "age"</span>
<span class="keyword">for</span> key, value <span class="keyword">in</span> d.items():
<span class="builtin">print</span>(key, value) <span class="comment"># "name" "Alice", "age" 26</span>
<span class="keyword">for</span> val <span class="keyword">in</span> d.values():
<span class="builtin">print</span>(val) <span class="comment"># "Alice", 26</span>
<span class="keyword">for</span> key <span class="keyword">in</span> d.keys():
<span class="builtin">print</span>(key) <span class="comment"># "name", "age"</span>
<span class="comment"># --- Useful methods ---</span>
<span class="builtin">len</span>(d) <span class="comment"># 2</span>
d.update({<span class="string">"gpa"</span>: <span class="number">3.9</span>}) <span class="comment"># merge another dict</span></code></pre>
<h3>Python: <code>defaultdict</code> and <code>Counter</code></h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> defaultdict, Counter
<span class="comment"># --- defaultdict: auto-creates default values for missing keys ---</span>
freq = defaultdict(<span class="builtin">int</span>) <span class="comment"># default value is 0</span>
<span class="keyword">for</span> char <span class="keyword">in</span> <span class="string">"hello"</span>:
freq[char] += <span class="number">1</span>
<span class="comment"># freq = {'h': 1, 'e': 1, 'l': 2, 'o': 1}</span>
groups = defaultdict(<span class="builtin">list</span>) <span class="comment"># default value is []</span>
groups[<span class="string">"fruits"</span>].append(<span class="string">"apple"</span>) <span class="comment"># no need to check if key exists</span>
groups[<span class="string">"fruits"</span>].append(<span class="string">"banana"</span>)
<span class="comment"># --- Counter: count elements in one line ---</span>
count = Counter(<span class="string">"abracadabra"</span>)
<span class="comment"># Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})</span>
count.most_common(<span class="number">2</span>) <span class="comment"># [('a', 5), ('b', 2)]</span>
<span class="comment"># Counter from a list</span>
nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">3</span>]
count = Counter(nums)
<span class="comment"># Counter({3: 3, 2: 2, 1: 1})</span></code></pre>
<!-- ---- JAVASCRIPT ---- -->
<h3>JavaScript: Object vs Map</h3>
<div class="warning-box">
<div class="label">When to use Map vs Object</div>
<ul>
<li><strong>Use <code>Map</code></strong> when keys are not strings (numbers, objects, etc.), when you need to preserve insertion order, or when you frequently add/remove keys.</li>
<li><strong>Use plain <code>Object</code></strong> for simple string-keyed config, JSON-compatible data, or when you need object destructuring.</li>
</ul>
</div>
<h3>JavaScript: Object</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// --- Creating ---</span>
<span class="keyword">const</span> obj = {};
<span class="keyword">const</span> obj2 = { <span class="string">"name"</span>: <span class="string">"Alice"</span>, <span class="string">"age"</span>: <span class="number">25</span> };
<span class="comment">// --- Accessing ---</span>
obj2[<span class="string">"name"</span>]; <span class="comment">// "Alice"</span>
obj2.name; <span class="comment">// "Alice" (dot notation)</span>
<span class="comment">// --- Inserting / Updating ---</span>
obj2[<span class="string">"grade"</span>] = <span class="string">"A"</span>;
obj2.grade = <span class="string">"A"</span>;
<span class="comment">// --- Deleting ---</span>
<span class="keyword">delete</span> obj2.grade;
<span class="comment">// --- Checking ---</span>
<span class="string">"name"</span> <span class="keyword">in</span> obj2; <span class="comment">// true</span>
obj2.hasOwnProperty(<span class="string">"name"</span>); <span class="comment">// true</span>
<span class="comment">// --- Iterating ---</span>
<span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> obj2) {
<span class="builtin">console</span>.log(key, obj2[key]);
}
Object.keys(obj2); <span class="comment">// ["name", "age"]</span>
Object.values(obj2); <span class="comment">// ["Alice", 25]</span>
Object.entries(obj2); <span class="comment">// [["name","Alice"], ["age",25]]</span></code></pre>
<h3>JavaScript: Map</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// --- Creating ---</span>
<span class="keyword">const</span> map = <span class="keyword">new</span> <span class="builtin">Map</span>();
<span class="keyword">const</span> map2 = <span class="keyword">new</span> <span class="builtin">Map</span>([
[<span class="string">"name"</span>, <span class="string">"Alice"</span>],
[<span class="string">"age"</span>, <span class="number">25</span>]
]);
<span class="comment">// --- Operations ---</span>
map2.set(<span class="string">"grade"</span>, <span class="string">"A"</span>); <span class="comment">// insert / update</span>
map2.get(<span class="string">"name"</span>); <span class="comment">// "Alice"</span>
map2.has(<span class="string">"name"</span>); <span class="comment">// true</span>
map2.delete(<span class="string">"grade"</span>); <span class="comment">// remove</span>
map2.size; <span class="comment">// 2</span>
<span class="comment">// --- Iterating ---</span>
map2.forEach((value, key) => {
<span class="builtin">console</span>.log(key, value);
});
<span class="keyword">for</span> (<span class="keyword">const</span> [key, value] <span class="keyword">of</span> map2) {
<span class="builtin">console</span>.log(key, value);
}
<span class="comment">// --- Keys can be ANY type ---</span>
<span class="keyword">const</span> objKey = { id: <span class="number">1</span> };
map.set(objKey, <span class="string">"object as key"</span>); <span class="comment">// works!</span>
map.set(<span class="number">42</span>, <span class="string">"number as key"</span>); <span class="comment">// works!</span>
<span class="comment">// --- Convert to/from array ---</span>
<span class="keyword">const</span> arr = [...map2]; <span class="comment">// [["name","Alice"], ["age",25]]</span>
<span class="keyword">const</span> fromArr = <span class="keyword">new</span> <span class="builtin">Map</span>(arr); <span class="comment">// back to Map</span></code></pre>
</section>
<!-- ================================================================== -->
<!-- SECTION 4 : HASH SETS -->
<!-- ================================================================== -->
<section id="hash-sets">
<h2>4. Hash Sets</h2>
<p>A <strong>hash set</strong> is like a hash map but it stores <strong>only keys</strong> — no associated values. It answers one question fast: <em>"Is this element in the collection?"</em></p>
<h3>Python: <code>set</code></h3>
<pre><code><span class="lang-label">Python</span>
<span class="comment"># --- Creating ---</span>
s = <span class="builtin">set</span>() <span class="comment"># empty set (NOT {} which is a dict)</span>
s = {<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>} <span class="comment"># set with values</span>
s = <span class="builtin">set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">3</span>]) <span class="comment"># from list (duplicates removed)</span>
<span class="comment"># --- Operations ---</span>
s.add(<span class="number">4</span>) <span class="comment"># add element</span>
s.remove(<span class="number">4</span>) <span class="comment"># remove (KeyError if missing)</span>
s.discard(<span class="number">4</span>) <span class="comment"># remove (no error if missing)</span>
<span class="number">3</span> <span class="keyword">in</span> s <span class="comment"># True (O(1) lookup)</span>
<span class="builtin">len</span>(s) <span class="comment"># 3</span>
<span class="comment"># --- Set Operations ---</span>
a = {<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>}
b = {<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>}
a | b <span class="comment"># Union: {1, 2, 3, 4}</span>
a.union(b) <span class="comment"># Union: {1, 2, 3, 4}</span>
a & b <span class="comment"># Intersection: {2, 3}</span>
a.intersection(b) <span class="comment"># Intersection: {2, 3}</span>
a - b <span class="comment"># Difference: {1}</span>
a.difference(b) <span class="comment"># Difference: {1}</span>
a ^ b <span class="comment"># Symmetric difference: {1, 4}</span>
a.symmetric_difference(b) <span class="comment"># Symmetric difference: {1, 4}</span>
a.issubset(b) <span class="comment"># False</span>
a.issuperset(b) <span class="comment"># False</span></code></pre>
<h3>JavaScript: <code>Set</code></h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// --- Creating ---</span>
<span class="keyword">const</span> s = <span class="keyword">new</span> <span class="builtin">Set</span>();
<span class="keyword">const</span> s2 = <span class="keyword">new</span> <span class="builtin">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">3</span>]); <span class="comment">// {1, 2, 3} (duplicates removed)</span>
<span class="comment">// --- Operations ---</span>
s2.add(<span class="number">4</span>); <span class="comment">// add element</span>
s2.delete(<span class="number">4</span>); <span class="comment">// remove element (returns boolean)</span>
s2.has(<span class="number">3</span>); <span class="comment">// true (O(1) lookup)</span>
s2.size; <span class="comment">// 3</span>
<span class="comment">// --- Iterating ---</span>
s2.forEach(val => <span class="builtin">console</span>.log(val));
<span class="keyword">for</span> (<span class="keyword">const</span> val <span class="keyword">of</span> s2) { <span class="builtin">console</span>.log(val); }
<span class="comment">// --- Set Operations (manual in JS) ---</span>
<span class="keyword">const</span> a = <span class="keyword">new</span> <span class="builtin">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]);
<span class="keyword">const</span> b = <span class="keyword">new</span> <span class="builtin">Set</span>([<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]);
<span class="comment">// Union</span>
<span class="keyword">const</span> union = <span class="keyword">new</span> <span class="builtin">Set</span>([...a, ...b]); <span class="comment">// {1, 2, 3, 4}</span>
<span class="comment">// Intersection</span>
<span class="keyword">const</span> inter = <span class="keyword">new</span> <span class="builtin">Set</span>([...a].filter(x => b.has(x))); <span class="comment">// {2, 3}</span>
<span class="comment">// Difference (a - b)</span>
<span class="keyword">const</span> diff = <span class="keyword">new</span> <span class="builtin">Set</span>([...a].filter(x => !b.has(x))); <span class="comment">// {1}</span>
<span class="comment">// Symmetric Difference</span>
<span class="keyword">const</span> symDiff = <span class="keyword">new</span> <span class="builtin">Set</span>(
[...a].filter(x => !b.has(x)).concat([...b].filter(x => !a.has(x)))
); <span class="comment">// {1, 4}</span>
<span class="comment">// Convert to array</span>
<span class="keyword">const</span> arr = [...s2]; <span class="comment">// [1, 2, 3]</span>
<span class="keyword">const</span> arr2 = Array.from(s2); <span class="comment">// [1, 2, 3]</span></code></pre>
</section>
<!-- ================================================================== -->
<!-- SECTION 5 : COMMON HASH MAP PATTERNS -->
<!-- ================================================================== -->
<section id="common-patterns">
<h2>5. Common Hash Map Patterns</h2>
<!-- Pattern: Frequency Counter -->
<h3>Pattern 1: Frequency Counter</h3>
<p>Count how often each element appears. This is the single most common hash map pattern in interviews.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">frequency_count</span>(nums):
freq = {}
<span class="keyword">for</span> num <span class="keyword">in</span> nums:
freq[num] = freq.get(num, <span class="number">0</span>) + <span class="number">1</span>
<span class="keyword">return</span> freq
<span class="comment"># Or with Counter:</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> Counter
freq = Counter(nums)
<span class="comment"># Example</span>
<span class="builtin">print</span>(frequency_count([<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">3</span>]))
<span class="comment"># {1: 1, 2: 2, 3: 3}</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">frequencyCount</span>(nums) {
<span class="keyword">const</span> freq = <span class="keyword">new</span> <span class="builtin">Map</span>();
<span class="keyword">for</span> (<span class="keyword">const</span> num <span class="keyword">of</span> nums) {
freq.set(num, (freq.get(num) || <span class="number">0</span>) + <span class="number">1</span>);
}
<span class="keyword">return</span> freq;
}
<span class="comment">// Example</span>
<span class="builtin">console</span>.log(frequencyCount([<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">3</span>]));
<span class="comment">// Map { 1 => 1, 2 => 2, 3 => 3 }</span></code></pre>
<!-- Pattern: Two Sum -->
<h3>Pattern 2: Two Sum (The Classic)</h3>
<p>Given an array of integers and a target, return the <strong>indices</strong> of the two numbers that add up to the target.</p>
<div class="formula-box">
Key insight: For each number <code>num</code>, check if <code>target - num</code> already exists in the hash map.
</div>
<div class="tip-box">
<div class="label">Why hash map beats brute force</div>
<p><strong>Brute force:</strong> Check every pair — O(n^2).<br>
<strong>Hash map:</strong> One pass, store complements — O(n).</p>
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">two_sum</span>(nums, target):
<span class="comment"># Map: number -> its index</span>
seen = {}
<span class="keyword">for</span> i, num <span class="keyword">in</span> <span class="builtin">enumerate</span>(nums):
complement = target - num <span class="comment"># what we need to find</span>
<span class="keyword">if</span> complement <span class="keyword">in</span> seen: <span class="comment"># have we seen it before?</span>
<span class="keyword">return</span> [seen[complement], i] <span class="comment"># return both indices</span>
seen[num] = i <span class="comment"># store current number and index</span>
<span class="keyword">return</span> [] <span class="comment"># no solution found</span>
<span class="comment"># --- Walk-through ---</span>
<span class="comment"># nums = [2, 7, 11, 15], target = 9</span>
<span class="comment">#</span>
<span class="comment"># i=0: num=2, comp=7, seen={} -> not found, store {2: 0}</span>
<span class="comment"># i=1: num=7, comp=2, seen={2: 0} -> FOUND! return [0, 1]</span>
<span class="builtin">print</span>(two_sum([<span class="number">2</span>, <span class="number">7</span>, <span class="number">11</span>, <span class="number">15</span>], <span class="number">9</span>)) <span class="comment"># [0, 1]</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">twoSum</span>(nums, target) {
<span class="keyword">const</span> seen = <span class="keyword">new</span> <span class="builtin">Map</span>(); <span class="comment">// number -> index</span>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < nums.length; i++) {
<span class="keyword">const</span> complement = target - nums[i]; <span class="comment">// what we need</span>
<span class="keyword">if</span> (seen.has(complement)) { <span class="comment">// have we seen it?</span>
<span class="keyword">return</span> [seen.get(complement), i]; <span class="comment">// return both indices</span>
}
seen.set(nums[i], i); <span class="comment">// store current number</span>
}
<span class="keyword">return</span> []; <span class="comment">// no solution</span>
}
<span class="comment">// Walk-through:</span>
<span class="comment">// nums = [2, 7, 11, 15], target = 9</span>
<span class="comment">//</span>
<span class="comment">// i=0: num=2, comp=7, seen=Map{} -> not found, store {2->0}</span>
<span class="comment">// i=1: num=7, comp=2, seen=Map{2->0} -> FOUND! return [0, 1]</span>
<span class="builtin">console</span>.log(twoSum([<span class="number">2</span>, <span class="number">7</span>, <span class="number">11</span>, <span class="number">15</span>], <span class="number">9</span>)); <span class="comment">// [0, 1]</span></code></pre>
<!-- Pattern: Group Anagrams -->
<h3>Pattern 3: Group Anagrams</h3>
<p>Given an array of strings, group anagrams together. Two strings are anagrams if they contain the same characters in any order.</p>
<div class="formula-box">
Key insight: Sort each string to get a canonical key. Anagrams share the same sorted form.
<br>"eat" -> "aet", "tea" -> "aet", "ate" -> "aet" -- all map to "aet"
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> defaultdict
<span class="keyword">def</span> <span class="function">group_anagrams</span>(strs):
groups = defaultdict(<span class="builtin">list</span>)
<span class="keyword">for</span> s <span class="keyword">in</span> strs:
<span class="comment"># Sort the string to create a canonical key</span>
key = <span class="builtin">tuple</span>(<span class="builtin">sorted</span>(s)) <span class="comment"># tuple because lists can't be dict keys</span>
groups[key].append(s)
<span class="keyword">return</span> <span class="builtin">list</span>(groups.values())
<span class="comment"># --- Walk-through ---</span>
<span class="comment"># strs = ["eat", "tea", "tan", "ate", "nat", "bat"]</span>
<span class="comment">#</span>
<span class="comment"># "eat" -> sorted = ('a','e','t') -> groups[('a','e','t')] = ["eat"]</span>
<span class="comment"># "tea" -> sorted = ('a','e','t') -> groups[('a','e','t')] = ["eat","tea"]</span>
<span class="comment"># "tan" -> sorted = ('a','n','t') -> groups[('a','n','t')] = ["tan"]</span>
<span class="comment"># "ate" -> sorted = ('a','e','t') -> groups[('a','e','t')] = ["eat","tea","ate"]</span>
<span class="comment"># "nat" -> sorted = ('a','n','t') -> groups[('a','n','t')] = ["tan","nat"]</span>
<span class="comment"># "bat" -> sorted = ('a','b','t') -> groups[('a','b','t')] = ["bat"]</span>
<span class="comment">#</span>
<span class="comment"># Result: [["eat","tea","ate"], ["tan","nat"], ["bat"]]</span>
<span class="builtin">print</span>(group_anagrams([<span class="string">"eat"</span>,<span class="string">"tea"</span>,<span class="string">"tan"</span>,<span class="string">"ate"</span>,<span class="string">"nat"</span>,<span class="string">"bat"</span>]))</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">groupAnagrams</span>(strs) {
<span class="keyword">const</span> groups = <span class="keyword">new</span> <span class="builtin">Map</span>();
<span class="keyword">for</span> (<span class="keyword">const</span> s <span class="keyword">of</span> strs) {
<span class="comment">// Sort the string to create a canonical key</span>
<span class="keyword">const</span> key = s.split(<span class="string">""</span>).sort().join(<span class="string">""</span>);
<span class="keyword">if</span> (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(s);
}
<span class="keyword">return</span> [...groups.values()];
}
<span class="comment">// Walk-through:</span>
<span class="comment">// "eat" -> sorted = "aet" -> groups{"aet": ["eat"]}</span>
<span class="comment">// "tea" -> sorted = "aet" -> groups{"aet": ["eat","tea"]}</span>
<span class="comment">// "tan" -> sorted = "ant" -> groups{"ant": ["tan"]}</span>
<span class="comment">// "ate" -> sorted = "aet" -> groups{"aet": ["eat","tea","ate"]}</span>
<span class="comment">// "nat" -> sorted = "ant" -> groups{"ant": ["tan","nat"]}</span>
<span class="comment">// "bat" -> sorted = "abt" -> groups{"abt": ["bat"]}</span>
<span class="comment">//</span>
<span class="comment">// Result: [["eat","tea","ate"], ["tan","nat"], ["bat"]]</span>
<span class="builtin">console</span>.log(groupAnagrams([<span class="string">"eat"</span>,<span class="string">"tea"</span>,<span class="string">"tan"</span>,<span class="string">"ate"</span>,<span class="string">"nat"</span>,<span class="string">"bat"</span>]));</code></pre>
<!-- Pattern: Checking for Duplicates -->
<h3>Pattern 4: Checking for Duplicates</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">contains_duplicate</span>(nums):
seen = <span class="builtin">set</span>()
<span class="keyword">for</span> num <span class="keyword">in</span> nums:
<span class="keyword">if</span> num <span class="keyword">in</span> seen:
<span class="keyword">return</span> <span class="keyword">True</span>
seen.add(num)
<span class="keyword">return</span> <span class="keyword">False</span>
<span class="comment"># One-liner alternative:</span>
<span class="keyword">def</span> <span class="function">contains_duplicate</span>(nums):
<span class="keyword">return</span> <span class="builtin">len</span>(nums) != <span class="builtin">len</span>(<span class="builtin">set</span>(nums))</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">containsDuplicate</span>(nums) {
<span class="keyword">const</span> seen = <span class="keyword">new</span> <span class="builtin">Set</span>();
<span class="keyword">for</span> (<span class="keyword">const</span> num <span class="keyword">of</span> nums) {
<span class="keyword">if</span> (seen.has(num)) <span class="keyword">return</span> <span class="keyword">true</span>;
seen.add(num);
}
<span class="keyword">return</span> <span class="keyword">false</span>;
}
<span class="comment">// One-liner alternative:</span>
<span class="keyword">const</span> <span class="function">containsDuplicate</span> = nums => <span class="keyword">new</span> <span class="builtin">Set</span>(nums).size !== nums.length;</code></pre>
</section>
<!-- ================================================================== -->
<!-- SECTION 6 : WHEN TO USE HASH MAPS -->
<!-- ================================================================== -->
<section id="when-to-use">
<h2>6. When to Use Hash Maps</h2>
<p>Reach for a hash map (or hash set) when you see these patterns in a problem:</p>
<table>
<thead>
<tr>
<th>Pattern</th>
<th>Use</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>O(1) lookups</strong></td>
<td>Hash map / set</td>
<td>"Have we seen this element before?"</td>
</tr>
<tr>
<td><strong>Counting frequencies</strong></td>
<td>Hash map</td>
<td>"How many times does each char appear?"</td>
</tr>
<tr>
<td><strong>Caching / memoization</strong></td>
<td>Hash map</td>
<td>"Store computed results to avoid recalculation"</td>
</tr>
<tr>
<td><strong>Mapping relationships</strong></td>
<td>Hash map</td>
<td>"Map each node to its parent"</td>
</tr>
<tr>
<td><strong>Removing duplicates</strong></td>
<td>Hash set</td>
<td>"Return unique elements only"</td>
</tr>
<tr>
<td><strong>Complement problems</strong></td>
<td>Hash map</td>
<td>"Find two numbers that sum to target"</td>
</tr>
<tr>
<td><strong>Grouping</strong></td>
<td>Hash map of lists</td>
<td>"Group anagrams", "group by category"</td>
</tr>
<tr>
<td><strong>Prefix sums</strong></td>
<td>Hash map</td>
<td>"Subarray sum equals K"</td>
</tr>
</tbody>
</table>
<div class="tip-box">
<div class="label">Interview heuristic</div>
<p>If the brute force is O(n^2) because of nested "find" operations, a hash map can almost always bring it down to <strong>O(n)</strong>.</p>
</div>
<div class="formula-box">
<strong>Hash Map vs Sorted Map -- Decision Rule:</strong><br><br>
• Need O(1) average lookup, no ordering → <strong>Hash Map</strong> (dict, HashMap, unordered_map)<br>
• Need sorted iteration or range queries → <strong>Sorted Map</strong> (TreeMap, std::map) -- O(log n)<br>
• Only need membership testing (no values) → <strong>Hash Set</strong> (set, HashSet)<br><br>
<strong>Load factor rule:</strong> Expected chain length = n/m (items/buckets). O(1) assumes load factor is bounded (Python: 2/3, Java: 0.75).
</div>
</section>
<!-- ================================================================== -->
<!-- SECTION 7 : LEETCODE PROBLEMS -->
<!-- ================================================================== -->
<section id="leetcode-problems">
<h2>7. LeetCode Problems</h2>
<p>Essential hash map problems ordered from easy to medium. Practice these to build pattern recognition.</p>
<table>
<thead>
<tr>
<th>Problem</th>
<th>Difficulty</th>
<th>Pattern</th>
<th>Key Idea</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://leetcode.com/problems/two-sum/" class="resource-link">Two Sum</a></td>
<td><span class="tag green">Easy</span></td>
<td>Complement lookup</td>
<td>Store num->index, check if target-num exists</td>
</tr>
<tr>
<td><a href="https://leetcode.com/problems/valid-anagram/" class="resource-link">Valid Anagram</a></td>
<td><span class="tag green">Easy</span></td>
<td>Frequency counter</td>
<td>Compare character frequencies of both strings</td>
</tr>
<tr>
<td><a href="https://leetcode.com/problems/contains-duplicate/" class="resource-link">Contains Duplicate</a></td>
<td><span class="tag green">Easy</span></td>
<td>Set membership</td>
<td>Add to set; if already present, duplicate found</td>
</tr>
<tr>
<td><a href="https://leetcode.com/problems/group-anagrams/" class="resource-link">Group Anagrams</a></td>
<td><span class="tag orange">Medium</span></td>
<td>Sorted key grouping</td>
<td>Sort each word as key, group values in a list</td>
</tr>
<tr>
<td><a href="https://leetcode.com/problems/top-k-frequent-elements/" class="resource-link">Top K Frequent Elements</a></td>
<td><span class="tag orange">Medium</span></td>
<td>Freq map + bucket sort</td>
<td>Count frequencies, then use bucket sort or heap for top K</td>
</tr>
<tr>
<td><a href="https://leetcode.com/problems/longest-consecutive-sequence/" class="resource-link">Longest Consecutive Sequence</a></td>
<td><span class="tag orange">Medium</span></td>
<td>Set + sequence start</td>
<td>Put all in set; only start counting from sequence beginnings</td>
</tr>
<tr>
<td><a href="https://leetcode.com/problems/subarray-sum-equals-k/" class="resource-link">Subarray Sum Equals K</a></td>
<td><span class="tag orange">Medium</span></td>
<td>Prefix sum + hash map</td>
<td>Store prefix_sum->count; check if prefix_sum - k exists</td>
</tr>
<tr>
<td><a href="https://leetcode.com/problems/lru-cache/" class="resource-link">LRU Cache</a></td>
<td><span class="tag orange">Medium</span></td>
<td>Hash map + doubly linked list</td>
<td>O(1) access via map, O(1) eviction via linked list</td>
</tr>
</tbody>
</table>
<h3>Full Solution: Two Sum</h3>
<div class="example-box">
<div class="label">Problem statement</div>
<p>Given an array of integers <code>nums</code> and an integer <code>target</code>, return indices of the two numbers such that they add up to <code>target</code>. You may assume each input has exactly one solution.</p>
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">twoSum</span>(nums, target):
seen = {} <span class="comment"># value -> index</span>
<span class="keyword">for</span> i, num <span class="keyword">in</span> <span class="builtin">enumerate</span>(nums):
complement = target - num <span class="comment"># the number we need</span>
<span class="keyword">if</span> complement <span class="keyword">in</span> seen: <span class="comment"># O(1) lookup</span>
<span class="keyword">return</span> [seen[complement], i]
seen[num] = i <span class="comment"># store for future lookups</span>
<span class="keyword">return</span> []
<span class="comment"># Time: O(n) - single pass through array</span>
<span class="comment"># Space: O(n) - hash map stores up to n entries</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">var</span> <span class="function">twoSum</span> = <span class="keyword">function</span>(nums, target) {
<span class="keyword">const</span> seen = <span class="keyword">new</span> <span class="builtin">Map</span>(); <span class="comment">// value -> index</span>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < nums.length; i++) {
<span class="keyword">const</span> complement = target - nums[i]; <span class="comment">// the number we need</span>
<span class="keyword">if</span> (seen.has(complement)) { <span class="comment">// O(1) lookup</span>
<span class="keyword">return</span> [seen.get(complement), i];
}
seen.set(nums[i], i); <span class="comment">// store for future lookups</span>
}
<span class="keyword">return</span> [];
};
<span class="comment">// Time: O(n) - single pass through array</span>
<span class="comment">// Space: O(n) - Map stores up to n entries</span></code></pre>
<h3>Full Solution: Group Anagrams</h3>
<div class="example-box">
<div class="label">Problem statement</div>
<p>Given an array of strings <code>strs</code>, group the anagrams together. You can return the answer in any order.</p>
<p><strong>Example:</strong> <code>["eat","tea","tan","ate","nat","bat"]</code> returns <code>[["eat","tea","ate"],["tan","nat"],["bat"]]</code></p>
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> collections <span class="keyword">import</span> defaultdict
<span class="keyword">def</span> <span class="function">groupAnagrams</span>(strs):
groups = defaultdict(<span class="builtin">list</span>) <span class="comment"># sorted_key -> [original strings]</span>
<span class="keyword">for</span> s <span class="keyword">in</span> strs:
key = <span class="builtin">tuple</span>(<span class="builtin">sorted</span>(s)) <span class="comment"># O(k log k) where k = len(s)</span>
groups[key].append(s)
<span class="keyword">return</span> <span class="builtin">list</span>(groups.values())
<span class="comment"># Time: O(n * k log k) where n = number of strings, k = max string length</span>
<span class="comment"># Space: O(n * k) for storing all strings in groups</span>
<span class="comment"># --- Alternative: character count key (avoids sorting) ---</span>
<span class="keyword">def</span> <span class="function">groupAnagrams</span>(strs):
groups = defaultdict(<span class="builtin">list</span>)
<span class="keyword">for</span> s <span class="keyword">in</span> strs:
<span class="comment"># Count frequency of each letter as key</span>
count = [<span class="number">0</span>] * <span class="number">26</span>
<span class="keyword">for</span> c <span class="keyword">in</span> s:
count[<span class="builtin">ord</span>(c) - <span class="builtin">ord</span>(<span class="string">'a'</span>)] += <span class="number">1</span>
groups[<span class="builtin">tuple</span>(count)].append(s)
<span class="keyword">return</span> <span class="builtin">list</span>(groups.values())
<span class="comment"># Time: O(n * k) - no sorting needed</span>
<span class="comment"># Space: O(n * k)</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">var</span> <span class="function">groupAnagrams</span> = <span class="keyword">function</span>(strs) {
<span class="keyword">const</span> groups = <span class="keyword">new</span> <span class="builtin">Map</span>(); <span class="comment">// sorted_key -> [original strings]</span>
<span class="keyword">for</span> (<span class="keyword">const</span> s <span class="keyword">of</span> strs) {
<span class="keyword">const</span> key = s.split(<span class="string">""</span>).sort().join(<span class="string">""</span>); <span class="comment">// O(k log k)</span>
<span class="keyword">if</span> (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(s);
}
<span class="keyword">return</span> [...groups.values()];
};
<span class="comment">// Time: O(n * k log k)</span>
<span class="comment">// Space: O(n * k)</span>
<span class="comment">// --- Alternative: character count key ---</span>
<span class="keyword">var</span> <span class="function">groupAnagrams</span> = <span class="keyword">function</span>(strs) {
<span class="keyword">const</span> groups = <span class="keyword">new</span> <span class="builtin">Map</span>();
<span class="keyword">for</span> (<span class="keyword">const</span> s <span class="keyword">of</span> strs) {
<span class="keyword">const</span> count = <span class="keyword">new</span> Array(<span class="number">26</span>).fill(<span class="number">0</span>);
<span class="keyword">for</span> (<span class="keyword">const</span> c <span class="keyword">of</span> s) {
count[c.charCodeAt(<span class="number">0</span>) - <span class="number">97</span>]++;
}
<span class="keyword">const</span> key = count.join(<span class="string">","</span>); <span class="comment">// "1,0,0,...,1,0" as string key</span>
<span class="keyword">if</span> (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(s);
}
<span class="keyword">return</span> [...groups.values()];
};
<span class="comment">// Time: O(n * k)</span>
<span class="comment">// Space: O(n * k)</span></code></pre>
</section>
<!-- ================================================================== -->
<!-- SECTION 8 : IMPLEMENTING FROM SCRATCH -->
<!-- ================================================================== -->
<section id="implement-from-scratch">
<h2>8. Implementing a Hash Map from Scratch</h2>
<p>Building your own hash map helps you understand the internals. Here is a simplified but educational implementation using <strong>chaining</strong> (array of linked lists).</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">HashMap</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, capacity=<span class="number">16</span>):
self.capacity = capacity
self.size = <span class="number">0</span>
self.buckets = [[] <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="builtin">range</span>(capacity)]
<span class="keyword">def</span> <span class="function">_hash</span>(self, key):
<span class="string">"""Convert key to bucket index."""</span>
<span class="keyword">return</span> <span class="builtin">hash</span>(key) % self.capacity
<span class="keyword">def</span> <span class="function">put</span>(self, key, value):
<span class="string">"""Insert or update a key-value pair."""</span>
index = self._hash(key)
bucket = self.buckets[index]
<span class="comment"># Check if key already exists in this bucket</span>
<span class="keyword">for</span> i, (k, v) <span class="keyword">in</span> <span class="builtin">enumerate</span>(bucket):
<span class="keyword">if</span> k == key:
bucket[i] = (key, value) <span class="comment"># update existing</span>
<span class="keyword">return</span>
<span class="comment"># Key not found, add new entry</span>
bucket.append((key, value))
self.size += <span class="number">1</span>