-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithms.html
More file actions
1286 lines (1148 loc) · 51.1 KB
/
algorithms.html
File metadata and controls
1286 lines (1148 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Algorithms - Interview Preparation & Coding Challenges</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
'edu-blue': '#3B82F6',
'edu-green': '#10B981',
'edu-purple': '#8B5CF6',
'edu-yellow': '#F59E0B',
'edu-bg': '#F9FAFB',
'edu-text': '#374151'
}
}
}
}
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
<link rel="stylesheet" href="css/educational-theme.css">
<style>
.algorithm-card {
transition: all 0.3s ease;
cursor: pointer;
}
.algorithm-card:hover {
transform: translateY(-3px);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}
.complexity-low {
background: linear-gradient(135deg, #10B981, #34D399);
}
.complexity-medium {
background: linear-gradient(135deg, #F59E0B, #FBBF24);
}
.complexity-high {
background: linear-gradient(135deg, #EF4444, #F87171);
}
.code-editor {
background: #1F2937;
border: 1px solid #374151;
border-radius: 8px;
padding: 1rem;
font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
color: #F9FAFB;
resize: vertical;
min-height: 300px;
width: 100%;
}
.output-panel {
background: #111827;
border: 1px solid #374151;
border-radius: 8px;
padding: 1rem;
font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
color: #10B981;
min-height: 200px;
overflow-y: auto;
white-space: pre-wrap;
}
.algorithm-modal {
display: none;
}
.algorithm-modal.active {
display: flex;
}
.complexity-badge {
font-size: 0.75rem;
padding: 0.25rem 0.75rem;
border-radius: 9999px;
font-weight: 500;
}
.step-item {
background: #F3F4F6;
border-left: 4px solid #3B82F6;
padding: 1rem;
margin: 0.5rem 0;
border-radius: 0 0.5rem 0.5rem 0;
}
.tab-button {
padding: 0.5rem 1rem;
border-radius: 0.5rem 0.5rem 0 0;
border: none;
background: #E5E7EB;
color: #6B7280;
cursor: pointer;
transition: all 0.2s;
}
.tab-button.active {
background: #3B82F6;
color: white;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.interview-tip {
background: linear-gradient(135deg, #FEF3C7, #FDE68A);
border: 1px solid #F59E0B;
border-radius: 0.5rem;
padding: 1rem;
margin: 1rem 0;
}
.time-complexity {
background: #DBEAFE;
color: #1E40AF;
padding: 0.5rem;
border-radius: 0.375rem;
font-family: monospace;
font-size: 0.875rem;
}
.space-complexity {
background: #D1FAE5;
color: #065F46;
padding: 0.5rem;
border-radius: 0.375rem;
font-family: monospace;
font-size: 0.875rem;
}
</style>
</head>
<body class="bg-edu-bg text-edu-text">
<!-- Navigation -->
<nav class="bg-white shadow-lg fixed w-full z-50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<div class="flex-shrink-0 flex items-center">
<a href="index.html" class="flex items-center">
<span class="text-2xl font-bold text-edu-blue">JS</span>
<span class="text-2xl font-bold text-edu-purple ml-1">Learning Hub</span>
</a>
</div>
</div>
<div class="hidden md:flex items-center space-x-8">
<a href="index.html" class="text-gray-700 hover:text-edu-blue transition-colors">Home</a>
<a href="lessons.html" class="text-gray-700 hover:text-edu-blue transition-colors">Lessons</a>
<a href="playground.html" class="text-gray-700 hover:text-edu-blue transition-colors">Playground</a>
<a href="algorithms.html" class="text-edu-blue font-semibold">Algorithms</a>
<a href="exercises.html" class="text-gray-700 hover:text-edu-blue transition-colors">Exercises</a>
</div>
</div>
</div>
</nav>
<!-- Header -->
<section class="pt-20 pb-12 bg-gradient-to-r from-edu-blue to-edu-purple">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center text-white">
<h1 class="text-4xl md:text-5xl font-bold mb-4">JavaScript Algorithms</h1>
<p class="text-xl opacity-90 max-w-3xl mx-auto mb-6">
Master essential algorithms and data structures for coding interviews and real-world programming
challenges.
</p>
<div class="bg-white bg-opacity-10 rounded-lg p-6 max-w-4xl mx-auto">
<div class="grid md:grid-cols-3 gap-6 text-center">
<div>
<div class="text-3xl font-bold text-edu-yellow">25+</div>
<div class="text-sm opacity-90">Algorithm Implementations</div>
</div>
<div>
<div class="text-3xl font-bold text-edu-green">100%</div>
<div class="text-sm opacity-90">Interview Ready</div>
</div>
<div>
<div class="text-3xl font-bold text-white">O(n)</div>
<div class="text-sm opacity-90">Complexity Analysis</div>
</div>
</div>
</div>
</div>
</section>
<!-- Filter Section -->
<section class="py-8 bg-white border-b border-gray-200">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex flex-wrap items-center justify-between gap-4">
<div class="flex flex-wrap gap-3">
<button onclick="filterAlgorithms('all')"
class="filter-btn active px-4 py-2 rounded-lg border border-gray-300 bg-edu-blue text-white font-medium">
All Algorithms
</button>
<button onclick="filterAlgorithms('sorting')"
class="filter-btn px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
Sorting
</button>
<button onclick="filterAlgorithms('searching')"
class="filter-btn px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
Searching
</button>
<button onclick="filterAlgorithms('array')"
class="filter-btn px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
Array
</button>
<button onclick="filterAlgorithms('string')"
class="filter-btn px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
String
</button>
<button onclick="filterAlgorithms('tree')"
class="filter-btn px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
Tree
</button>
<button onclick="filterAlgorithms('dynamic')"
class="filter-btn px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
Dynamic Programming
</button>
</div>
<div class="flex items-center gap-3">
<span class="text-sm text-gray-600">Sort by:</span>
<select id="sort-select" onchange="sortAlgorithms()"
class="border border-gray-300 rounded px-3 py-1 text-sm">
<option value="name">Algorithm Name</option>
<option value="complexity">Time Complexity</option>
<option value="difficulty">Difficulty</option>
<option value="category">Category</option>
</select>
</div>
</div>
</div>
</section>
<!-- Algorithms Grid -->
<section class="py-16">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6" id="algorithms-grid">
<!-- Algorithms will be populated by JavaScript -->
</div>
</div>
</section>
<!-- Algorithm Modal -->
<div id="algorithm-modal"
class="algorithm-modal fixed inset-0 bg-black bg-opacity-50 items-center justify-center z-50">
<div class="bg-white rounded-lg max-w-7xl w-full mx-4 max-h-screen overflow-y-auto">
<!-- Modal Header -->
<div class="p-6 border-b border-gray-200 flex justify-between items-center">
<div>
<h2 id="modal-title" class="text-2xl font-bold text-gray-900"></h2>
<div class="flex items-center gap-3 mt-2">
<span id="modal-category"
class="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm font-medium"></span>
<span id="modal-time-complexity" class="time-complexity"></span>
<span id="modal-space-complexity" class="space-complexity"></span>
</div>
</div>
<button id="close-modal" class="text-gray-500 hover:text-gray-700">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12">
</path>
</svg>
</button>
</div>
<!-- Modal Content -->
<div class="p-6">
<!-- Tab Navigation -->
<div class="flex border-b border-gray-200 mb-6">
<button onclick="showTab('overview')" class="tab-button active" id="overview-tab">
📖 Overview
</button>
<button onclick="showTab('implementation')" class="tab-button" id="implementation-tab">
💻 Implementation
</button>
<button onclick="showTab('examples')" class="tab-button" id="examples-tab">
🔍 Examples
</button>
<button onclick="showTab('interview')" class="tab-button" id="interview-tab">
🎯 Interview Tips
</button>
</div>
<!-- Tab Content -->
<div id="overview-content" class="tab-content active">
<div class="grid lg:grid-cols-2 gap-6">
<div>
<h3 class="text-lg font-semibold mb-3">📋 Algorithm Description</h3>
<div id="modal-description" class="text-gray-600 leading-relaxed mb-6"></div>
<h3 class="text-lg font-semibold mb-3">⚡ How It Works</h3>
<div id="modal-steps" class="space-y-2"></div>
</div>
<div>
<h3 class="text-lg font-semibold mb-3">📊 Complexity Analysis</h3>
<div class="space-y-4 mb-6">
<div>
<div class="font-medium text-sm text-gray-700 mb-1">Time Complexity</div>
<div id="modal-time-analysis" class="time-complexity"></div>
</div>
<div>
<div class="font-medium text-sm text-gray-700 mb-1">Space Complexity</div>
<div id="modal-space-analysis" class="space-complexity"></div>
</div>
</div>
<h3 class="text-lg font-semibold mb-3">✅ Use Cases</h3>
<div id="modal-use-cases" class="space-y-2"></div>
</div>
</div>
</div>
<div id="implementation-content" class="tab-content">
<div class="grid lg:grid-cols-2 gap-6">
<div>
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-semibold">💻 Implementation</h3>
<div class="flex gap-2">
<button onclick="runAlgorithm()"
class="px-3 py-1 text-sm bg-edu-green text-white rounded hover:bg-green-600 transition-colors">
▶ Run Code
</button>
<button onclick="resetImplementation()"
class="px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 rounded transition-colors">
🔄 Reset
</button>
</div>
</div>
<textarea id="code-editor" class="code-editor"
placeholder="Algorithm implementation will appear here..."></textarea>
</div>
<div>
<h3 class="text-lg font-semibold mb-3">📊 Output & Visualization</h3>
<div id="output-panel" class="output-panel mb-4">
Click "Run Code" to see the algorithm in action.
</div>
<div id="visual-panel" class="hidden">
<h4 class="font-semibold mb-2">🎨 Visualization</h4>
<div id="visualization"
class="bg-gray-50 border rounded p-4 min-h-[150px] flex items-center justify-center">
Visual representation will appear here
</div>
</div>
</div>
</div>
</div>
<div id="examples-content" class="tab-content">
<h3 class="text-lg font-semibold mb-4">🔍 Practical Examples</h3>
<div id="modal-examples" class="space-y-4"></div>
</div>
<div id="interview-content" class="tab-content">
<div class="space-y-6">
<div class="interview-tip">
<h4 class="font-semibold text-amber-800 mb-2">💡 Interview Strategy</h4>
<div id="modal-interview-strategy"></div>
</div>
<div>
<h4 class="text-lg font-semibold mb-3">❓ Common Interview Questions</h4>
<div id="modal-interview-questions" class="space-y-2"></div>
</div>
<div>
<h4 class="text-lg font-semibold mb-3">🎯 Follow-up Questions</h4>
<div id="modal-followup-questions" class="space-y-2"></div>
</div>
<div>
<h4 class="text-lg font-semibold mb-3">🔧 Optimization Tips</h4>
<div id="modal-optimization-tips" class="space-y-2"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
<script>
// Algorithm data for JavaScript interview preparation
const algorithms = [
{
id: 'bubble-sort',
name: 'Bubble Sort',
category: 'sorting',
difficulty: 'easy',
timeComplexity: 'O(n²)',
spaceComplexity: 'O(1)',
description: 'A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.',
steps: [
'Compare adjacent elements in the array',
'Swap them if they are in wrong order',
'Continue through the array until no swaps are needed',
'Repeat the process for each element'
],
useCases: [
'Educational purposes - easy to understand',
'Small datasets where simplicity is preferred',
'When memory space is extremely limited'
],
implementation: `function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
// Track if any swaps were made
let swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
swapped = true;
}
}
// If no swaps were made, array is sorted
if (!swapped) break;
}
return arr;
}
// Example usage
const numbers = [64, 34, 25, 12, 22, 11, 90];
console.log("Original array:", numbers);
console.log("Sorted array:", bubbleSort([...numbers]));`,
examples: [
{
input: '[64, 34, 25, 12, 22, 11, 90]',
output: '[11, 12, 22, 25, 34, 64, 90]',
explanation: 'Each pass bubbles the largest unsorted element to its correct position'
},
{
input: '[5, 2, 8, 1, 9]',
output: '[1, 2, 5, 8, 9]',
explanation: 'Multiple passes ensure all elements are in correct order'
}
],
interviewStrategy: 'Start by explaining the concept, then write the basic implementation. Mention the optimization of stopping early if no swaps occur.',
interviewQuestions: [
'Implement bubble sort and explain its time complexity',
'How can you optimize bubble sort?',
'When would you use bubble sort over other sorting algorithms?'
],
followupQuestions: [
'What is the best case time complexity?',
'How does bubble sort compare to selection sort?',
'Can you make it stable? Is it in-place?'
],
optimizationTips: [
'Add early termination when no swaps occur',
'Reduce the range in each iteration',
'Consider using a different algorithm for larger datasets'
]
},
{
id: 'binary-search',
name: 'Binary Search',
category: 'searching',
difficulty: 'medium',
timeComplexity: 'O(log n)',
spaceComplexity: 'O(1)',
description: 'An efficient searching algorithm that finds the position of a target value within a sorted array by repeatedly dividing the search interval in half.',
steps: [
'Start with the middle element of the sorted array',
'If target equals middle element, return the index',
'If target is less than middle, search the left half',
'If target is greater than middle, search the right half',
'Repeat until target is found or search space is empty'
],
useCases: [
'Searching in sorted arrays or lists',
'Finding insertion points in sorted data',
'Implementing efficient search in databases',
'Finding peaks, valleys, or boundaries in data'
],
implementation: `function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid; // Found the target
}
if (arr[mid] < target) {
left = mid + 1; // Search right half
} else {
right = mid - 1; // Search left half
}
}
return -1; // Target not found
}
// Recursive implementation
function binarySearchRecursive(arr, target, left = 0, right = arr.length - 1) {
if (left > right) {
return -1; // Base case: not found
}
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
return binarySearchRecursive(arr, target, mid + 1, right);
} else {
return binarySearchRecursive(arr, target, left, mid - 1);
}
}
// Example usage
const sortedArray = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
console.log("Array:", sortedArray);
console.log("Search for 7:", binarySearch(sortedArray, 7));
console.log("Search for 4:", binarySearch(sortedArray, 4));`,
examples: [
{
input: 'arr = [1, 3, 5, 7, 9, 11, 13], target = 7',
output: '3 (index)',
explanation: 'Found at index 3 after checking middle elements'
},
{
input: 'arr = [1, 3, 5, 7, 9, 11, 13], target = 4',
output: '-1 (not found)',
explanation: 'Target not in array, returns -1'
}
],
interviewStrategy: 'Emphasize the requirement of sorted data. Explain both iterative and recursive approaches. Discuss edge cases.',
interviewQuestions: [
'Implement binary search iteratively and recursively',
'What is the prerequisite for binary search?',
'How do you handle duplicate elements?'
],
followupQuestions: [
'Find the first/last occurrence of a target',
'Find the insertion point for a target',
'Search in a rotated sorted array'
],
optimizationTips: [
'Use iterative approach to avoid stack overflow',
'Handle integer overflow in mid calculation',
'Consider boundary conditions carefully'
]
},
{
id: 'two-sum',
name: 'Two Sum',
category: 'array',
difficulty: 'easy',
timeComplexity: 'O(n)',
spaceComplexity: 'O(n)',
description: 'Find two numbers in an array that add up to a specific target sum. Return their indices.',
steps: [
'Create a hash map to store numbers and their indices',
'Iterate through the array',
'For each number, calculate the complement (target - current)',
'Check if complement exists in hash map',
'If found, return the indices; otherwise, add current number to map'
],
useCases: [
'Finding pairs that meet certain criteria',
'Solving subset sum problems',
'Building blocks for more complex algorithms',
'Common interview question foundation'
],
implementation: `function twoSum(nums, target) {
const numMap = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (numMap.has(complement)) {
return [numMap.get(complement), i];
}
numMap.set(nums[i], i);
}
return []; // No solution found
}
// Alternative: Brute force approach (O(n²))
function twoSumBruteForce(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return [];
}
// For sorted array: Two pointers approach
function twoSumSorted(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const sum = nums[left] + nums[right];
if (sum === target) {
return [left, right];
} else if (sum < target) {
left++;
} else {
right--;
}
}
return [];
}
// Example usage
const numbers = [2, 7, 11, 15];
const target = 9;
console.log("Array:", numbers);
console.log("Target:", target);
console.log("Result:", twoSum(numbers, target));`,
examples: [
{
input: 'nums = [2, 7, 11, 15], target = 9',
output: '[0, 1]',
explanation: 'nums[0] + nums[1] = 2 + 7 = 9'
},
{
input: 'nums = [3, 2, 4], target = 6',
output: '[1, 2]',
explanation: 'nums[1] + nums[2] = 2 + 4 = 6'
}
],
interviewStrategy: 'Start with brute force, then optimize using hash map. Explain trade-offs between time and space complexity.',
interviewQuestions: [
'Find two numbers that sum to target',
'What if there are multiple solutions?',
'How would you handle edge cases?'
],
followupQuestions: [
'Three Sum problem',
'Two Sum in sorted array',
'Two Sum with specific constraints'
],
optimizationTips: [
'Use hash map for O(n) solution',
'Consider two pointers for sorted arrays',
'Handle duplicate values carefully'
]
},
{
id: 'fibonacci',
name: 'Fibonacci Sequence',
category: 'dynamic',
difficulty: 'medium',
timeComplexity: 'O(n)',
spaceComplexity: 'O(1)',
description: 'Generate the Fibonacci sequence where each number is the sum of the two preceding ones, starting from 0 and 1.',
steps: [
'Start with base cases: F(0) = 0, F(1) = 1',
'For each subsequent number, add the two previous numbers',
'Continue until reaching the desired position',
'Optimize using iterative approach or memoization'
],
useCases: [
'Mathematical computations and modeling',
'Algorithm optimization examples',
'Dynamic programming introduction',
'Recursive vs iterative comparison'
],
implementation: `// Iterative approach (most efficient)
function fibonacci(n) {
if (n <= 1) return n;
let prev = 0;
let curr = 1;
for (let i = 2; i <= n; i++) {
const temp = curr;
curr = prev + curr;
prev = temp;
}
return curr;
}
// Recursive approach (naive - exponential time)
function fibonacciRecursive(n) {
if (n <= 1) return n;
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
// Memoized recursive approach
function fibonacciMemo(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) return n;
memo[n] = fibonacciMemo(n - 1, memo) + fibonacciMemo(n - 2, memo);
return memo[n];
}
// Generate Fibonacci sequence up to n terms
function fibonacciSequence(n) {
const sequence = [];
for (let i = 0; i < n; i++) {
sequence.push(fibonacci(i));
}
return sequence;
}
// Example usage
console.log("F(10):", fibonacci(10));
console.log("First 10 Fibonacci numbers:", fibonacciSequence(10));
// Performance comparison
console.time("Iterative");
console.log("F(40) iterative:", fibonacci(40));
console.timeEnd("Iterative");
console.time("Memoized");
console.log("F(40) memoized:", fibonacciMemo(40));
console.timeEnd("Memoized");`,
examples: [
{
input: 'n = 10',
output: '55',
explanation: 'The 10th Fibonacci number is 55'
},
{
input: 'sequence(8)',
output: '[0, 1, 1, 2, 3, 5, 8, 13]',
explanation: 'First 8 Fibonacci numbers'
}
],
interviewStrategy: 'Discuss different approaches: recursive, iterative, and memoized. Explain time complexities and trade-offs.',
interviewQuestions: [
'Calculate the nth Fibonacci number',
'Optimize recursive Fibonacci implementation',
'Generate Fibonacci sequence up to n terms'
],
followupQuestions: [
'Check if a number is in Fibonacci sequence',
'Find Fibonacci numbers in a given range',
'Calculate Fibonacci modulo some number'
],
optimizationTips: [
'Use iterative approach for best performance',
'Implement memoization for recursive solutions',
'Consider matrix exponentiation for very large n'
]
},
{
id: 'palindrome',
name: 'Palindrome Check',
category: 'string',
difficulty: 'easy',
timeComplexity: 'O(n)',
spaceComplexity: 'O(1)',
description: 'Check if a string reads the same forwards and backwards, ignoring spaces, punctuation, and case.',
steps: [
'Clean the string by removing non-alphanumeric characters',
'Convert to lowercase for case-insensitive comparison',
'Use two pointers from start and end',
'Compare characters moving towards center',
'Return false if any mismatch, true if all match'
],
useCases: [
'Text processing and validation',
'Data structure problems (linked lists, arrays)',
'String manipulation algorithms',
'Interview coding challenges'
],
implementation: `function isPalindrome(s) {
// Clean string: remove non-alphanumeric and convert to lowercase
const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, '');
let left = 0;
let right = cleaned.length - 1;
while (left < right) {
if (cleaned[left] !== cleaned[right]) {
return false;
}
left++;
right--;
}
return true;
}
// Alternative: Compare with reversed string
function isPalindromeReverse(s) {
const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleaned === cleaned.split('').reverse().join('');
}
// For arrays/numbers
function isPalindromeArray(arr) {
let left = 0;
let right = arr.length - 1;
while (left < right) {
if (arr[left] !== arr[right]) {
return false;
}
left++;
right--;
}
return true;
}
// Check if number is palindrome
function isPalindromeNumber(num) {
const str = num.toString();
return isPalindromeArray(str.split(''));
}
// Example usage
console.log('isPalindrome("A man a plan a canal Panama"):', isPalindrome("A man a plan a canal Panama"));
console.log('isPalindrome("race a car"):', isPalindrome("race a car"));
console.log('isPalindromeNumber(121):', isPalindromeNumber(121));
console.log('isPalindromeArray([1,2,3,2,1]):', isPalindromeArray([1,2,3,2,1]));`,
examples: [
{
input: '"A man a plan a canal Panama"',
output: 'true',
explanation: 'Ignoring spaces and case: "amanaplanacanalpanama"'
},
{
input: '"race a car"',
output: 'false',
explanation: 'Cleaned string "raceacar" is not a palindrome'
}
],
interviewStrategy: 'Clarify requirements (case sensitivity, special characters). Show two-pointer technique and discuss alternatives.',
interviewQuestions: [
'Check if string is palindrome',
'Find longest palindromic substring',
'Check if number is palindrome without string conversion'
],
followupQuestions: [
'Valid palindrome after deleting one character',
'Count palindromic substrings',
'Check palindrome in linked list'
],
optimizationTips: [
'Use two pointers for O(1) space',
'Consider in-place character checking',
'Optimize string cleaning process'
]
},
{
id: 'reverse-string',
name: 'Reverse String',
category: 'string',
difficulty: 'easy',
timeComplexity: 'O(n)',
spaceComplexity: 'O(1)',
description: 'Reverse a string in-place using various techniques like two pointers, recursion, or built-in methods.',
steps: [
'Convert string to array if needed (strings are immutable)',
'Use two pointers: one at start, one at end',
'Swap characters at these positions',
'Move pointers towards center',
'Continue until pointers meet'
],
useCases: [
'String manipulation exercises',
'Data preprocessing',
'Algorithm building blocks',
'Technical interview preparation'
],
implementation: `// Method 1: Built-in methods (simplest)
function reverseString1(s) {
return s.split('').reverse().join('');
}
// Method 2: Two pointers (in-place for arrays)
function reverseString2(s) {
const arr = s.split('');
let left = 0;
let right = arr.length - 1;
while (left < right) {
// Swap characters
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
return arr.join('');
}
// Method 3: Recursion
function reverseString3(s) {
// Base case
if (s.length <= 1) return s;
// Recursive case
return s[s.length - 1] + reverseString3(s.slice(0, -1));
}
// Method 4: Iterative building
function reverseString4(s) {
let reversed = '';
for (let i = s.length - 1; i >= 0; i--) {
reversed += s[i];
}
return reversed;
}
// Method 5: Using reduce
function reverseString5(s) {
return s.split('').reduce((reversed, char) => char + reversed, '');
}
// For array of characters (in-place)
function reverseCharArray(s) {
let left = 0;
let right = s.length - 1;
while (left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
return s;
}
// Example usage
const testString = "hello world";
console.log("Original:", testString);
console.log("Method 1:", reverseString1(testString));
console.log("Method 2:", reverseString2(testString));
console.log("Method 3:", reverseString3(testString));
console.log("Method 4:", reverseString4(testString));
console.log("Method 5:", reverseString5(testString));
// Performance test
const longString = "a".repeat(100000);
console.time("Built-in methods");
reverseString1(longString);
console.timeEnd("Built-in methods");
console.time("Two pointers");
reverseString2(longString);
console.timeEnd("Two pointers");`,
examples: [
{
input: '"hello"',
output: '"olleh"',
explanation: 'Each character position is swapped with its mirror'
},
{
input: '"JavaScript"',
output: '"tpircSavaJ"',
explanation: 'String reversed character by character'
}
],
interviewStrategy: 'Show multiple approaches. Discuss in-place vs new string creation. Consider performance implications.',
interviewQuestions: [
'Reverse a string using different methods',
'Reverse string in-place (character array)',
'Reverse words in a sentence'
],
followupQuestions: [
'Reverse only vowels in a string',
'Reverse string with special character preservation',
'Reverse each word in a sentence individually'
],
optimizationTips: [
'Use two pointers for space efficiency',
'Consider performance of string concatenation',
'Choose appropriate method based on constraints'
]