-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patharrays.html
More file actions
1632 lines (1369 loc) · 85.8 KB
/
arrays.html
File metadata and controls
1632 lines (1369 loc) · 85.8 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>Arrays & Strings - 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> / Arrays & Strings</div>
<h1>Arrays & Strings</h1>
<p>The most fundamental data structure in programming. Master arrays and you have the foundation for everything else in DSA.</p>
</div>
<!-- Table of Contents -->
<div class="toc">
<h4>Table of Contents</h4>
<a href="#what-is-array">1. What is an Array?</a>
<a href="#time-complexity">2. Time Complexity</a>
<a href="#basic-operations">3. Basic Operations with Code</a>
<a href="#techniques">4. Common Array Techniques</a>
<a href="#strings">5. Strings</a>
<a href="#leetcode">6. LeetCode Problems to Practice</a>
<a href="#quiz">7. Practice Quiz</a>
</div>
<!-- ============================================================ -->
<!-- SECTION 1: What is an Array? -->
<!-- ============================================================ -->
<section id="what-is-array">
<h2>1. What is an Array?</h2>
<p>
An <strong>array</strong> is a collection of elements stored in <strong>contiguous (adjacent) memory locations</strong>. Because the elements sit right next to each other in memory, you can jump to any element instantly if you know its index. This is why array access is O(1) -- the computer calculates the exact memory address with simple arithmetic.
</p>
<div class="formula-box">
address(arr[i]) = base_address + (i * element_size)
</div>
<h3>Fixed-Size vs Dynamic Arrays</h3>
<p>
In low-level languages like C or Java, arrays have a <strong>fixed size</strong> -- you declare how many elements they hold at creation and that is it. You cannot grow or shrink them.
</p>
<p>
In Python and JavaScript, you work with <strong>dynamic arrays</strong> (Python's <code>list</code>, JavaScript's <code>Array</code>). These automatically resize when you add more elements than the current capacity allows. Under the hood, they allocate a new, larger block of memory and copy everything over. This resizing is why appending is <strong>O(1) amortized</strong> -- most appends are instant, but occasionally one triggers a costly resize.
</p>
<div class="warning-box">
<div class="label">Warning</div>
<p>Do not confuse "array" in C (fixed, contiguous, typed) with Python's <code>list</code> (dynamic, can hold mixed types). When interviewers say "array," they typically mean the logical concept -- an indexed, ordered collection -- regardless of language.</p>
</div>
<h3>Memory Layout</h3>
<p>Here is how an array of integers looks in memory. Each cell is the same size, and the index determines the offset from the base address:</p>
<div class="memory-diagram">
Memory Address: 0x1000 0x1004 0x1008 0x100C 0x1010
+----------+----------+----------+----------+----------+
arr = | 10 | 20 | 30 | 40 | 50 |
+----------+----------+----------+----------+----------+
Index: [0] [1] [2] [3] [4]
To access arr[3]:
address = 0x1000 + (3 * 4 bytes) = 0x100C --> value: 40
This is why random access is O(1) -- just one multiplication and one addition.
</div>
<h3>Why O(1) Random Access Matters</h3>
<p>
Because every element is the same size and stored contiguously, accessing <code>arr[0]</code> and <code>arr[999999]</code> takes the exact same amount of time. No scanning, no traversal -- just a direct memory lookup. This is the superpower of arrays compared to linked lists, where you would need to walk through every node.
</p>
<div class="tip-box">
<div class="label">Tip</div>
<p>Arrays are cache-friendly. Because elements are adjacent in memory, your CPU cache loads nearby elements automatically. Iterating through an array is one of the fastest operations a computer can do.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 2: Time Complexity -->
<!-- ============================================================ -->
<section id="time-complexity">
<h2>2. Time Complexity</h2>
<p>Understanding the time complexity of every operation is critical. This table is your cheat sheet for array operations:</p>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Fixed-Size Array</th>
<th>Dynamic Array</th>
<th>Why?</th>
</tr>
</thead>
<tbody>
<tr>
<td>Access by index</td>
<td>O(1)</td>
<td>O(1)</td>
<td>Direct address calculation</td>
</tr>
<tr>
<td>Search (unsorted)</td>
<td>O(n)</td>
<td>O(n)</td>
<td>Must check each element</td>
</tr>
<tr>
<td>Search (sorted)</td>
<td>O(log n)</td>
<td>O(log n)</td>
<td>Binary search</td>
</tr>
<tr>
<td>Insert at end</td>
<td>N/A (fixed size)</td>
<td>O(1) amortized</td>
<td>Occasional resize costs O(n)</td>
</tr>
<tr>
<td>Insert at index</td>
<td>O(n)</td>
<td>O(n)</td>
<td>Must shift elements right</td>
</tr>
<tr>
<td>Delete from end</td>
<td>N/A</td>
<td>O(1)</td>
<td>No shifting needed</td>
</tr>
<tr>
<td>Delete at index</td>
<td>O(n)</td>
<td>O(n)</td>
<td>Must shift elements left</td>
</tr>
</tbody>
</table>
<div class="formula-box">
Space complexity: O(n) -- arrays store n elements
</div>
<div class="example-box">
<div class="label">Example -- Why Insert at Index is O(n)</div>
<p>To insert <code>99</code> at index 2 in <code>[10, 20, 30, 40, 50]</code>:</p>
<p>Step 1: Shift 30, 40, 50 one position right.</p>
<p>Step 2: Place 99 at index 2.</p>
<p>Result: <code>[10, 20, 99, 30, 40, 50]</code>. In the worst case (inserting at index 0), you shift all n elements.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 3: Basic Operations with Code -->
<!-- ============================================================ -->
<section id="basic-operations">
<h2>3. Basic Operations with Code</h2>
<!-- Creating Arrays -->
<h3>Creating Arrays</h3>
<p>Both Python and JavaScript create dynamic arrays with similar syntax:</p>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
<span class="comment"># Create an array (list in Python)</span>
arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]
<span class="comment"># Create an empty array</span>
empty = []
<span class="comment"># Create array of n zeros</span>
zeros = [<span class="number">0</span>] * <span class="number">10</span>
<span class="comment"># Create array with list comprehension</span>
squares = [i**<span class="number">2</span> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(<span class="number">5</span>)]
<span class="comment"># [0, 1, 4, 9, 16]</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Create an array</span>
<span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];
<span class="comment">// Create an empty array</span>
<span class="keyword">const</span> empty = [];
<span class="comment">// Create array of n zeros</span>
<span class="keyword">const</span> zeros = <span class="keyword">new</span> <span class="builtin">Array</span>(<span class="number">10</span>).<span class="function">fill</span>(<span class="number">0</span>);
<span class="comment">// Create array with Array.from</span>
<span class="keyword">const</span> squares = <span class="builtin">Array</span>.<span class="function">from</span>(
{<span class="function">length</span>: <span class="number">5</span>}, (_, i) => i ** <span class="number">2</span>
);
<span class="comment">// [0, 1, 4, 9, 16]</span></code></pre>
</div>
<!-- Accessing Elements -->
<h3>Accessing Elements</h3>
<p>Access any element in O(1) using its index. Arrays are zero-indexed in both languages:</p>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
arr = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>, <span class="number">50</span>]
<span class="comment"># Access by index</span>
first = arr[<span class="number">0</span>] <span class="comment"># 10</span>
third = arr[<span class="number">2</span>] <span class="comment"># 30</span>
<span class="comment"># Negative indexing (Python-only!)</span>
last = arr[-<span class="number">1</span>] <span class="comment"># 50</span>
second_last = arr[-<span class="number">2</span>] <span class="comment"># 40</span>
<span class="comment"># Length</span>
size = <span class="builtin">len</span>(arr) <span class="comment"># 5</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> arr = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>, <span class="number">50</span>];
<span class="comment">// Access by index</span>
<span class="keyword">const</span> first = arr[<span class="number">0</span>]; <span class="comment">// 10</span>
<span class="keyword">const</span> third = arr[<span class="number">2</span>]; <span class="comment">// 30</span>
<span class="comment">// Last element (no negative indexing)</span>
<span class="keyword">const</span> last = arr[arr.<span class="function">length</span> - <span class="number">1</span>]; <span class="comment">// 50</span>
<span class="comment">// Or use .at() in modern JS</span>
<span class="keyword">const</span> alsoLast = arr.<span class="function">at</span>(-<span class="number">1</span>); <span class="comment">// 50</span>
<span class="comment">// Length</span>
<span class="keyword">const</span> size = arr.<span class="function">length</span>; <span class="comment">// 5</span></code></pre>
</div>
<!-- Traversal -->
<h3>Traversal</h3>
<p>Traversal means visiting every element. There are multiple ways to loop through an array:</p>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
arr = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>]
<span class="comment"># Method 1: Simple for loop</span>
<span class="keyword">for</span> val <span class="keyword">in</span> arr:
<span class="builtin">print</span>(val)
<span class="comment"># Method 2: With index using enumerate</span>
<span class="keyword">for</span> i, val <span class="keyword">in</span> <span class="builtin">enumerate</span>(arr):
<span class="builtin">print</span>(<span class="string">f"Index </span>{i}<span class="string">: </span>{val}<span class="string">"</span>)
<span class="comment"># Method 3: Index-based loop</span>
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(<span class="builtin">len</span>(arr)):
<span class="builtin">print</span>(arr[i])
<span class="comment"># Method 4: While loop</span>
i = <span class="number">0</span>
<span class="keyword">while</span> i < <span class="builtin">len</span>(arr):
<span class="builtin">print</span>(arr[i])
i += <span class="number">1</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> arr = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>];
<span class="comment">// Method 1: for...of loop</span>
<span class="keyword">for</span> (<span class="keyword">const</span> val <span class="keyword">of</span> arr) {
console.<span class="function">log</span>(val);
}
<span class="comment">// Method 2: forEach with index</span>
arr.<span class="function">forEach</span>((val, i) => {
console.<span class="function">log</span>(<span class="string">`Index ${i}: ${val}`</span>);
});
<span class="comment">// Method 3: Classic for loop</span>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < arr.<span class="function">length</span>; i++) {
console.<span class="function">log</span>(arr[i]);
}
<span class="comment">// Method 4: While loop</span>
<span class="keyword">let</span> i = <span class="number">0</span>;
<span class="keyword">while</span> (i < arr.<span class="function">length</span>) {
console.<span class="function">log</span>(arr[i]);
i++;
}</code></pre>
</div>
<div class="tip-box">
<div class="label">Tip</div>
<p>In Python, prefer <code>for val in arr</code> for simple iteration and <code>for i, val in enumerate(arr)</code> when you need the index. The <code>range(len(arr))</code> pattern is considered less Pythonic but is sometimes necessary for two-pointer patterns.</p>
</div>
<!-- Inserting -->
<h3>Inserting Elements</h3>
<p>Adding elements to a dynamic array:</p>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]
<span class="comment"># Append to end -- O(1) amortized</span>
arr.<span class="function">append</span>(<span class="number">4</span>)
<span class="comment"># [1, 2, 3, 4]</span>
<span class="comment"># Insert at specific index -- O(n)</span>
arr.<span class="function">insert</span>(<span class="number">1</span>, <span class="number">99</span>)
<span class="comment"># [1, 99, 2, 3, 4]</span>
<span class="comment"># Extend with another list -- O(k)</span>
arr.<span class="function">extend</span>([<span class="number">5</span>, <span class="number">6</span>])
<span class="comment"># [1, 99, 2, 3, 4, 5, 6]</span>
<span class="comment"># Concatenation (creates new list)</span>
new_arr = arr + [<span class="number">7</span>, <span class="number">8</span>]</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];
<span class="comment">// Push to end -- O(1) amortized</span>
arr.<span class="function">push</span>(<span class="number">4</span>);
<span class="comment">// [1, 2, 3, 4]</span>
<span class="comment">// Insert at specific index -- O(n)</span>
arr.<span class="function">splice</span>(<span class="number">1</span>, <span class="number">0</span>, <span class="number">99</span>);
<span class="comment">// [1, 99, 2, 3, 4]</span>
<span class="comment">// Push multiple elements</span>
arr.<span class="function">push</span>(<span class="number">5</span>, <span class="number">6</span>);
<span class="comment">// [1, 99, 2, 3, 4, 5, 6]</span>
<span class="comment">// Unshift to front -- O(n)</span>
arr.<span class="function">unshift</span>(<span class="number">0</span>);
<span class="comment">// [0, 1, 99, 2, 3, 4, 5, 6]</span></code></pre>
</div>
<!-- Deleting -->
<h3>Deleting Elements</h3>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
arr = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>, <span class="number">50</span>]
<span class="comment"># Pop last element -- O(1)</span>
last = arr.<span class="function">pop</span>()
<span class="comment"># last = 50, arr = [10, 20, 30, 40]</span>
<span class="comment"># Pop at specific index -- O(n)</span>
second = arr.<span class="function">pop</span>(<span class="number">1</span>)
<span class="comment"># second = 20, arr = [10, 30, 40]</span>
<span class="comment"># Remove by value -- O(n)</span>
arr.<span class="function">remove</span>(<span class="number">30</span>)
<span class="comment"># arr = [10, 40]</span>
<span class="comment"># Delete by index</span>
<span class="keyword">del</span> arr[<span class="number">0</span>]
<span class="comment"># arr = [40]</span>
<span class="comment"># Clear entire list</span>
arr.<span class="function">clear</span>()
<span class="comment"># arr = []</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> arr = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>, <span class="number">50</span>];
<span class="comment">// Pop last element -- O(1)</span>
<span class="keyword">const</span> last = arr.<span class="function">pop</span>();
<span class="comment">// last = 50, arr = [10, 20, 30, 40]</span>
<span class="comment">// Remove at index using splice -- O(n)</span>
<span class="keyword">const</span> removed = arr.<span class="function">splice</span>(<span class="number">1</span>, <span class="number">1</span>);
<span class="comment">// removed = [20], arr = [10, 30, 40]</span>
<span class="comment">// Shift removes first element -- O(n)</span>
<span class="keyword">const</span> first = arr.<span class="function">shift</span>();
<span class="comment">// first = 10, arr = [30, 40]</span>
<span class="comment">// Filter to remove by value -- O(n)</span>
<span class="keyword">let</span> filtered = arr.<span class="function">filter</span>(x => x !== <span class="number">30</span>);
<span class="comment">// filtered = [40]</span>
<span class="comment">// Clear entire array</span>
arr.<span class="function">length</span> = <span class="number">0</span>;
<span class="comment">// arr = []</span></code></pre>
</div>
<!-- Slicing -->
<h3>Slicing</h3>
<p>Slicing extracts a sub-array without modifying the original. Both languages use start-inclusive, end-exclusive ranges:</p>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
arr = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>, <span class="number">50</span>]
<span class="comment"># Basic slice: arr[start:end]</span>
sub = arr[<span class="number">1</span>:<span class="number">4</span>]
<span class="comment"># [20, 30, 40]</span>
<span class="comment"># From beginning</span>
first_three = arr[:<span class="number">3</span>]
<span class="comment"># [10, 20, 30]</span>
<span class="comment"># To end</span>
last_two = arr[<span class="number">3</span>:]
<span class="comment"># [40, 50]</span>
<span class="comment"># With step</span>
every_other = arr[::<span class="number">2</span>]
<span class="comment"># [10, 30, 50]</span>
<span class="comment"># Reverse an array</span>
reversed_arr = arr[::-<span class="number">1</span>]
<span class="comment"># [50, 40, 30, 20, 10]</span>
<span class="comment"># Shallow copy</span>
copy = arr[:]</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> arr = [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>, <span class="number">50</span>];
<span class="comment">// Basic slice: arr.slice(start, end)</span>
<span class="keyword">const</span> sub = arr.<span class="function">slice</span>(<span class="number">1</span>, <span class="number">4</span>);
<span class="comment">// [20, 30, 40]</span>
<span class="comment">// From beginning</span>
<span class="keyword">const</span> firstThree = arr.<span class="function">slice</span>(<span class="number">0</span>, <span class="number">3</span>);
<span class="comment">// [10, 20, 30]</span>
<span class="comment">// To end</span>
<span class="keyword">const</span> lastTwo = arr.<span class="function">slice</span>(<span class="number">3</span>);
<span class="comment">// [40, 50]</span>
<span class="comment">// No step parameter -- use filter</span>
<span class="keyword">const</span> everyOther = arr.<span class="function">filter</span>(
(_, i) => i % <span class="number">2</span> === <span class="number">0</span>
);
<span class="comment">// [10, 30, 50]</span>
<span class="comment">// Reverse (mutates original!)</span>
<span class="keyword">const</span> rev = [...arr].<span class="function">reverse</span>();
<span class="comment">// [50, 40, 30, 20, 10]</span>
<span class="comment">// Shallow copy</span>
<span class="keyword">const</span> copy = [...arr];</code></pre>
</div>
<div class="warning-box">
<div class="label">Warning</div>
<p>In JavaScript, <code>.reverse()</code> mutates the original array. Always spread into a new array first with <code>[...arr].reverse()</code> if you need to preserve the original. Python's <code>arr[::-1]</code> creates a new list and does not mutate.</p>
</div>
<!-- Searching -->
<h3>Searching (Linear Search)</h3>
<p>Linear search checks each element one by one. It is O(n) in the worst case:</p>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">linear_search</span>(arr, target):
<span class="string">"""Return index of target, or -1 if not found."""</span>
<span class="keyword">for</span> i, val <span class="keyword">in</span> <span class="builtin">enumerate</span>(arr):
<span class="keyword">if</span> val == target:
<span class="keyword">return</span> i
<span class="keyword">return</span> -<span class="number">1</span>
<span class="comment"># Usage</span>
arr = [<span class="number">5</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">1</span>, <span class="number">9</span>]
idx = <span class="function">linear_search</span>(arr, <span class="number">8</span>) <span class="comment"># 2</span>
idx = <span class="function">linear_search</span>(arr, <span class="number">7</span>) <span class="comment"># -1</span>
<span class="comment"># Built-in alternatives:</span>
<span class="number">8</span> <span class="keyword">in</span> arr <span class="comment"># True (O(n))</span>
arr.<span class="function">index</span>(<span class="number">8</span>) <span class="comment"># 2 (raises ValueError if not found)</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">linearSearch</span>(arr, target) {
<span class="comment">// Return index of target, or -1</span>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < arr.<span class="function">length</span>; i++) {
<span class="keyword">if</span> (arr[i] === target) {
<span class="keyword">return</span> i;
}
}
<span class="keyword">return</span> -<span class="number">1</span>;
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> arr = [<span class="number">5</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">1</span>, <span class="number">9</span>];
<span class="function">linearSearch</span>(arr, <span class="number">8</span>); <span class="comment">// 2</span>
<span class="function">linearSearch</span>(arr, <span class="number">7</span>); <span class="comment">// -1</span>
<span class="comment">// Built-in alternatives:</span>
arr.<span class="function">includes</span>(<span class="number">8</span>); <span class="comment">// true (O(n))</span>
arr.<span class="function">indexOf</span>(<span class="number">8</span>); <span class="comment">// 2 (-1 if not found)</span></code></pre>
</div>
<!-- Sorting -->
<h3>Sorting</h3>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
arr = [<span class="number">5</span>, <span class="number">2</span>, <span class="number">8</span>, <span class="number">1</span>, <span class="number">9</span>, <span class="number">3</span>]
<span class="comment"># Sort in-place -- O(n log n)</span>
arr.<span class="function">sort</span>()
<span class="comment"># arr = [1, 2, 3, 5, 8, 9]</span>
<span class="comment"># Sort descending</span>
arr.<span class="function">sort</span>(reverse=<span class="keyword">True</span>)
<span class="comment"># arr = [9, 8, 5, 3, 2, 1]</span>
<span class="comment"># Create new sorted list (original unchanged)</span>
original = [<span class="number">5</span>, <span class="number">2</span>, <span class="number">8</span>]
new_sorted = <span class="builtin">sorted</span>(original)
<span class="comment"># original = [5, 2, 8]</span>
<span class="comment"># new_sorted = [2, 5, 8]</span>
<span class="comment"># Sort with custom key</span>
words = [<span class="string">"banana"</span>, <span class="string">"fig"</span>, <span class="string">"cherry"</span>]
words.<span class="function">sort</span>(key=<span class="builtin">len</span>)
<span class="comment"># ["fig", "banana", "cherry"]</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> arr = [<span class="number">5</span>, <span class="number">2</span>, <span class="number">8</span>, <span class="number">1</span>, <span class="number">9</span>, <span class="number">3</span>];
<span class="comment">// Sort in-place -- O(n log n)</span>
<span class="comment">// WARNING: default sort is lexicographic!</span>
arr.<span class="function">sort</span>((a, b) => a - b);
<span class="comment">// arr = [1, 2, 3, 5, 8, 9]</span>
<span class="comment">// Sort descending</span>
arr.<span class="function">sort</span>((a, b) => b - a);
<span class="comment">// arr = [9, 8, 5, 3, 2, 1]</span>
<span class="comment">// Create new sorted array</span>
<span class="keyword">const</span> original = [<span class="number">5</span>, <span class="number">2</span>, <span class="number">8</span>];
<span class="keyword">const</span> newSorted = [...original].<span class="function">sort</span>(
(a, b) => a - b
);
<span class="comment">// original = [5, 2, 8] (unchanged)</span>
<span class="comment">// Sort with custom comparator</span>
<span class="keyword">const</span> words = [<span class="string">"banana"</span>, <span class="string">"fig"</span>, <span class="string">"cherry"</span>];
words.<span class="function">sort</span>((a, b) => a.<span class="function">length</span> - b.<span class="function">length</span>);
<span class="comment">// ["fig", "banana", "cherry"]</span></code></pre>
</div>
<div class="warning-box">
<div class="label">Critical JavaScript Gotcha</div>
<p>JavaScript's default <code>.sort()</code> converts elements to strings and sorts lexicographically. This means <code>[10, 9, 80].sort()</code> gives <code>[10, 80, 9]</code> -- not <code>[9, 10, 80]</code>. <strong>Always pass a comparator</strong> when sorting numbers: <code>arr.sort((a, b) => a - b)</code>.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 4: Common Array Techniques -->
<!-- ============================================================ -->
<section id="techniques">
<h2>4. Common Array Techniques</h2>
<p>These three techniques show up in the majority of array interview problems. Learn them deeply and you will recognize them instantly.</p>
<!-- Two Pointers -->
<h3 id="two-pointers">Two Pointers</h3>
<p>
The <strong>two-pointer technique</strong> uses two indices that move through the array, typically from opposite ends or at different speeds. It reduces brute-force O(n^2) solutions to O(n) by eliminating redundant comparisons.
</p>
<div class="formula-box">
When to use Two Pointers:
- Array is sorted (or can be sorted)
- You need to find a pair/triplet that satisfies a condition
- You need to compare elements from both ends
- You need to partition or rearrange in-place
</div>
<p><strong>Example: Two Sum on a Sorted Array</strong></p>
<p>Given a sorted array and a target, find two numbers that add up to the target. Return their indices.</p>
<div class="example-box">
<div class="label">Walkthrough</div>
<p><code>arr = [1, 3, 5, 7, 11, 15]</code>, <code>target = 12</code></p>
<p>Left pointer at index 0 (value 1), right pointer at index 5 (value 15).</p>
<p>1 + 15 = 16 > 12 --> Move right pointer left.</p>
<p>1 + 11 = 12 = target --> Found it! Return [0, 4].</p>
<p>Key insight: if the sum is too big, decreasing the right side makes it smaller. If the sum is too small, increasing the left side makes it bigger.</p>
</div>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">two_sum_sorted</span>(arr, target):
<span class="string">"""
Find two numbers in sorted array
that add up to target.
Returns their indices.
"""</span>
left = <span class="number">0</span>
right = <span class="builtin">len</span>(arr) - <span class="number">1</span>
<span class="keyword">while</span> left < right:
current_sum = arr[left] + arr[right]
<span class="keyword">if</span> current_sum == target:
<span class="keyword">return</span> [left, right]
<span class="keyword">elif</span> current_sum < target:
left += <span class="number">1</span> <span class="comment"># Need bigger sum</span>
<span class="keyword">else</span>:
right -= <span class="number">1</span> <span class="comment"># Need smaller sum</span>
<span class="keyword">return</span> [] <span class="comment"># No pair found</span>
<span class="comment"># Usage</span>
arr = [<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">11</span>, <span class="number">15</span>]
<span class="builtin">print</span>(<span class="function">two_sum_sorted</span>(arr, <span class="number">12</span>))
<span class="comment"># [0, 4] (arr[0] + arr[4] = 1 + 11 = 12)</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">twoSumSorted</span>(arr, target) {
<span class="comment">/**
* Find two numbers in sorted array
* that add up to target.
* Returns their indices.
*/</span>
<span class="keyword">let</span> left = <span class="number">0</span>;
<span class="keyword">let</span> right = arr.<span class="function">length</span> - <span class="number">1</span>;
<span class="keyword">while</span> (left < right) {
<span class="keyword">const</span> sum = arr[left] + arr[right];
<span class="keyword">if</span> (sum === target) {
<span class="keyword">return</span> [left, right];
} <span class="keyword">else if</span> (sum < target) {
left++; <span class="comment">// Need bigger sum</span>
} <span class="keyword">else</span> {
right--; <span class="comment">// Need smaller sum</span>
}
}
<span class="keyword">return</span> []; <span class="comment">// No pair found</span>
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">11</span>, <span class="number">15</span>];
console.<span class="function">log</span>(<span class="function">twoSumSorted</span>(arr, <span class="number">12</span>));
<span class="comment">// [0, 4] (arr[0] + arr[4] = 1 + 11 = 12)</span></code></pre>
</div>
<div class="formula-box">
Two Pointers Complexity: Time O(n) | Space O(1)
</div>
<div class="formula-box">
<strong>Two Pointers -- Variant Decision Rule:</strong><br><br>
• <strong>Converging (left/right):</strong> Array is sorted AND you need pairs that satisfy a condition → O(n)<br>
• <strong>Same direction (fast/slow):</strong> Partition, filter, or remove in-place → O(n)<br>
• <strong>Sliding Window (special case):</strong> Contiguous subarray/substring with constraint → O(n)<br><br>
<strong>Key rule:</strong> arr[i:j] slicing in Python creates a new array and is O(j-i), not O(1).
</div>
<!-- Sliding Window -->
<h3 id="sliding-window">Sliding Window</h3>
<p>
The <strong>sliding window</strong> technique maintains a "window" (a contiguous sub-array) that slides across the array. Instead of recomputing the entire window from scratch at every position, you add the new element entering the window and remove the element leaving it. This turns O(n*k) brute-force into O(n).
</p>
<div class="formula-box">
When to use Sliding Window:
- Problem involves contiguous sub-arrays/substrings
- You need to find max/min sum of size k
- You need longest/shortest sub-array with some property
- Fixed window: size k is given
- Variable window: find optimal size that satisfies condition
</div>
<p><strong>Example: Maximum Sum Subarray of Size k</strong></p>
<p>Given an array and a window size k, find the maximum sum of any contiguous subarray of length k.</p>
<div class="example-box">
<div class="label">Walkthrough</div>
<p><code>arr = [2, 1, 5, 1, 3, 2]</code>, <code>k = 3</code></p>
<p>Window [2, 1, 5] = 8</p>
<p>Slide: remove 2, add 1 --> [1, 5, 1] = 7</p>
<p>Slide: remove 1, add 3 --> [5, 1, 3] = 9</p>
<p>Slide: remove 5, add 2 --> [1, 3, 2] = 6</p>
<p>Maximum sum = 9</p>
</div>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">max_sum_subarray</span>(arr, k):
<span class="string">"""
Find maximum sum of any contiguous
subarray of size k.
"""</span>
<span class="keyword">if</span> <span class="builtin">len</span>(arr) < k:
<span class="keyword">return</span> <span class="number">0</span>
<span class="comment"># Calculate sum of first window</span>
window_sum = <span class="builtin">sum</span>(arr[:k])
max_sum = window_sum
<span class="comment"># Slide the window</span>
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(k, <span class="builtin">len</span>(arr)):
<span class="comment"># Add new element, remove old</span>
window_sum += arr[i] - arr[i - k]
max_sum = <span class="builtin">max</span>(max_sum, window_sum)
<span class="keyword">return</span> max_sum
<span class="comment"># Usage</span>
arr = [<span class="number">2</span>, <span class="number">1</span>, <span class="number">5</span>, <span class="number">1</span>, <span class="number">3</span>, <span class="number">2</span>]
<span class="builtin">print</span>(<span class="function">max_sum_subarray</span>(arr, <span class="number">3</span>))
<span class="comment"># 9 (subarray [5, 1, 3])</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">maxSumSubarray</span>(arr, k) {
<span class="comment">/**
* Find maximum sum of any contiguous
* subarray of size k.
*/</span>
<span class="keyword">if</span> (arr.<span class="function">length</span> < k) <span class="keyword">return</span> <span class="number">0</span>;
<span class="comment">// Calculate sum of first window</span>
<span class="keyword">let</span> windowSum = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < k; i++) {
windowSum += arr[i];
}
<span class="keyword">let</span> maxSum = windowSum;
<span class="comment">// Slide the window</span>
<span class="keyword">for</span> (<span class="keyword">let</span> i = k; i < arr.<span class="function">length</span>; i++) {
<span class="comment">// Add new element, remove old</span>
windowSum += arr[i] - arr[i - k];
maxSum = Math.<span class="function">max</span>(maxSum, windowSum);
}
<span class="keyword">return</span> maxSum;
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> arr = [<span class="number">2</span>, <span class="number">1</span>, <span class="number">5</span>, <span class="number">1</span>, <span class="number">3</span>, <span class="number">2</span>];
console.<span class="function">log</span>(<span class="function">maxSumSubarray</span>(arr, <span class="number">3</span>));
<span class="comment">// 9 (subarray [5, 1, 3])</span></code></pre>
</div>
<div class="formula-box">
Sliding Window Complexity: Time O(n) | Space O(1)
</div>
<!-- Prefix Sum -->
<h3 id="prefix-sum">Prefix Sum</h3>
<p>
A <strong>prefix sum</strong> array stores the cumulative sum up to each index. Once built (O(n) time), you can answer any "sum of elements from index i to j" query in O(1) time. Without prefix sums, each range sum query would take O(n).
</p>
<div class="formula-box">
prefix[0] = 0
prefix[i] = arr[0] + arr[1] + ... + arr[i-1]
sum(arr[i..j]) = prefix[j+1] - prefix[i]
</div>
<div class="example-box">
<div class="label">Walkthrough</div>
<p><code>arr = [2, 4, 6, 8, 10]</code></p>
<p><code>prefix = [0, 2, 6, 12, 20, 30]</code></p>
<p>Sum from index 1 to 3 = prefix[4] - prefix[1] = 20 - 2 = 18</p>
<p>Verify: arr[1] + arr[2] + arr[3] = 4 + 6 + 8 = 18</p>
</div>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">build_prefix_sum</span>(arr):
<span class="string">"""Build prefix sum array."""</span>
prefix = [<span class="number">0</span>] * (<span class="builtin">len</span>(arr) + <span class="number">1</span>)
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(<span class="builtin">len</span>(arr)):
prefix[i + <span class="number">1</span>] = prefix[i] + arr[i]
<span class="keyword">return</span> prefix
<span class="keyword">def</span> <span class="function">range_sum</span>(prefix, i, j):
<span class="string">"""Sum of arr[i..j] in O(1)."""</span>
<span class="keyword">return</span> prefix[j + <span class="number">1</span>] - prefix[i]
<span class="comment"># Usage</span>
arr = [<span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">8</span>, <span class="number">10</span>]
prefix = <span class="function">build_prefix_sum</span>(arr)
<span class="comment"># prefix = [0, 2, 6, 12, 20, 30]</span>
<span class="builtin">print</span>(<span class="function">range_sum</span>(prefix, <span class="number">1</span>, <span class="number">3</span>))
<span class="comment"># 18 (4 + 6 + 8)</span>
<span class="builtin">print</span>(<span class="function">range_sum</span>(prefix, <span class="number">0</span>, <span class="number">4</span>))
<span class="comment"># 30 (2 + 4 + 6 + 8 + 10)</span>
<span class="builtin">print</span>(<span class="function">range_sum</span>(prefix, <span class="number">2</span>, <span class="number">2</span>))
<span class="comment"># 6 (just arr[2])</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">buildPrefixSum</span>(arr) {
<span class="comment">/** Build prefix sum array. */</span>
<span class="keyword">const</span> prefix = <span class="keyword">new</span> <span class="builtin">Array</span>(arr.<span class="function">length</span> + <span class="number">1</span>).<span class="function">fill</span>(<span class="number">0</span>);
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < arr.<span class="function">length</span>; i++) {
prefix[i + <span class="number">1</span>] = prefix[i] + arr[i];
}
<span class="keyword">return</span> prefix;
}
<span class="keyword">function</span> <span class="function">rangeSum</span>(prefix, i, j) {
<span class="comment">/** Sum of arr[i..j] in O(1). */</span>
<span class="keyword">return</span> prefix[j + <span class="number">1</span>] - prefix[i];
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> arr = [<span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">8</span>, <span class="number">10</span>];
<span class="keyword">const</span> prefix = <span class="function">buildPrefixSum</span>(arr);
<span class="comment">// prefix = [0, 2, 6, 12, 20, 30]</span>
console.<span class="function">log</span>(<span class="function">rangeSum</span>(prefix, <span class="number">1</span>, <span class="number">3</span>));
<span class="comment">// 18 (4 + 6 + 8)</span>
console.<span class="function">log</span>(<span class="function">rangeSum</span>(prefix, <span class="number">0</span>, <span class="number">4</span>));
<span class="comment">// 30 (2 + 4 + 6 + 8 + 10)</span>
console.<span class="function">log</span>(<span class="function">rangeSum</span>(prefix, <span class="number">2</span>, <span class="number">2</span>));
<span class="comment">// 6 (just arr[2])</span></code></pre>
</div>
<div class="formula-box">
Prefix Sum Complexity:
Build: O(n) time, O(n) space
Each query: O(1) time
Total for q queries: O(n + q) vs O(n * q) brute force
</div>
<div class="tip-box">
<div class="label">Tip</div>
<p>Prefix sums appear in disguise in many problems. Anytime you see "sum of subarray" or "range query," think prefix sums. The technique extends to 2D arrays (prefix sum matrices) for submatrix sum queries.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 5: Strings -->
<!-- ============================================================ -->
<section id="strings">
<h2>5. Strings</h2>
<h3>Strings as Arrays of Characters</h3>
<p>
A string is essentially a sequence (array) of characters. You can index into a string, iterate over it, and slice it just like an array. However, strings have one critical difference in both Python and JavaScript: they are <strong>immutable</strong>.
</p>
<div class="warning-box">
<div class="label">Immutability</div>
<p>In both Python and JavaScript, strings <strong>cannot be modified in-place</strong>. Every "modification" creates a new string. This means string concatenation in a loop is O(n^2) because each concatenation creates a new string and copies all previous characters.</p>
</div>
<div class="code-pair">
<pre><code><span class="lang-label">Python</span>
s = <span class="string">"hello"</span>
<span class="comment"># Strings are immutable</span>
<span class="comment"># s[0] = "H" # TypeError!</span>
<span class="comment"># Index access (just like arrays)</span>
first = s[<span class="number">0</span>] <span class="comment"># "h"</span>
last = s[-<span class="number">1</span>] <span class="comment"># "o"</span>
<span class="comment"># Iterate like an array</span>
<span class="keyword">for</span> char <span class="keyword">in</span> s:
<span class="builtin">print</span>(char)
<span class="comment"># To "modify," convert to list first</span>
chars = <span class="builtin">list</span>(s) <span class="comment"># ['h','e','l','l','o']</span>
chars[<span class="number">0</span>] = <span class="string">"H"</span>
s = <span class="string">""</span>.<span class="function">join</span>(chars) <span class="comment"># "Hello"</span>
<span class="comment"># Efficient concatenation: use join</span>
parts = [<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>]
result = <span class="string">""</span>.<span class="function">join</span>(parts) <span class="comment"># "abc" -- O(n)</span></code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> s = <span class="string">"hello"</span>;
<span class="comment">// Strings are immutable</span>
<span class="comment">// s[0] = "H"; // Silently fails!</span>
<span class="comment">// Index access (just like arrays)</span>
<span class="keyword">const</span> first = s[<span class="number">0</span>]; <span class="comment">// "h"</span>
<span class="keyword">const</span> last = s[s.<span class="function">length</span> - <span class="number">1</span>]; <span class="comment">// "o"</span>
<span class="comment">// Iterate like an array</span>
<span class="keyword">for</span> (<span class="keyword">const</span> char <span class="keyword">of</span> s) {
console.<span class="function">log</span>(char);
}
<span class="comment">// To "modify," convert to array first</span>
<span class="keyword">const</span> chars = s.<span class="function">split</span>(<span class="string">""</span>);
chars[<span class="number">0</span>] = <span class="string">"H"</span>;
<span class="keyword">const</span> newS = chars.<span class="function">join</span>(<span class="string">""</span>); <span class="comment">// "Hello"</span>
<span class="comment">// Efficient concatenation: use join</span>
<span class="keyword">const</span> parts = [<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>];
<span class="keyword">const</span> result = parts.<span class="function">join</span>(<span class="string">""</span>); <span class="comment">// "abc"</span></code></pre>
</div>