-
Notifications
You must be signed in to change notification settings - Fork 3
/
Compendium.tex
2274 lines (1994 loc) · 97.2 KB
/
Compendium.tex
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
\documentclass{article}
\usepackage[margin=1.0in]{geometry}
\usepackage{marginnote}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage{listings}
\usepackage{tikz-qtree}
\usepackage{tikz}
\usepackage{enumitem}
\usepackage{wrapfig}
\usepackage{caption}
\usetikzlibrary{shapes, arrows, positioning, calc, matrix, chains, trees, positioning,automata}
\usepackage{subcaption}
%\newcommand{\thickbox}[1]{\fbox{{\bf #1}}}
\newcommand{\thickbox}[1]{\setlength{\fboxrule}{1.3pt}\fbox{#1}\setlength{\fboxrule}{0.4pt}}
\lstdefinelanguage{Pseudo}
{keywords={if, return, function,length, for, each, else, join, in, swap, or ,and}}
\lstdefinestyle{pseudo}{
language=Pseudo,
aboveskip=3mm,
belowskip=3mm,
columns=flexible,
basicstyle={\normalsize\ttfamily},
keywordstyle=\bf,
numbers=none,
frame=none,
breaklines=true,
breakatwhitespace=true,
stepnumber=2,
tabsize=4
}
\begin{document}
\reversemarginpar
\captionsetup{justification=centering, textfont={it}}
\setdescription{leftmargin=\parindent,labelindent=\parindent}
\title{Computer Science Compendium}
\author{Scott Tolksdorf}
\maketitle
\clearpage
\setcounter{tocdepth}{2}
\tableofcontents
%\clearpage
%\section{Introduction}
\clearpage
\section{Data Structures}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Stacks}
\marginnote{\scriptsize{CLRS pg.232}}
A Stack is a dynamic set of data. It follows a {\bf Last-In First-Out} ordering system. Imagine a stack of plates, where you can only add to the stack and the top and only remove plates from the top. {\bf Used in} algorithms in converting decimal numbers to binary, evaluating math expressions, maze back-tracking solutions. Most languages used stacks to resolve operations. {\bf Insert/Delete}: $O(1)$.
\\ \\
{\bf Method:} The data structure uses {\bf Push} to insert new data and {\bf Pop} to remove data. It uses a {\bf Top} pointer to keep track of the data structures position in memory.
\begin{lstlisting}[style=pseudo]
Push(x){
S.top = S.top + 1
S[S.top] = x
}
Pop(){
S.top = S.top - 1
return S[S.top + 1]
}
\end{lstlisting}
\begin{figure}[h]
\centering
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[start chain=1 going right, node distance=-0.15mm]
\node[draw, on chain=1] (a) {4};
\node[draw, on chain=1] (b) {8};
\node[draw, on chain=1] (c) {9};
\node[draw, on chain=1] (d) {\phantom{0}};
\node[draw, on chain=1] (e) {\phantom{0}};
\node[below =of c] (top) {$\uparrow$};
\node[below =of top] {top};
\end{tikzpicture}
{\caption*{Initial stack}}
\end{subfigure}
$\rightarrow$
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[start chain=1 going right, node distance=-0.15mm]
\node[draw, on chain=1] (a) {4};
\node[draw, on chain=1] (b) {8};
\node[draw, on chain=1] (c) {\phantom{0}};
\node[draw, on chain=1] (d) {\phantom{0}};
\node[draw, on chain=1] (e) {\phantom{0}};
\node[below =of b] (top) {$\uparrow$};
\node[below =of top] {top};
\end{tikzpicture}
{\caption*{Pop() = 9}}
\end{subfigure}
$\rightarrow$
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[start chain=1 going right, node distance=-0.15mm]
\node[draw, on chain=1] (a) {4};
\node[draw, on chain=1] (b) {8};
\node[draw, on chain=1] (c) {6};
\node[draw, on chain=1] (d) {8};
\node[draw, on chain=1] (e) {\phantom{0}};
\node[below =of d] (top) {$\uparrow$};
\node[below =of top] {top};
\end{tikzpicture}
{\caption*{Push(6); Push(8)}}
\end{subfigure}
\end{figure}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Queues}
\marginnote{\scriptsize{CLRS pg.232}}
A Queue is a dynamic set of data. It follows a {\bf First-In First-Out} ordering system. Imagine a checkout at a store, you enter at the end of the queue and only leave at the front. To maximize memory use, queues are sometimes implemented cicular in nature. {\bf Used as} priority queues, where elements are added with a priority and removed in order of their priority. Dijkstra's Algoirthm and A* use priority queues to track the most efficient ways to solve their problem. {\bf Insert/Delete}: $O(1)$.
\\ \\
{\bf Method:} The data structure uses {\bf Enqueue} to insert new data and {\bf Dequeue} to remove data. It uses a {\bf Head} and {\bf Tail} pointer to keep track of the data structures position in memory.
\begin{lstlisting}[style=pseudo]
Enqueue(x){
Q[Q.tail] = x
if Q.tail == Q.length
Q.tail = 1
return Q.tail = Q.tail + 1
}
Dequeue(){
x = Q[Q.head]
if Q.head == Q.length
Q.head = 1
else
Q.head = Q.head + 1
return x
}
\end{lstlisting}
\begin{figure}[h]
\centering
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[start chain=1 going right, node distance=-0.15mm]
\node[draw, on chain=1] (f) {\phantom{0}};
\node[draw, on chain=1] (g) {\phantom{0}};
\node[draw, on chain=1] (a) {\phantom{0}};
\node[draw, on chain=1] (b) {4};
\node[draw, on chain=1] (c) {3};
\node[draw, on chain=1] (d) {5};
\node[draw, on chain=1] (e) {\phantom{0}};
\node[below =of b] (head) {$\uparrow$};
\node[below =of head] {head};
\node[below =of d] (tail) {$\uparrow$};
\node[below =of tail] {tail};
\end{tikzpicture}
{\caption*{Initial queue}}
\end{subfigure}
$\rightarrow$
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[start chain=1 going right, node distance=-0.15mm]
\node[draw, on chain=1] (f) {7};
\node[draw, on chain=1] (g) {\phantom{0}};
\node[draw, on chain=1] (a) {\phantom{0}};
\node[draw, on chain=1] (b) {4};
\node[draw, on chain=1] (c) {3};
\node[draw, on chain=1] (d) {5};
\node[draw, on chain=1] (e) {8};
\node[below =of b] (head) {$\uparrow$};
\node[below =of head] {head};
\node[below =of f] (tail) {$\uparrow$};
\node[below =of tail] {tail};
\end{tikzpicture}
{\caption*{Enqueue(8); Enqueue(7)}}
\end{subfigure}
$\rightarrow$
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[start chain=1 going right, node distance=-0.15mm]
\node[draw, on chain=1] (f) {7};
\node[draw, on chain=1] (g) {\phantom{0}};
\node[draw, on chain=1] (a) {\phantom{0}};
\node[draw, on chain=1] (b) {\phantom{0}};
\node[draw, on chain=1] (c) {3};
\node[draw, on chain=1] (d) {5};
\node[draw, on chain=1] (e) {8};
\node[below =of c] (head) {$\uparrow$};
\node[below =of head] {head};
\node[below =of f] (tail) {$\uparrow$};
\node[below =of tail] {tail};
\end{tikzpicture}
{\caption*{Dequeue() = 4}}
\end{subfigure}
\end{figure}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Linked Lists}
\marginnote{\scriptsize{CLRS pg.236}}
In Linked Lists data is stored linearly and sequenitially. Each node contains a pointer to the next node in the list. In a {\bf Double Linked List} each node also has a pointer to it's parent. Better then dynamic arrays for inserts/deletes and since it uses pointers, the data structure can be spread across memory. However, you can not random access a linked list, in order to get an element you must transverse the list to get there. Linked lists use slightly more memory per node to track the pointers. {\bf Search:} $O(n)$; {\bf Insert/Delete}: $O(1)$.
\begin{wrapfigure}{r}{7cm}
\begin{tikzpicture}[node distance=0.3cm and 0.5cm]
\node (null) {\fbox{\phantom{N}}\fbox{Nil}\fbox{\phantom{N}}};
\node[below =of null] (e1) {\fbox{\phantom{0}}\fbox{10}\fbox{\phantom{0}}};
\node[left =of e1] (e0) {\fbox{\phantom{0}}\fbox{9}\fbox{\phantom{0}}};
\node[right =of e1] (e2) {\fbox{\phantom{0}}\fbox{3}\fbox{\phantom{0}}};
\node[left =of e0] (head) {head};
\foreach \from/\to in {null/e0, e0/e1,e1/e2,e2/null, head/e0}
\draw[->] (\from) -- (\to);
\end{tikzpicture}
\end{wrapfigure}
\begin{lstlisting}[style=pseudo]
Search(k){
x = L.head
while x != Nil && x.key != k
x = x.next
return x
}
Insert(x){
x.next = L.head
if L.head != Nil
L.head.prev = x
L.head = x
x.prev = Nil
}
Delete(x){
x.prev.next = x.next
x.next.prev = x.prev
}
\end{lstlisting}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Heaps}
\marginnote{\scriptsize{CLRS pg.151}}
Heaps are a data structure which create a tree-like structure using sequential memory. They are defined by a {\bf Heap Property} which dictate how the heap is formed, eg. max-heap property: Parent nodes are always larger then their children. The internal structure of a heap may be largely unordered, but the heap property ensures the top of the heap is the max element of the data structure. Heaps are useful for any scenerio where simply knowing the largest element is needed, eg. {\bf Priority Queues}. Using properties of sequiential access, node navigation can be done using math on the node's index.
\\ \\
{\bf Method:} Heapify ensures that the node at the given index is following the heap property, if not it will "float down" the data structure until it does. When extracting the max value from a heap, replace it with the last value in the heap, and Heapify from the top.
\begin{wrapfigure}{r}{4cm}
\begin{tikzpicture}[node distance=0.5cm and 0.1cm]
\node (s) {\fbox{6}\fbox{5}\fbox{3}\fbox{1}\fbox{2}};
\node[below =of s] (arrow) {$\downarrow$};
\node[below =of arrow, circle, draw] (a) {6};
\node[below left =of a, circle, draw] (b) {5};
\node[below right =of a, circle, draw] (c) {3};
\node[below left =of b, circle, draw] (d) {1};
\node[below right =of b, circle, draw] (e) {2};
\foreach \from/\to in {a/b,a/c,b/d,b/e}
\draw (\from) -- (\to);
\end{tikzpicture}
\end{wrapfigure}
\begin{lstlisting}[style=pseudo]
Parent(i) => floor(i/2)
Left(i) => 2i
Right(i) => 2i + 1
BuildHeap(A){
for i = floor(A.length/2) -> 1
Heapify(A, i)
}
Heapify(A, i){
if A[Left(i)] > A[i]
largest = Left(i)
else
largest = i
if A[Right(i)] > A[largest]
largest = Right(i)
if largest != i
swap A[i] with A[largest]
Heapify(A, largest)
}
Extract(A){
max = A[0]
A[0] = A[A.length]
Heapify(A,0)
return max
}
\end{lstlisting}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Hashtables}
\marginnote{\scriptsize{CLRS pg.257}}
Hashtables is a data structure that map keys to values in an associated array using a {\bf Hash Function}. A hash function maps the value to the address space of the data structure. It should be choosen that limits clumping and collisions. A hash table's {\bf Load Factor} is the ratio of the number of elements in the data structure against it maximum size. When a hash table has a high load factor it has to be resized in order to avoid collisions. {\bf Search/Insert/Delete:} $O(1)$.
\\ \\
Collisions resolution could be done one of three ways: {\bf Chaining}, {\bf Open Addressing}, {\bf Cuckoo}
\begin{description}
\item[Chaining] Each entry in the hash table is a linked list which stores all the collisions for that hash value.
\item[Open Addressing] A probe sequence is used to check for values in a specific order. Performace degrades after a load factor above 0.7 and hash function must be very uniformly distributed.
\item[Cuckoo] Assures constant lookup time in the worst case. Uses multiple hash functions, whenever there is a collision, it uses the next hash function to store the value. Extremely good at utilizing space.
\end{description}
There are two main methods for {\bf resizing} a hashtable:
\begin{enumerate}
\item {\bf Rehash}: A new table size is allocated and every entry is copied over using the new hash function.
\item {\bf Incremental}: Create a new table of the larger size, keeping the old table. Perform lookups and deletes on both tables. Whenever you insert, only insert into the new table, as well as copy over a number of element from the old table. When all elements are moved over, delete the old table.
\end{enumerate}
A technique to speed up deletes is to use {\bf Tombstones}. A tombstone is a special entry that is inserted in place of an element you wish to delete. It's ignored during lookups, and replaced during inserts.
\clearpage
\subsection{Problems}
\begin{enumerate}
\item Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures
\item Given two strings, write a method to decide if one is a permutation of the other.
\item Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
\item Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
\item Implement an algorithm to find the kth to last element of a singly linked list.
\item Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x.
\item Implement a function to check if a linked list is a palindrome
\item Implement a queue class which implements a queue using two stacks.
\item Write a program to sort a stack in ascending order (with biggest items on top). You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: \texttt{push}, \texttt{pop}, \texttt{peek}, and \texttt{isEmpty}.
\end{enumerate}
\clearpage
\section{Sorting}
%-----------------------------------------------------------------------------------------------------------------
\subsection{MergeSort}
\marginnote{\scriptsize{CLRS pg.31}}
MergeSort is a {\bf Divide and Conquer algorithm}, it's recursive and can be parallelized well between multiple processors. It has {\bf Stable Sorting}, so items with the same value perserve their order from the original list. {\bf Avg/Worst Case}: $O(n \log n)$; {\bf Aux. Space}: $\Omega(n)$. {\bf Best used} when accessing data sequentially is important, eg. parallel/external sorting. On average slower then HeapSort and QuickSort.
\\ \\
{\bf Method:} MergeSort splits its list until it's down to 1 element, then rejoins them recursively inorder.
\begin{wrapfigure}{r}{2cm}
\begin{tikzpicture}
[scale=1.0, transform canvas={scale=1.0},
node distance=0.2cm and 0.07cm,
every node/.style={align=center}]
\node (s0) {\fbox{6}\fbox{2}\fbox{1}\fbox{5}};
\node[below left=of s0] (s1a) {\fbox{6}\fbox{2}};
\node[below right=of s0] (s1b) {\fbox{1}\fbox{5}};
\node[below left=of s1a] (s2a) {\fbox{6}};
\node[below right=of s1a] (s2b) {\fbox{2}};
\node[below left=of s1b] (s2c) {\fbox{1}};
\node[below right=of s1b] (s2d) {\fbox{5}};
\node[below right=of s2a] (s3a) {\fbox{2}\fbox{6}};
\node[below left=of s2d] (s3b) {\fbox{1}\fbox{5}};
\node[below left=of s3b] (s4) {\fbox{1}\fbox{2}\fbox{5}\fbox{6}};
\foreach \from/\to in {
s0/s1a,s0/s1b,
s1a/s2a,s1a/s2b,s1b/s2c,s1b/s2d,
s2a/s3a,s2b/s3a,s2c/s3b,s2d/s3b,
s3a/s4,s3b/s4}
\draw[->] (\from) -- (\to);
\end{tikzpicture}
\end{wrapfigure}
\begin{lstlisting}[style=pseudo]
MergeSort(list){
if length(list) <= 1
return list
split list -> A, B
A = MergeSort(A), B = MergeSort(B)
loop through each A, B and merge in sorted order
return result
}
\end{lstlisting}
\vspace{10 mm}
%-----------------------------------------------------------------------------------------------------------------
\subsection{QuickSort}
\marginnote{\scriptsize{CLRS pg.170}}
QuickSort is a {\bf Divide and Conquer algorithm}, it's recursive and can be parallelized well between multiple processors. It has {\bf Non-Stable Sorting}, so items with the same value do not perserve their order from the original list. {\bf Avg Case}: $O(n \log n)$; {\bf Worst Case}: $O(n^2)$; {\bf Aux. Space}: $\Omega(\log n)$. {\bf Best used} when speed is top priority. Can have cases where running time is very slow, bad for very large data sets and possible for attacks.
\\ \\
{\bf Method:} QuickSort chooses a pivot, then creates two new lists, one containing elements less then the pivot and one greater then the pivot. Recursively applies this to the new lists. Rejoins them with the pivot.
\begin{wrapfigure}{r}{2cm}
\begin{tikzpicture}
[scale=1.0,
transform canvas={scale=1.0},
node distance=0.2cm and 0.04cm,
every node/.style={align=center}]
\node (s0) {\fbox{5}\fbox{2}\thickbox{3}\fbox{1}\fbox{6}};
\node[below left=of s0] (s1a) {\thickbox{2}\fbox{1}};
\node[below right=of s0] (s1c) {\thickbox{5}\fbox{6}};
\node[below left=of s1a] (s2a) {\fbox{1}};
\node[below =of s1a] (s2b) {\thickbox{2}};
\node[below right=of s1a] (s2c) {\fbox{\phantom{0}}};
\node[below left=of s1c] (s2d) {\fbox{\phantom{0}}};
\node[below =of s1c] (s2e) {\thickbox{5}};
\node[below right=of s1c] (s2f) {\fbox{6}};
\node[below =of s2c] (s3a) {\fbox{1}\fbox{2}};
\node[yshift=-2.85cm] (s3b) {\thickbox{3}};
\node[below =of s2d] (s3c) {\fbox{5}\fbox{6}};
\node[below =of s3b] (s4) {\fbox{1}\fbox{2}\fbox{3}\fbox{5}\fbox{6}};
\foreach \from/\to in {
s0/s1a,s0/s1c,
s1a/s2a,s1a/s2b,s1a/s2c, s1c/s2d,s1c/s2e,s1c/s2f,
s2a/s3a,s2b/s3a,s2c/s3a, s0/s3b, s2d/s3c,s2e/s3c,s2f/s3c,
s3a/s4, s3b/s4, s3c/s4}
\draw[->] (\from) -- (\to);
\end{tikzpicture}
\end{wrapfigure}
\begin{lstlisting}[style=pseudo]
QuickSort(list){
if length(list) <= 1
return list
select and remove a pivot from list
create empty lists -> left, right
for each x in array
if x <= pivot
append x to left
else
append x to right
return join(QuickSort(left), pivot, QuickSort(right))
}
\end{lstlisting}
%-----------------------------------------------------------------------------------------------------------------
\clearpage
\subsection{HeapSort}
\marginnote{\scriptsize{CLRS pg.151}}
Heapsort is a comparison-based sorting algorithm. It has {\bf Non-Stable Sorting}, so items with the same value do not perserve their order from the original list. {\bf Avg/Worst Case}: $O(n \log n)$; {\bf Aux. Space}: $\Omega(1)$. {\bf Best used} when space is a concerned, eg. embedded systems. On average runs slower then QuickSort, but faster then MergeSort.
\\ \\
{\bf Method:} HeapSort first builds a heap out of the data, the iteratively removes the largest elements from the heap and stores it in an array, then rebuilds the heap. Repeat until the heap is exhausted.
\begin{lstlisting}[style=pseudo]
HeapSort(A){
BuildHeap(A)
for length(A)
result = Extract(A)
replace with last in heap
reduce heap size by 1
Heapify(A)
return result
}
\end{lstlisting}
\begin{figure}[h]
\centering
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[node distance=0.5cm and 0.1cm]
\node (s) {\fbox{6}\fbox{2}\fbox{3}\fbox{1}\fbox{5}};
%\node[below =of s, circle, draw] (a) {\phantom{0}};
%\node[below left =of a, circle, draw] (b) {\phantom{0}};
%\node[below right =of a, circle, draw] (c) {\phantom{0}};
%\node[below left =of b, circle, draw] (d) {\phantom{0}};
%\node[below right =of b, circle, draw] (e) {\phantom{0}};
%\foreach \from/\to in {a/b,a/c,b/d,b/e}
%\draw (\from) -- (\to);
\end{tikzpicture}
{\caption*{Initial array}}
\end{subfigure}
$\rightarrow$
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[node distance=0.5cm and 0.1cm]
\node (s) {\fbox{6}\fbox{5}\fbox{3}\fbox{1}\fbox{2}};
\node[below =of s, circle, draw] (a) {6};
\node[below left =of a, circle, draw] (b) {5};
\node[below right =of a, circle, draw] (c) {3};
\node[below left =of b, circle, draw] (d) {1};
\node[below right =of b, circle, draw] (e) {2};
\foreach \from/\to in {a/b,a/c,b/d,b/e}
\draw (\from) -- (\to);
\end{tikzpicture}
{\caption*{Reorganized as a heap}}
\end{subfigure}
$\rightarrow$
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[node distance=0.5cm and 0.1cm]
\node (s) {\fbox{2}\fbox{5}\fbox{3}\fbox{1}\thickbox{6}};
\node[below =of s, circle, draw] (a) {2};
\node[below left =of a, circle, draw] (b) {5};
\node[below right =of a, circle, draw] (c) {3};
\node[below left =of b, circle, draw] (d) {1};
\foreach \from/\to in {a/b,a/c,b/d}
\draw (\from) -- (\to);
\end{tikzpicture}
{\caption*{Remove root node, \par replaced with last}}
\end{subfigure}
\end{figure}
\begin{figure}[h]
\centering
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[node distance=0.5cm and 0.1cm]
\node (s) {\fbox{5}\fbox{2}\fbox{3}\fbox{1}\thickbox{6}};
\node[below =of s, circle, draw] (a) {5};
\node[below left =of a, circle, draw] (b) {2};
\node[below right =of a, circle, draw] (c) {3};
\node[below left =of b, circle, draw] (d) {1};
\foreach \from/\to in {a/b,a/c,b/d}
\draw (\from) -- (\to);
\end{tikzpicture}
{\caption*{Heapify}}
\end{subfigure}
$\rightarrow$
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[node distance=0.5cm and 0.1cm]
\node (s) {\fbox{1}\fbox{2}\fbox{3}\thickbox{5}\thickbox{6}};
\node[below =of s, circle, draw] (a) {1};
\node[below left =of a, circle, draw] (b) {2};
\node[below right =of a, circle, draw] (c) {3};
\foreach \from/\to in {a/b,a/c}
\draw (\from) -- (\to);
\end{tikzpicture}
{\caption*{Remove root node, \par replaced with last}}
\end{subfigure}
$\rightarrow$
\begin{subfigure}{.3\textwidth}
\centering
\begin{tikzpicture}[node distance=0.5cm and 0.1cm]
\node (s) {\fbox{3}\fbox{2}\fbox{1}\thickbox{5}\thickbox{6}};
\node[below =of s, circle, draw] (a) {3};
\node[below left =of a, circle, draw] (b) {2};
\node[below right =of a, circle, draw] (c) {1};
\foreach \from/\to in {a/b,a/c}
\draw (\from) -- (\to);
\end{tikzpicture}
{\caption*{Re-heapify!}}
\end{subfigure}
{\caption*{Example of heaping an array}}
\end{figure}
\clearpage
\subsection{Problems}
\begin{enumerate}
\item Write a method to sort an array of strings so that all the anagrams are next to each other.
\item Imagine you have a 20 GB file with one string per line. Explain how you would sort the file.
\item Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element.
\item A circus is designing a tower routine consisting of people standing atop one another's shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the heights and weights of each person in the circus, write a method to compute the largest possible number of people in such a tower.
\begin{lstlisting}[style=pseudo]
Example
Input (ht,wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110)
Output:The longest tower is (56, 90) (60,95) (65,100) (68,110) (70,150) (75,190)
\end{lstlisting}
\end{enumerate}
\clearpage
\section{Trees}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Binary Search Trees}
\marginnote{\scriptsize{CLRS pg.287}}
Binary Trees are family of data structures efficient at lookups. Data is stored that $Right \leq Node \leq Left$. BSTs are {\bf unbalanced}, meaning one part of the tree may become much larger then the other, hurting the efficiency. {\bf Search/Insert:} $O(n \log n)$; {\bf Delete:} $O(n)$.
%\begin{lstlisting}[style=pseudo]
%Search(node, val){
%if node == Nil or node.key == val
%return node
%if val > node.key
%return Search(node.left, val)
%else
%return Search(node.right, val)
%}
%Insert(node, val){
%if node is empty
%node = val
%
%if val > .key
%x = x.left
%else
%x = x.right
%if val > x.parent.key
%x.left = val
%else
%x.right = val
%}
%Delete(T, node){
%if node.left == Nil and node.right == Nil
%//TODO
%}
%\end{lstlisting}
\begin{figure}[h]
\centering
\begin{subfigure}{.4\textwidth}
\centering
\begin{tikzpicture}[node distance=0.5cm and 0.1cm]
\node (s) {\fbox{6}\fbox{5}\fbox{7}\fbox{5}\fbox{2}\fbox{8}};
\node[below =of s, circle, draw] (a) {6};
\node[below left =of a, circle, draw] (b) {5};
\node[below right =of a, circle, draw] (c) {7};
\node[below left =of b, circle, draw] (d) {2};
\node[below right =of b, circle, draw] (e) {5};
\node[below right =of c, circle, draw] (f) {8};
\foreach \from/\to in {a/b,a/c,b/d,b/e,c/f}
\draw (\from) -- (\to);
\end{tikzpicture}
{\caption*{Well-balanced BST}}
\end{subfigure}
\begin{subfigure}{.4\textwidth}
\centering
\begin{tikzpicture}[node distance=0.5cm and 0.1cm]
\node (s) {\fbox{10}\fbox{8}\fbox{7}\fbox{5}\fbox{6}\fbox{1}};
\node[below =of s, circle, draw] (a) {10};
\node[below left =of a, circle, draw] (b) {8};
\node[below left =of b, circle, draw] (c) {7};
\node[below left =of c, circle, draw] (d) {5};
\node[below left =of d, circle, draw] (e) {1};
\node[below right =of d, circle, draw] (f) {6};
\foreach \from/\to in {a/b,b/c,c/d,d/e,d/f}
\draw (\from) -- (\to);
\end{tikzpicture}
{\caption*{Unbalanced BST}}
\end{subfigure}
\end{figure}
%-----------------------------------------------------------------------------------------------------------------
\subsection{B-Trees}
\marginnote{\scriptsize{CLRS pg.488}}
B-Trees are an extreme form of {\bf k-ary Trees}, where k is very large. Each node has a minimum and maximum number of children it can have; $t-1$ and $2t - 1$ respectively, where $t$ is the {\bf order} of the tree. B-Trees are achieve extremely large tree structures with a small height when the order of the tree is high, number of nodes is $2t^h -1$ where $h$ is the height of the tree. {\bf Search/Insert/Delete:} $O(\log n)$.
\\ \\
{\bf Best Used} for when lookups are very expensive and when lookups are best done in large sequiential blocks. Mostly used for storing data on {\bf physical storage}.
\begin{figure}[h]
\centering
\begin{tikzpicture}[every tree node/.style={draw},
level distance=1.25cm,sibling distance=.5cm,
edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}]
\Tree [.{A\ldots M\ldots}
[.{B\ldots F\ldots H}
[.{C D} ]
[.{G} ]
]
[.{N\ldots R\ldots T Y}
[.{O P Q} ]
[.{S} ]
]
]
\end{tikzpicture}
{\caption*{B-tree with order of 2}}
\end{figure}
Inserting a node is slightly more complicated. When inserting a new value into a node that is full, we must split the node into smaller chunks. With deleting a value, you may have to rearrange a node's children.
\begin{figure}[h]
\centering
\begin{tikzpicture}[every tree node/.style={draw},
level distance=1.25cm,sibling distance=.5cm,
edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}]
\Tree [.{\ldots N W\ldots}
[.{P Q R S T U V W} ]
]
\end{tikzpicture}
\hspace{1 cm} \raisebox{1.0cm}{$\rightarrow$} \hspace{1 cm}
\begin{tikzpicture}[every tree node/.style={draw},
level distance=1.25cm,sibling distance=.5cm,
edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}]
\Tree [.{\ldots N S W\ldots}
[.{P Q R} ]
[.{T U V W} ]
]
\end{tikzpicture}
{\caption*{Splitting a child node into 2 on $S$ because it is too large}}
\end{figure}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Tries}
A Trie is an unique tree data structure where a node's location within the tree determines its value. Each edge of the tree has a value given to it and as you traverse the tree you build the value of the node. Very useful for {\bf storing strings} and {\bf binary values}.
\\ \\
Tries have a {\bf faster worst case than hash tables} because they don't need to rebuilds, they can produce {\bf alpha-ordering} which may be useful for some applications like spell checking, and there is {\bf no chance for collisions}. However, Tries may need more memory, long entires can create useless nodes, and they require {\bf lots of random access memory} to operate. {\bf Search/Insert/Delete:} $O(k)$ where $k$ is the length of the longest node value.
\begin{figure}[h]
\centering
\begin{tikzpicture}[every tree node/.style={draw},
level distance=1.25cm,sibling distance=.5cm,
edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}]
\Tree [.\phantom{0}
\edge node[auto=right] {t};
[.t
\edge node[auto=right] {o};
[.to ]
\edge node[auto=right] {e};
[.te
\edge node[auto=right] {a};
[.tea ]
\edge node[auto=right] {n};
[.ten ]
]
]
\edge node[auto=right] {a};
[.a ]
\edge node[auto=left] {i};
[.i
\edge node[auto=left] {n};
[.in
\edge node[auto=left] {n};
[.inn ]
]
]
]
\end{tikzpicture}
{\caption*{Building a Trie for "to", "tea", "ten", and "inn"}}
\end{figure}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Radix Tree}
\marginnote{\scriptsize{CLRS pg.304}}
Radix Tress are space optimized {\bf Trie} where each node with only one child is merged with its parent, and its edge is updated accordingly. They are {\bf more efficient for small sets} especially if the strings are long and for sets of strings that share long prefixes. {\bf Search/Insert/Delete:} $O(k)$ where $k$ is the length of the longest edge key.
\\ \\
{\bf Best used} in IP Routing, where the ability to contain large ranges of values with a few exceptions is particularly suited to the hierarchical organization of IP addresses. They are useful for {\bf Inverted Indexes} in text documents for very fast searching through the document.
\begin{figure}[h]
\centering
\begin{tikzpicture}[every tree node/.style={draw},
level distance=1.25cm,sibling distance=.5cm,
edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}]
\Tree [.\phantom{0}
\edge node[auto=right] {t};
[.\phantom{0}
\edge node[auto=right] {oast};
[.toast ]
\edge node[auto=left] {est};
[.test
\edge node[auto=right] {ing};
[.testing ]
\edge node[auto=left] {er};
[.tester ]
]
]
\edge node[auto=left] {slow};
[.slow
\edge node[auto=left] {ly};
[.slowly ]
]
]
\end{tikzpicture}
{\caption*{Building a Radix Trie for "toast", "test", "testing", "tester", "slow", and "slowly"}}
\end{figure}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Self-Balancing Trees}
\marginnote{\scriptsize{CLRS pg.308}}
A Self-Balancing Tree is a binary search tree that keeps its height small during inserts and deletes. Binary Search Trees have a very bad worst-case; Self-Balancing Trees attempt to correct this by using {\bf Tree Rotations} to maintain tree properties that ensure a predictable height of the tree.
\\ \\
Whenever a node is inserted or deleted, we need to check the node's children for consistency of the height property. {\bf Avg/Worst} of {\bf Search/Insert/Deletes:}$O(\log n)$. The two most common Self-Balancing Trees are {\bf AVL Trees} and {\bf Red-Black Trees}.
\begin{figure}[h]
\centering
\begin{tikzpicture}[
every tree node/.style={},
level distance=1.0cm,sibling distance=.5cm,
edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}
]
\Tree [.\phantom{0}
[.\node[draw, circle] {$y$};
[.\node[draw, circle] {$x$};
[.A ]
[.B ]
]
[.C ]
]
]
\end{tikzpicture}
\begin{tikzpicture}[node distance=0.3cm and 1.5cm]
\node (tl) {\phantom{0}};
\node [right =of tl] (tr) {\phantom{0}};
\node [below =of tl] (bl) {\phantom{0}};
\node [right =of bl] (br) {\phantom{0}};
\draw[->] (tr) --(tl) node[above,midway] {\small LeftRotate($x$)};
\draw[->] (bl) --(br) node[below,midway] {\small RightRotate($y$)};
\end{tikzpicture}
\begin{tikzpicture}[
every tree node/.style={},
level distance=1.0cm,sibling distance=.5cm,
edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}
]
\Tree [.\phantom{0}
[.\node[draw, circle] {$x$};
[.A ]
[.\node[draw, circle] {$y$};
[.B ]
[.C ]
]
]
]
\end{tikzpicture}
%{\caption*{Basic Tree Rotations}}
\end{figure}
%-----------------------------------------------------------------------------------------------------------------
\subsubsection{AVL Trees}
The height property of an AVL Tree is that {\bf the heights of the two child subtrees of any node differ by at most one}. AVL Trees are more rigidly balanced than Red-Black Trees, leading to {\bf slower inserts and deletes} but {\bf faster search}.
%\begin{minipage}{\linewidth}
%\begin{lstlisting}[style=pseudo]
%balanceFactor(node) => height(node.left) - height(node.right)
%Insert(node, val){
%if node is Nil
%node.key = val
%return node
%if val > node.key
%node.left = Insert(node.left, val)
%if balanceFactor(node) > 1
%if val > node.left.key
%LeftRotate(node)
%LeftRotate(node)
%if val <= node.key
%node.right = Insert(node.right, val)
%if balanceFactor(node) < -1
%if val < node.right.key
%RightRotate(node)
%RightRotate(node)
%return node
%}
%
%Delete(z){
%//finish later, very complex
%}
%\end{lstlisting}
%\end{minipage}
%-----------------------------------------------------------------------------------------------------------------
\subsubsection{Red-Black Trees}
Red-Black Trees are less rigidly balanced than AVL Trees, leading to {\bf slower search} but {\bf faster inserts and deletes}. The height properties of a Red-Black Tree are as follows:
\begin{enumerate}
\item A node may be red or black
\item All leaves are black
\item Every red node must have two black child nodes
\item Every path from the root to a leaf must have the same number of black nodes.
\end{enumerate}
\begin{figure}[h]
\centering
\tikzset{
node_black/.style = {
circle, white, font=\sffamily\bfseries, draw=black, fill=black
},
node_red/.style = {
circle, red, draw=red, very thick
},
node_nil/.style = {
white, font=\scriptsize\sffamily\bfseries, draw=black, fill=black
}
}
\begin{tikzpicture}[every tree node/.style={draw},
level distance=1.25cm,sibling distance=.5cm,
edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}]
\Tree [.\node[node_black] {13};
[.\node[node_red] {8};
[.\node[node_black] {1};
[.\node[node_nil] {NIL}; ]
[.\node[node_red] {6};
[.\node[node_nil] {NIL}; ]
]
]
[.\node[node_black] {11};
[.\node[node_nil] {NIL}; ]
[.\node[node_nil] {NIL}; ]
]
]
[.\node[node_red] {17};
[.\node[node_black] {15};
[.\node[node_nil] {NIL}; ]
[.\node[node_nil] {NIL}; ]
]
[.\node[node_black] {25};
[.\node[node_red] {22};
[.\node[node_nil] {NIL}; ]
[.\node[node_nil] {NIL}; ]
]
[.\node[node_red] {27};
[.\node[node_nil] {NIL}; ]
[.\node[node_nil] {NIL}; ]
]
]
]
]
\end{tikzpicture}
\end{figure}
%\begin{minipage}{\linewidth}
%\begin{lstlisting}[style=pseudo]
%//TODO: Make recursive
%Insert(z){
%find leaf where node should be attached -> y
%z.parent = y
%if z.key > y.key
%y.left = z
%else
%y.right = z
%z.color = red
%
%//Maintain height property
%while z.parent is red
%if z.parent is a left-child
%if z.uncle is red
%z.parent.color = black
%z.uncle.color = black
%z.grandparent.color = red
%z = z.grandparent
%if z.uncle is black and z is a right-child
%z = z.parent
%LeftRotate(z)
%if z's uncle is black and z is a left-child
%z.parent.color = black
%z.grandparent.color = red
%RightRotate(z.grandparent)
%else
%Same as above but switch left and right rotate
%root.color = black
%}
%Delete(z){
%//finish later, very complex
%}
%\end{lstlisting}
%\end{minipage}
%-----------------------------------------------------------------------------------------------------------------
\subsection{Bloom Filter}
A Bloom Filter is a space efficient probalistic data structure that's used to test whether an element is in a set. False positives are possible, but {\bf false negatives} are not. An empty Bloom Filter is a bit array of $m$ bits all set to 0. Whenever you add an element to the set use $k$ hash functions and flip all the corresponing entires to 1. To test if an entry belongs to the set, simply hash it and check the corresponding bit entires. If any of them are 0 the element is not part of the set. The probability of a {\bf false positive} is $(1 - e^{-kn/m})^k$, where $n$ is the number of elements encoded in the set.
\\ \\
{\bf Used in} Chrome to detect unsafe urls from a master list, BigTable to skip unnecessary table lookups, and in url shortners.
\begin{figure}[h]
\centering
\begin{tikzpicture}[start chain=1 going right, node distance=-0.15mm]
\node (y) {y};
\node[left =of y] (x) {x};
\node[right =of y] (z) {z};
\node[draw, on chain=1] at (-1.7,-1.5) (a) {1};
\node[draw, on chain=1] (b) {0};
\node[draw, on chain=1] (c) {1};
\node[draw, on chain=1] (d) {1};
\node[draw, on chain=1] (e) {0};
\node[draw, on chain=1] (f) {1};
\node[draw, on chain=1] (g) {1};
\node[draw, on chain=1] (h) {0};
\node[draw, on chain=1] (i) {0};
\node at (0,-3.0) (w) {w};
\foreach \from/\to in {x/a,x/d,y/c,y/f,z/f,z/g,w/d,w/e}
\draw[->, thick] (\from) -- (\to);
\end{tikzpicture}
{\caption*{$x$, $y$, $z$ are in the set, where $w$ is not}}
\end{figure}
\subsection{Problems}
\begin{enumerate}
\item Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
\item Implement a function to check if a binary tree is a binary search tree.
\item Write an algorithm to find the'next'node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent.
\item You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum to a given value. The path does not need to start or end at the root or a leaf.
\item You have two very large binary trees: Tl, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of Tl.
\\ \\
A tree T2 is a subtree of Tl if there exists a node n in Tl such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.
\item Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.
\end{enumerate}
\clearpage
\section{Bit Manipulation}
Bit Manipulation is the act of manipualting individual bits within data. It can reduce the need to loop over a data structure and can give many-fold speed ups, as bit manipulations are {\bf processed in parallel}, but the code can become rather more difficult to write and maintain. {\bf Used in} low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization.
\subsection{Operations}
Bit manipulation supports a number operations: OR \text{\textbar}, AND \& , XOR \string^ , SHIFT << , and NOT \string~ .
\begin{lstlisting}[style=pseudo]
0110 | 0001 = 0111
1000 & 1011 = 1000