Repository navigation
Expand file tree
/
Copy pathleetcode-visualizer.html
More file actions
4505 lines (4264 loc) · 184 KB
/
Copy pathleetcode-visualizer.html
File metadata and controls
4505 lines (4264 loc) · 184 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>Algorithm Visualizer — real Python execution</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700;800&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{
--void:#090c11;
--panel:#10151d;
--panel-2:#141c27;
--inset:#0b0f16;
--line:#212b37;
--line-soft:#181f29;
--text-hi:#e9eff5;
--text-mid:#8ea0b2;
--text-dim:#4d5a68;
--accent:#3fe0c5;
--accent-dim:rgba(63,224,197,.13);
--accent-glow:rgba(63,224,197,.35);
--blue:#5b8def;
--blue-dim:rgba(91,141,239,.14);
--warn:#f0a93b;
--warn-dim:rgba(240,169,59,.14);
--danger:#ff6b6b;
--danger-dim:rgba(255,107,107,.14);
--violet:#a78bfa;
--violet-dim:rgba(167,139,250,.14);
--pink:#ff8fd6;
--font-mono:'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, monospace;
--font-sans:'Space Grotesk', ui-sans-serif, system-ui, sans-serif;
--ll-arrow:#5b8def;
}
*{box-sizing:border-box;}
html,body{height:100%;}
body{
margin:0; background:var(--void); color:var(--text-hi);
font-family:var(--font-sans); -webkit-font-smoothing:antialiased; overflow:hidden;
}
::selection{background:var(--accent-glow); color:#04140f;}
::-webkit-scrollbar{width:10px;height:10px;}
::-webkit-scrollbar-track{background:transparent;}
::-webkit-scrollbar-thumb{background:var(--line); border-radius:6px; border:2px solid var(--panel);}
::-webkit-scrollbar-thumb:hover{background:#2c3947;}
.stage{ display:flex; flex-direction:column; height:100vh; }
/* ---------- topbar ---------- */
.topbar{
display:flex; align-items:center; gap:16px; padding:10px 16px;
background:var(--panel); border-bottom:1px solid var(--line); flex-shrink:0;
}
.brand{ display:flex; align-items:center; gap:10px; }
.brand-badge{
width:34px;height:34px;border-radius:9px; background:linear-gradient(135deg,var(--accent),var(--blue));
display:flex;align-items:center;justify-content:center; font-weight:800; font-size:12px; color:#04140f;
}
.brand-text h1{ font-size:14px; margin:0; letter-spacing:.2px; }
.brand-text p{ font-size:11px; margin:0; color:var(--text-mid); }
.lang-chips{ display:flex; gap:6px; margin-left:8px; }
.lang-chip{
padding:6px 12px; border-radius:8px; font-size:12px; font-weight:600; cursor:pointer;
background:var(--panel-2); color:var(--text-mid); border:1px solid var(--line); position:relative;
}
.lang-chip.active{ background:var(--accent-dim); color:var(--accent); border-color:var(--accent); }
.lang-chip .beta-dot{
position:absolute; top:-4px; right:-4px; background:var(--warn); color:#241800; font-size:8px;
padding:1px 4px; border-radius:6px; font-weight:800;
}
.spacer{ flex:1; }
.run-btn{
display:flex; align-items:center; gap:8px; padding:9px 18px; border-radius:9px; border:none; cursor:pointer;
background:linear-gradient(135deg,var(--accent),#28c4ab); color:#04140f; font-weight:700; font-size:13px;
}
.run-btn:disabled{ opacity:.5; cursor:default; }
.run-btn:active{ transform:translateY(1px); }
/* ---------- main layout ---------- */
.main{ flex:1; display:flex; min-height:0; }
.panel{ display:flex; flex-direction:column; min-width:0; }
.panel-head{
display:flex; align-items:center; justify-content:space-between; padding:9px 14px;
border-bottom:1px solid var(--line); background:var(--panel); flex-shrink:0;
}
.panel-head .ph-title{ font-size:11px; letter-spacing:1.2px; color:var(--text-mid); font-weight:700; text-transform:uppercase; }
.panel-head .ph-meta{ font-size:11px; color:var(--text-dim); font-family:var(--font-mono); }
.col-source{ width:34%; border-right:1px solid var(--line); background:var(--inset); }
.col-trace{ width:27%; border-right:1px solid var(--line); background:var(--void); }
.col-viz{ flex:1; background:var(--void); }
/* ---------- source panel ---------- */
.source-edit-wrap{ position:relative; flex:1; min-height:0; overflow:hidden; }
.line-highlight-bar{
position:absolute; left:0; right:0; height:21px; display:none; pointer-events:none; z-index:1;
}
.line-highlight-bar.active{ background:var(--accent-dim); box-shadow:inset 3px 0 0 var(--accent); }
.line-highlight-bar.err{ background:var(--danger-dim); box-shadow:inset 3px 0 0 var(--danger); }
.source-edit{
position:relative; z-index:2; width:100%; height:100%; background:transparent; color:var(--text-hi); border:none; outline:none; resize:none;
font-family:var(--font-mono); font-size:12.5px; line-height:21px; padding:14px; tab-size:4; white-space:pre; overflow:auto;
}
.entry-bar{ padding:9px 14px; border-top:1px solid var(--line); background:var(--panel); font-family:var(--font-mono); font-size:11.5px; color:var(--text-mid); flex-shrink:0; }
.entry-bar b{ color:var(--accent); font-weight:600; }
.entry-bar input{
width:100%; margin-top:6px; background:var(--inset); border:1px solid var(--line); border-radius:6px; color:var(--text-hi);
padding:6px 9px; font-family:var(--font-mono); font-size:11.5px;
}
.live-row{ display:flex; align-items:center; gap:8px; padding:7px 14px; border-top:1px solid var(--line); background:var(--panel); font-size:11.5px; color:var(--text-mid); flex-shrink:0; }
.live-row label{ display:flex; align-items:center; gap:6px; cursor:pointer; user-select:none; }
.live-status{ margin-left:auto; font-family:var(--font-mono); font-size:11px; padding:2px 8px; border-radius:5px; background:var(--panel-2); }
.live-status.ok{ color:var(--accent); }
.live-status.pending{ color:var(--warn); }
.live-status.err{ color:var(--danger); }
/* ---------- trace panel ---------- */
.trace-scroll{ flex:1; overflow:auto; padding:10px; display:flex; flex-direction:column; gap:6px; }
.trace-card{
border:1px solid var(--line); border-radius:8px; padding:8px 10px; background:var(--panel);
font-family:var(--font-mono); font-size:11.5px; cursor:pointer;
}
.trace-card:hover{ border-color:var(--text-dim); }
.trace-card.current{ border-color:var(--accent); background:var(--accent-dim); box-shadow:0 0 0 1px var(--accent-glow); }
.trace-kind{ display:inline-block; font-size:9px; font-weight:800; letter-spacing:.6px; padding:2px 6px; border-radius:5px; margin-bottom:5px; }
.trace-desc{ color:var(--text-hi); line-height:1.4; word-break:break-word; }
.trace-line-no{ color:var(--text-dim); float:right; }
.k-ASSIGN{ background:var(--blue-dim); color:var(--blue); }
.k-IF_CHECK{ background:var(--violet-dim); color:var(--violet); }
.k-LOOP_START,.k-LOOP_CHECK,.k-LOOP_ITER{ background:var(--warn-dim); color:var(--warn); }
.k-PUSH,.k-POP,.k-SORT{ background:var(--accent-dim); color:var(--accent); }
.k-CALL,.k-RETURN{ background:rgba(255,143,214,.14); color:var(--pink); }
.k-BREAK,.k-CONTINUE{ background:var(--danger-dim); color:var(--danger); }
.k-EXPR{ background:var(--line-soft); color:var(--text-mid); }
/* ---------- viz panel ---------- */
.viz-scroll{ flex:1; overflow:auto; padding:18px; display:flex; flex-direction:column; gap:20px; }
.narration{
font-size:14px; text-align:center; color:var(--text-hi); font-weight:600; padding:10px 16px;
background:var(--panel-2); border:1px solid var(--line); border-radius:10px; min-height:20px;
flex-shrink:0;
}
.narration .nk{ color:var(--accent); }
/* flex-shrink:0 is the fix for the "graph panel disappears" bug: .viz-scroll is a
column flex container, and by default flex children shrink to fit rather than
overflow — with several blocks stacked (call stack, graph, visited, ...) the
browser would compress the largest one (usually the graph/tree/linked-list SVG)
down toward zero height instead of just letting .viz-scroll's own overflow:auto
scroll. Pinning every block to its natural size means nothing gets crushed —
the panel scrolls instead, exactly like the CSS overflow:auto already intended. */
.ds-block{ background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:14px 16px; flex-shrink:0; }
.ds-label{ font-size:10.5px; letter-spacing:1px; text-transform:uppercase; color:var(--text-mid); font-weight:700; }
.ds-empty{ color:var(--text-dim); font-family:var(--font-mono); font-size:12px; padding:6px 0; }
/* collapsible block header — every ds-block's label doubles as a click target
so the user can hide blocks they don't care about right now (e.g. collapse
CALL STACK to make more room for GRAPH) instead of scrolling past them. */
.ds-head{ display:flex; align-items:center; justify-content:space-between; gap:10px; cursor:pointer; user-select:none; margin-bottom:10px; }
.ds-head .ds-label{ margin-bottom:0; }
.ds-head:hover .ds-label{ color:var(--text-hi); }
.ds-head:focus-visible{ outline:1px solid var(--accent); outline-offset:2px; border-radius:4px; }
.ds-chevron{ color:var(--text-dim); font-size:9px; line-height:1; flex-shrink:0; transition:transform 160ms ease; }
.ds-head:hover .ds-chevron{ color:var(--text-mid); }
.ds-block.collapsed{ padding-bottom:14px; }
.ds-block.collapsed .ds-head{ margin-bottom:0; }
.ds-block.collapsed .ds-chevron{ transform:rotate(-90deg); }
.ds-block.collapsed > *:not(.ds-head){ display:none; }
/* array */
.array-flags-row{ display:flex; }
.array-flag-slot{ display:flex; flex-direction:column-reverse; align-items:center; gap:3px; min-height:22px; }
.ptr-flag{
background:var(--flag-color,var(--accent)); color:#041018; font-family:var(--font-mono); font-size:10px; font-weight:800;
padding:2px 7px; border-radius:5px; white-space:nowrap;
}
.array-cells-row{ display:flex; }
.array-idx-row{ display:flex; }
.array-cell{
width:44px; height:44px; margin:2px; border-radius:8px; background:var(--inset); border:1px solid var(--line);
display:flex; align-items:center; justify-content:center; font-family:var(--font-mono); font-size:14px; font-weight:600;
color:var(--text-hi); flex-shrink:0;
}
.cell-val{ line-height:1; }
.array-idx-cell{ width:48px; text-align:center; font-family:var(--font-mono); font-size:10px; color:var(--text-dim); flex-shrink:0; }
.cell-active{ border-color:var(--accent); box-shadow:0 0 0 1px var(--accent), 0 0 14px var(--accent-glow); background:var(--accent-dim); }
.cell-compare{ border-color:var(--warn); background:var(--warn-dim); }
.cell-mismatch{ border-color:var(--danger); background:var(--danger-dim); }
.cell-pointed{ transform:translateY(-1px); }
/* grid */
.grid-table{ display:inline-flex; flex-direction:column; gap:2px; }
.grid-row{ display:flex; gap:2px; }
.grid-cell{
width:40px; height:40px; background:var(--inset); border:1px solid var(--line); border-radius:6px;
display:flex; align-items:center; justify-content:center; font-family:var(--font-mono); font-size:12.5px; color:var(--text-hi);
}
.grid-cell.cell-visited{ background:var(--accent-dim); border-color:var(--accent); }
.grid-cell.cell-active{ border-color:var(--pink); box-shadow:0 0 0 1px var(--pink), 0 0 10px rgba(255,143,214,.45); background:rgba(255,143,214,.14); }
/* stack */
.stack-body{ display:flex; flex-direction:column; align-items:center; }
.stack-top-flag{ display:flex; flex-direction:column; align-items:center; margin-bottom:2px; }
.stack-top-flag span{ font-family:var(--font-mono); font-size:10px; font-weight:800; color:var(--warn); letter-spacing:1px; }
.stack-top-arrow{ width:0;height:0; border-left:5px solid transparent; border-right:5px solid transparent; border-top:6px solid var(--warn); margin-top:2px; }
.stack-col{ display:flex; flex-direction:column-reverse; }
.stack-cell{
width:88px; height:38px; margin:2px 0; border-radius:7px; background:var(--inset); border:1px solid var(--line);
display:flex; align-items:center; justify-content:center; font-family:var(--font-mono); font-size:13px; color:var(--text-hi);
}
.stack-base{ width:110px; height:4px; background:var(--line); border-radius:3px; margin-top:4px; }
/* queue */
.queue-body{ display:flex; align-items:center; gap:10px; }
.queue-flag{ font-family:var(--font-mono); font-size:10px; font-weight:800; color:var(--blue); letter-spacing:1px; }
.queue-row{ display:flex; }
/* map / set chips */
.chip-row{ display:flex; flex-wrap:wrap; gap:8px; }
.map-chip{
display:flex; align-items:center; gap:4px; background:var(--inset); border:1px solid var(--line); border-radius:7px;
padding:5px 10px; font-family:var(--font-mono); font-size:12px;
}
.chip-key{ color:var(--blue); }
.chip-sep{ color:var(--text-dim); }
.chip-val{ color:var(--text-hi); }
.set-chip{
background:var(--violet-dim); border:1px solid var(--violet); color:var(--violet); border-radius:7px;
padding:5px 10px; font-family:var(--font-mono); font-size:12px; font-weight:600;
}
/* scalars */
.scalar-chip{ display:flex; align-items:center; gap:5px; background:var(--panel-2); border:1px solid var(--line); border-radius:7px; padding:5px 10px; font-family:var(--font-mono); font-size:12px; }
.scalar-name{ color:var(--text-mid); }
.scalar-eq{ color:var(--text-dim); }
.scalar-val{ color:var(--text-hi); font-weight:700; }
.scalar-chip.bool-true .scalar-val{ color:var(--accent); }
.scalar-chip.bool-false .scalar-val{ color:var(--danger); }
.scalar-chip.is-none .scalar-val{ color:var(--text-dim); }
/* call stack — capped height with its own internal scroll. Recursion depth is
unbounded, so without this a deep call stack keeps growing taller forever and
pushes every other block further down the page. Scrolling inside the call
stack itself keeps its footprint predictable so GRAPH/VISITED/etc. below it
stay reachable without the whole viz panel growing out of control. */
.callstack-body{ display:flex; flex-direction:column; gap:6px; max-height:200px; overflow-y:auto; padding-right:4px; }
.callstack-frame{ border:1px solid var(--line); border-radius:8px; padding:8px 10px; background:var(--inset); }
.callstack-frame.frame-active{ border-color:var(--pink); box-shadow:0 0 0 1px rgba(255,143,214,.35); }
.frame-head{ font-family:var(--font-mono); font-size:11.5px; color:var(--pink); font-weight:700; margin-bottom:5px; }
.frame-vars{ display:flex; flex-wrap:wrap; gap:5px; }
.frame-var-chip{ font-family:var(--font-mono); font-size:10.5px; background:var(--panel-2); color:var(--text-mid); padding:2px 7px; border-radius:5px; }
/* linked list / tree / graph svg */
.ds-linkedlist, .ds-tree, .ds-graph{ overflow-x:auto; }
.ll-svg, .tree-svg, .graph-svg{ display:block; margin:4px auto 0; }
.ll-node{ fill:var(--inset); stroke:var(--blue); stroke-width:1.5; }
.ll-val{ fill:var(--text-hi); font-family:var(--font-mono); font-size:14px; font-weight:700; }
.ll-edge{ stroke:var(--blue); stroke-width:2; fill:none; }
.ll-null{ fill:var(--text-dim); font-family:var(--font-mono); font-size:11px; }
.ll-flag-bg{ fill:var(--pink); }
.ll-flag-txt{ fill:#22001a; font-family:var(--font-mono); font-size:9.5px; font-weight:800; }
.ll-flag-stem{ stroke:var(--pink); stroke-width:1.5; stroke-dasharray:2,2; }
.tree-node{ fill:var(--inset); stroke:var(--violet); stroke-width:1.5; }
.tree-val{ fill:var(--text-hi); font-family:var(--font-mono); font-size:12px; font-weight:700; }
.tree-edge{ stroke:var(--line); stroke-width:2; }
.graph-node{ fill:var(--inset); stroke:var(--accent); stroke-width:1.5; }
.graph-node-active{ stroke:var(--pink); stroke-width:2.5; filter:drop-shadow(0 0 4px var(--pink)); }
.graph-val{ fill:var(--text-hi); font-family:var(--font-mono); font-size:11px; font-weight:700; }
.graph-edge{ stroke:var(--line); stroke-width:1.5; }
.graph-edge-active{ stroke:var(--pink); stroke-width:2.5; }
/* output console */
.output-console{ font-family:var(--font-mono); font-size:12px; color:var(--accent); background:var(--inset); border:1px solid var(--line); border-radius:9px; padding:10px 12px; }
.output-console .oline:before{ content:"› "; color:var(--text-dim); }
.output-console .oline{ padding:2px 0; }
/* error banner */
.error-banner{
margin:0 18px; padding:12px 16px; border-radius:10px; background:var(--danger-dim); border:1px solid var(--danger);
color:#ffd7d7; font-family:var(--font-mono); font-size:12.5px; display:none;
}
.error-banner.show{ display:block; }
.error-banner .et{ font-weight:800; margin-right:8px; }
/* timeline (replaced by live-bar below) */
.live-bar{ display:flex; align-items:center; gap:14px; padding:9px 16px; background:var(--panel); border-top:1px solid var(--line); flex-shrink:0; }
.speed-group{ display:flex; align-items:center; gap:6px; }
.tl-btn{ padding:7px 14px; border-radius:9px; border:1px solid var(--line); background:var(--panel-2); color:var(--text-hi); cursor:pointer; font-size:12.5px; font-weight:600; display:flex; align-items:center; justify-content:center; gap:6px; }
.tl-btn:hover{ border-color:var(--accent); }
.tl-btn:disabled{ opacity:.4; cursor:default; }
.speed-label{ font-size:11px; color:var(--text-dim); margin-right:2px; }
.speed-btn{ padding:5px 10px; border-radius:7px; border:1px solid var(--line); background:var(--panel-2); color:var(--text-mid); font-size:11.5px; font-weight:600; cursor:pointer; }
.speed-btn.active{ background:var(--accent-dim); color:var(--accent); border-color:var(--accent); }
.live-progress{ font-family:var(--font-mono); font-size:11.5px; color:var(--text-mid); }
.live-dot{ width:7px; height:7px; border-radius:50%; background:var(--accent); box-shadow:0 0 8px var(--accent-glow); display:inline-block; margin-right:5px; }
/* FLIP enter animation */
.flip-enter{ opacity:0; transform:scale(.6); }
.flip-enter-active{ opacity:1; transform:scale(1); transition:opacity 260ms ease, transform 260ms cubic-bezier(.2,.8,.2,1); }
@media (max-width: 900px){
.main{ flex-direction:column; }
.col-source,.col-trace,.col-viz{ width:100%; height:33vh; border-right:none; border-bottom:1px solid var(--line); }
}
</style>
</head>
<body>
<div class="stage">
<div class="topbar">
<div class="brand">
<div class="brand-badge">AIR</div>
<div class="brand-text">
<h1>Algorithm Intermediate Representation</h1>
<p><span class="live-dot"></span>real Python interpreter — any array / stack / linked-list / tree / graph problem</p>
</div>
</div>
<div class="lang-chips">
<div class="lang-chip active" data-lang="python">Python</div>
<div class="lang-chip" data-lang="cpp">C++<span class="beta-dot">β</span></div>
<div class="lang-chip" data-lang="java">Java<span class="beta-dot">β</span></div>
<div class="lang-chip" data-lang="javascript">JavaScript<span class="beta-dot">β</span></div>
</div>
<div class="spacer"></div>
<button class="run-btn" id="runBtn">▶ Run & Visualize</button>
</div>
<div id="errorBanner" class="error-banner"></div>
<div class="main">
<div class="panel col-source">
<div class="panel-head">
<span class="ph-title">Source</span>
<span class="ph-meta">always editable</span>
</div>
<div class="source-edit-wrap">
<div id="lineHighlight" class="line-highlight-bar"></div>
<div id="errLineMarker" class="line-highlight-bar"></div>
<textarea id="sourceEdit" class="source-edit" spellcheck="false"></textarea>
</div>
<div id="entryBar" class="entry-bar" style="display:none;">
<div><b>No driver call found</b> — I generated one automatically. Edit & press Enter to override:</div>
<div id="entryNote" style="margin:4px 0 6px;color:var(--text-dim);"></div>
<input id="entryInput" type="text" placeholder='e.g. Solution().isValid("([)]")'>
</div>
<div id="langNotice" class="entry-bar" style="display:none;color:var(--warn);"></div>
<div class="live-row">
<label><input type="checkbox" id="liveToggle" checked> Live — animate while typing</label>
<span id="liveStatus" class="live-status ok">live</span>
</div>
</div>
<div class="panel col-trace">
<div class="panel-head">
<span class="ph-title">Execution Trace</span>
<span class="ph-meta" id="stepMeta"></span>
</div>
<div id="traceScroll" class="trace-scroll"></div>
</div>
<div class="panel col-viz">
<div class="panel-head">
<span class="ph-title">Visualization</span>
</div>
<div class="viz-scroll" id="vizScroll">
<div id="narration" class="narration">Press Run to execute.</div>
</div>
<div class="panel-head" style="border-top:1px solid var(--line);border-bottom:none;">
<span class="ph-title">Output</span>
</div>
<div id="outputConsole" class="output-console" style="margin:0 14px 14px;"></div>
</div>
</div>
<div class="live-bar">
<button class="tl-btn" id="restartBtn" title="Restart animation">↺ Restart</button>
<div class="speed-group">
<span class="speed-label">Speed</span>
<button class="speed-btn" data-speed="1400">0.5×</button>
<button class="speed-btn active" data-speed="550">1×</button>
<button class="speed-btn" data-speed="220">2×</button>
</div>
<div class="spacer"></div>
<span class="live-progress" id="liveProgress"></span>
</div>
</div>
<script>
/* ---- engine/lexer.js ---- */
(function(){
"use strict";
/* ===================== PYTHON LEXER ===================== */
const KEYWORDS = new Set([
'False','None','True','and','as','assert','async','await','break','class',
'continue','def','del','elif','else','except','finally','for','from','global',
'if','import','in','is','lambda','nonlocal','not','or','pass','raise','return',
'try','while','with','yield'
]);
class Tok {
constructor(type, value, line, col){
this.type = type; this.value = value; this.line = line; this.col = col;
}
}
class LexError extends Error {
constructor(msg, line){ super(msg); this.line = line; this.name='LexError'; }
}
function tokenize(source){
// Normalize line endings, expand tabs to spaces (8-width, python-like) for indent calc
const src = source.replace(/\r\n/g,'\n').replace(/\r/g,'\n');
const lines = src.split('\n');
const tokens = [];
const indentStack = [0];
let parenDepth = 0;
let lastLineHadContent = false;
for (let ln = 0; ln < lines.length; ln++){
let raw = lines[ln];
let i = 0;
const lineNo = ln; // 0-indexed
if (parenDepth === 0){
// compute indentation
let indent = 0;
while (i < raw.length && (raw[i] === ' ' || raw[i] === '\t')){
indent += (raw[i] === '\t') ? 8 - (indent % 8) : 1;
i++;
}
// blank or comment-only line -> skip (no NEWLINE token, no indent change)
let rest = raw.slice(i);
if (rest.trim() === '' || rest.trim().startsWith('#')){
continue;
}
if (indent > indentStack[indentStack.length-1]){
indentStack.push(indent);
tokens.push(new Tok('INDENT', indent, lineNo, 0));
} else {
while (indent < indentStack[indentStack.length-1]){
indentStack.pop();
tokens.push(new Tok('DEDENT', indent, lineNo, 0));
}
if (indent !== indentStack[indentStack.length-1]){
throw new LexError(`Inconsistent indentation on line ${lineNo+1}`, lineNo);
}
}
}
// tokenize the rest of the line starting at i
let lineEmitted = false;
while (i < raw.length){
const ch = raw[i];
if (ch === ' ' || ch === '\t'){ i++; continue; }
if (ch === '#'){ break; } // rest of line is comment
if (ch === '\\' && i === raw.length-1){ i++; break; } // line continuation
// string literal
if (ch === '"' || ch === "'"){
const quote = ch;
let triple = raw.slice(i,i+3) === quote.repeat(3);
let isF = false, isR = false;
// check prefix already consumed? handled below before entering here
let start = i;
let strVal = '';
if (triple){
i += 3;
let closed = false;
let buf = '';
// multi-line string support: keep consuming lines
let curLn = ln;
let curRaw = raw;
while (true){
while (i < curRaw.length){
if (curRaw.slice(i,i+3) === quote.repeat(3)){ i+=3; closed=true; break; }
if (curRaw[i] === '\\' && i+1 < curRaw.length){ buf += unescapeChar(curRaw[i+1]); i+=2; continue; }
buf += curRaw[i]; i++;
}
if (closed) break;
buf += '\n';
curLn++;
if (curLn >= lines.length) throw new LexError('Unterminated triple-quoted string', ln);
curRaw = lines[curLn];
i = 0;
}
if (curLn !== ln){ ln = curLn; raw = curRaw; }
tokens.push(new Tok('STRING', buf, lineNo, start));
lineEmitted = true;
continue;
} else {
i++;
let buf = '';
while (i < raw.length && raw[i] !== quote){
if (raw[i] === '\\' && i+1 < raw.length){ buf += unescapeChar(raw[i+1]); i += 2; continue; }
buf += raw[i]; i++;
}
if (i >= raw.length) throw new LexError(`Unterminated string on line ${lineNo+1}`, lineNo);
i++; // consume closing quote
tokens.push(new Tok('STRING', buf, lineNo, start));
lineEmitted = true;
continue;
}
}
// f-string / raw string prefix
if (/[fFrRbB]/.test(ch) && i+1 < raw.length && (raw[i+1] === '"' || raw[i+1] === "'")){
const prefix = ch.toLowerCase();
const quote = raw[i+1];
let triple = raw.slice(i+1,i+4) === quote.repeat(3);
let j = triple ? i+4 : i+2;
let buf = '';
if (triple){
while (raw.slice(j,j+3) !== quote.repeat(3)){
if (j >= raw.length) throw new LexError('Unterminated triple string', lineNo);
buf += raw[j]; j++;
}
j += 3;
} else {
while (j < raw.length && raw[j] !== quote){
if (raw[j] === '\\' && j+1 < raw.length){ buf += raw[j] + raw[j+1]; j+=2; continue; }
buf += raw[j]; j++;
}
j++; // closing quote
}
if (prefix === 'f'){
tokens.push(new Tok('FSTRING', buf, lineNo, i));
} else {
// raw / bytes: unescape unless raw
const val = prefix === 'r' ? buf : buf.replace(/\\(.)/g, (m,c)=>unescapeChar(c));
tokens.push(new Tok('STRING', val, lineNo, i));
}
i = j;
lineEmitted = true;
continue;
}
// number
if (/[0-9]/.test(ch) || (ch === '.' && /[0-9]/.test(raw[i+1]||''))){
let start = i;
let isFloat = false;
while (i < raw.length && /[0-9_]/.test(raw[i])) i++;
if (raw[i] === '.'){ isFloat = true; i++; while (i<raw.length && /[0-9_]/.test(raw[i])) i++; }
if (raw[i] === 'e' || raw[i] === 'E'){
isFloat = true; i++;
if (raw[i]==='+'||raw[i]==='-') i++;
while (i<raw.length && /[0-9_]/.test(raw[i])) i++;
}
// hex/oct/bin
let text = raw.slice(start,i).replace(/_/g,'');
let num;
if (/^0[xX]/.test(text)) num = parseInt(text,16);
else if (/^0[oO]/.test(text)) num = parseInt(text.slice(2),8);
else if (/^0[bB]/.test(text)) num = parseInt(text.slice(2),2);
else num = isFloat ? parseFloat(text) : parseInt(text,10);
tokens.push(new Tok('NUMBER', num, lineNo, start));
lineEmitted = true;
continue;
}
// identifier / keyword
if (/[A-Za-z_]/.test(ch)){
let start = i;
while (i < raw.length && /[A-Za-z0-9_]/.test(raw[i])) i++;
const word = raw.slice(start,i);
if (KEYWORDS.has(word)) tokens.push(new Tok('KEYWORD', word, lineNo, start));
else tokens.push(new Tok('NAME', word, lineNo, start));
lineEmitted = true;
continue;
}
// operators / punctuation (longest match first)
const three = raw.slice(i,i+3);
const two = raw.slice(i,i+2);
const OPS3 = ['**=','//=','>>=','<<=','...'];
const OPS2 = ['**','//','==','!=','<=','>=','->','+=','-=','*=','/=','%=','&=','|=','^=',':=' ];
if (OPS3.includes(three)){ tokens.push(new Tok('OP', three, lineNo, i)); i+=3; lineEmitted=true; continue; }
if (OPS2.includes(two)){ tokens.push(new Tok('OP', two, lineNo, i)); i+=2; lineEmitted=true; continue; }
if ('()[]{}'.includes(ch)){
if ('([{'.includes(ch)) parenDepth++;
else parenDepth = Math.max(0,parenDepth-1);
tokens.push(new Tok('OP', ch, lineNo, i)); i++; lineEmitted=true; continue;
}
if (',:.;=+-*/%<>!&|^~@'.includes(ch)){
tokens.push(new Tok('OP', ch, lineNo, i)); i++; lineEmitted=true; continue;
}
// unknown char - skip it
i++;
}
if (lineEmitted && parenDepth === 0){
tokens.push(new Tok('NEWLINE', null, lineNo, raw.length));
}
}
// final dedents
while (indentStack.length > 1){
indentStack.pop();
tokens.push(new Tok('DEDENT', 0, lines.length, 0));
}
tokens.push(new Tok('ENDMARKER', null, lines.length, 0));
return tokens;
}
function unescapeChar(c){
switch(c){
case 'n': return '\n';
case 't': return '\t';
case 'r': return '\r';
case '\\': return '\\';
case "'": return "'";
case '"': return '"';
case '0': return '\0';
default: return c;
}
}
const exportObjLexer = { tokenize, Tok, LexError, KEYWORDS };
if (typeof module !== 'undefined') module.exports = exportObjLexer;
else window.PyLexer = exportObjLexer;
})();
/* ---- engine/parser.js ---- */
(function(){
"use strict";
/* ===================== PYTHON PARSER ===================== */
const { tokenize } = typeof require !== 'undefined' ? require('./lexer.js') : window.PyLexer;
class ParseError extends Error {
constructor(msg, line){ super(msg); this.line = line; this.name = 'ParseError'; }
}
// AST node helper
function N(type, props, line){ return Object.assign({ type, line }, props); }
class Parser {
constructor(tokens){
this.toks = tokens.filter(t => t.type !== 'COMMENT');
this.pos = 0;
}
peek(o=0){ return this.toks[this.pos+o]; }
cur(){ return this.toks[this.pos]; }
at(type, value){
const t = this.cur();
if (t.type !== type) return false;
if (value !== undefined && t.value !== value) return false;
return true;
}
atKw(...kws){ const t = this.cur(); return t.type === 'KEYWORD' && kws.includes(t.value); }
atOp(...ops){ const t = this.cur(); return t.type === 'OP' && ops.includes(t.value); }
advance(){ return this.toks[this.pos++]; }
expect(type, value){
const t = this.cur();
if (t.type !== type || (value !== undefined && t.value !== value)){
throw new ParseError(`Expected ${type}${value?(' '+value):''} but got ${t.type} '${t.value}' on line ${t.line+1}`, t.line);
}
return this.advance();
}
skipNewlines(){ while (this.at('NEWLINE')) this.advance(); }
parseModule(){
const body = [];
this.skipNewlines();
while (!this.at('ENDMARKER')){
body.push(this.parseStatement());
this.skipNewlines();
}
return N('Module', { body }, 0);
}
parseBlock(){
this.skipNewlines();
this.expect('INDENT');
const body = [];
this.skipNewlines();
while (!this.at('DEDENT') && !this.at('ENDMARKER')){
body.push(this.parseStatement());
this.skipNewlines();
}
if (this.at('DEDENT')) this.advance();
return body;
}
parseSimpleOrBlock(){
if (this.at('NEWLINE')) return this.parseBlock();
const body = [];
body.push(this.parseSmallStatement());
while (this.atOp(';')){ this.advance(); if(this.at('NEWLINE')) break; body.push(this.parseSmallStatement()); }
if (this.at('NEWLINE')) this.advance();
return body;
}
parseStatement(){
const t = this.cur();
if (t.type === 'KEYWORD'){
switch(t.value){
case 'if': return this.parseIf();
case 'while': return this.parseWhile();
case 'for': return this.parseFor();
case 'def': return this.parseDef();
case 'class': return this.parseClass();
case 'try': return this.parseTry();
case 'with': return this.parseWith();
case 'import': case 'from': return this.parseImport();
}
}
const line = t.line;
const stmts = [];
stmts.push(this.parseSmallStatement());
while (this.atOp(';')){
this.advance();
if (this.at('NEWLINE') || this.at('ENDMARKER')) break;
stmts.push(this.parseSmallStatement());
}
if (this.at('NEWLINE')) this.advance();
if (stmts.length === 1) return stmts[0];
return N('Block', { body: stmts }, line);
}
parseSmallStatement(){
const t = this.cur();
if (t.type === 'KEYWORD'){
switch(t.value){
case 'return': return this.parseReturn();
case 'pass': this.advance(); return N('Pass', {}, t.line);
case 'break': this.advance(); return N('Break', {}, t.line);
case 'continue': this.advance(); return N('Continue', {}, t.line);
case 'global': return this.parseGlobal();
case 'nonlocal': return this.parseNonlocal();
case 'del': return this.parseDel();
case 'raise': return this.parseRaise();
case 'assert': return this.parseAssert();
case 'import': case 'from': return this.parseImport();
case 'yield': { this.advance(); let val=null; if(!this.at('NEWLINE') && !this.atOp(';')) val=this.parseExprList(); return N('ExprStmt',{expr:N('Yield',{value:val},t.line)},t.line); }
}
}
return this.parseExprOrAssign();
}
parseGlobal(){
const line = this.cur().line; this.advance();
const names = [this.expect('NAME').value];
while (this.atOp(',')){ this.advance(); names.push(this.expect('NAME').value); }
return N('Global', { names }, line);
}
parseNonlocal(){
const line = this.cur().line; this.advance();
const names = [this.expect('NAME').value];
while (this.atOp(',')){ this.advance(); names.push(this.expect('NAME').value); }
return N('Nonlocal', { names }, line);
}
parseDel(){
const line = this.cur().line; this.advance();
const target = this.parseExpr ? this.parseExpr() : this.parseExprList();
return N('Del', { target }, line);
}
parseRaise(){
const line = this.cur().line; this.advance();
let exc = null;
if (!this.at('NEWLINE') && !this.atOp(';')) exc = this.parseNamedExpr();
return N('Raise', { exc }, line);
}
parseAssert(){
const line = this.cur().line; this.advance();
const test = this.parseNamedExpr();
let msg = null;
if (this.atOp(',')){ this.advance(); msg = this.parseNamedExpr(); }
return N('Assert', { test, msg }, line);
}
parseImport(){
const line = this.cur().line;
while (!this.at('NEWLINE') && !this.at('ENDMARKER')) this.advance();
return N('Pass', {}, line);
}
parseReturn(){
const line = this.cur().line; this.advance();
let val = null;
if (!this.at('NEWLINE') && !this.at('ENDMARKER') && !this.atOp(';')){
val = this.parseExprList();
}
return N('Return', { value: val }, line);
}
parseIf(){
const line = this.cur().line;
this.advance();
const test = this.parseNamedExpr();
this.expect('OP', ':');
const body = this.parseSimpleOrBlock();
let orelse = [];
if (this.atKw('elif')){
orelse = [this.parseElif()];
} else if (this.atKw('else')){
this.advance();
this.expect('OP', ':');
orelse = this.parseSimpleOrBlock();
}
return N('If', { test, body, orelse }, line);
}
parseElif(){
const line = this.cur().line;
this.advance();
const test = this.parseNamedExpr();
this.expect('OP', ':');
const body = this.parseSimpleOrBlock();
let orelse = [];
if (this.atKw('elif')){
orelse = [this.parseElif()];
} else if (this.atKw('else')){
this.advance();
this.expect('OP', ':');
orelse = this.parseSimpleOrBlock();
}
return N('If', { test, body, orelse }, line);
}
parseWhile(){
const line = this.cur().line;
this.advance();
const test = this.parseNamedExpr();
this.expect('OP', ':');
const body = this.parseSimpleOrBlock();
let orelse = [];
if (this.atKw('else')){
this.advance(); this.expect('OP', ':');
orelse = this.parseSimpleOrBlock();
}
return N('While', { test, body, orelse }, line);
}
parseFor(){
const line = this.cur().line;
this.advance();
const target = this.parseTargetList();
this.expect('KEYWORD', 'in');
const iter = this.parseExprList();
this.expect('OP', ':');
const body = this.parseSimpleOrBlock();
let orelse = [];
if (this.atKw('else')){
this.advance(); this.expect('OP', ':');
orelse = this.parseSimpleOrBlock();
}
return N('For', { target, iter, body, orelse }, line);
}
parseTargetList(){
const first = this.parseTarget();
if (this.atOp(',')){
const items = [first];
while (this.atOp(',')){
this.advance();
if (this.atKw('in') || this.atOp(':') ) break;
items.push(this.parseTarget());
}
return N('TupleTarget', { items }, first.line);
}
return first;
}
parseTarget(){
if (this.atOp('(') || this.atOp('[')){
const closeCh = this.atOp('(') ? ')' : ']';
this.advance();
const items = [];
while (!this.atOp(closeCh)){
items.push(this.parseTarget());
if (this.atOp(',')) this.advance(); else break;
}
this.expect('OP', closeCh);
return N('TupleTarget', { items }, this.cur().line);
}
return this.parsePostfix(this.parseAtom());
}
captureAnnotationText(){
// consume the annotation expression but also return a rough source string for synthesis hints
let depth = 0; let parts = [];
while (true){
const t = this.cur();
if (depth===0 && (this.atOp('=',',') || this.atOp(')') )) break;
if (t.type==='NEWLINE' || t.type==='ENDMARKER') break;
if (t.type==='OP' && '([{'.includes(t.value)) depth++;
if (t.type==='OP' && ')]}'.includes(t.value)){ if (depth===0) break; depth--; }
parts.push(String(t.value));
this.advance();
}
return parts.join('');
}
parseDef(){
const line = this.cur().line;
this.advance();
const name = this.expect('NAME').value;
this.expect('OP', '(');
const params = [];
while (!this.atOp(')')){
let star = '';
if (this.atOp('*')){ this.advance(); star='*'; }
if (this.atOp('**')){ this.advance(); star='**'; }
const pname = this.expect('NAME').value;
let def = null, annotation = null;
if (this.atOp(':')){ this.advance(); annotation = this.captureAnnotationText(); }
if (this.atOp('=')){ this.advance(); def = this.parseOr(); }
params.push({ name: pname, default: def, star, annotation });
if (this.atOp(',')) this.advance(); else break;
}
this.expect('OP', ')');
if (this.atOp('->')){ this.advance(); this.parseOr(); }
this.expect('OP', ':');
const body = this.parseSimpleOrBlock();
return N('FunctionDef', { name, params, body }, line);
}
parseClass(){
const line = this.cur().line;
this.advance();
const name = this.expect('NAME').value;
let bases = [];
if (this.atOp('(')){
this.advance();
while (!this.atOp(')')){
bases.push(this.parseOr());
if (this.atOp(',')) this.advance(); else break;
}
this.expect('OP', ')');
}
this.expect('OP', ':');
const body = this.parseSimpleOrBlock();
return N('ClassDef', { name, bases, body }, line);
}
parseTry(){
const line = this.cur().line;
this.advance();
this.expect('OP', ':');
const body = this.parseSimpleOrBlock();
const handlers = [];
while (this.atKw('except')){
const hline = this.cur().line;
this.advance();
let exType = null, exName = null;
if (!this.atOp(':')){
exType = this.parseOr();
if (this.atKw('as')){ this.advance(); exName = this.expect('NAME').value; }
}
this.expect('OP', ':');
const hbody = this.parseSimpleOrBlock();
handlers.push({ exType, exName, body: hbody, line: hline });
}
let orelse = [];
if (this.atKw('else')){ this.advance(); this.expect('OP',':'); orelse = this.parseSimpleOrBlock(); }
let finalbody = [];
if (this.atKw('finally')){ this.advance(); this.expect('OP',':'); finalbody = this.parseSimpleOrBlock(); }
return N('Try', { body, handlers, orelse, finalbody }, line);
}
parseWith(){
const line = this.cur().line;
this.advance();
const items = [];
items.push(this.parseWithItem());
while (this.atOp(',')){ this.advance(); items.push(this.parseWithItem()); }
this.expect('OP', ':');
const body = this.parseSimpleOrBlock();
return N('With', { items, body }, line);
}
parseWithItem(){
const ctx = this.parseOr();
let asName = null;
if (this.atKw('as')){ this.advance(); asName = this.parseTarget(); }
return { ctx, asName };
}
// ---- expressions ----
parseExprList(){
const first = this.parseNamedExprOrStar();
if (this.atOp(',')){
const items = [first];
while (this.atOp(',')){
this.advance();
if (this.at('NEWLINE') || this.atOp(':',';') || this.at('ENDMARKER')) break;
items.push(this.parseNamedExprOrStar());
}
return N('Tuple', { items }, first.line);
}
return first;
}
parseExprOrAssign(){
const first = this.parseExprList();
const AUG = ['+=','-=','*=','/=','//=','%=','**=','&=','|=','^=','>>=','<<='];
if (this.cur().type === 'OP' && AUG.includes(this.cur().value)){
const op = this.advance().value;
const val = this.parseExprList();
return N('AugAssign', { target: first, op: op.slice(0,-1), value: val }, first.line);
}
if (this.atOp('=')){
const targets = [first];
let value = null;
while (this.atOp('=')){
this.advance();