├── Algorithms.mdown ├── DataStructures.mdown ├── README.md ├── ReviewOfBasicJava.mdown ├── ReviewOfBasicOOPConcepts.mdown └── to_do.mdown /Algorithms.mdown: -------------------------------------------------------------------------------- 1 | # Algorithms 2 | 3 | ## Sorting 4 | 5 | ### Bubble Sort 6 | 7 | | Worst | Average | Best | Space | Notes | 8 | |-------|---------|------|-------|-------| 9 | | O(n^2) | O(n^2) | O(n) | O(1) | good when one element maybe changed a bit, when the list is almost entirely sorted | 10 | 11 | Bubble sort ... 12 | 13 | ### Selection Sort 14 | | Worst | Average | Best | Space | Notes | 15 | |-------|---------|------|-------|-------| 16 | | O(n^2) | O(n^2) | | O(1) | | 17 | 18 | Selection sort divides the array into a sorted (left) and unsorted (right) array and repeatedly selects the smallest element from the unsorted array and swaps it with the leftmost element, and that element becomes a part of the sorted array. 19 | 20 | #### Pseudocode 21 | 22 | ``` 23 | procedure selection sort 24 | list : array of items 25 | n : size of list 26 | 27 | for i = 1 to n - 1 28 | /* set current element as minimum*/ 29 | min = i 30 | 31 | /* check the element to be minimum */ 32 | 33 | for j = i+1 to n 34 | if list[j] < list[min] then 35 | min = j; 36 | end if 37 | end for 38 | 39 | /* swap the minimum element with the current element*/ 40 | if indexMin != i then 41 | swap list[min] and list[i] 42 | end if 43 | 44 | end for 45 | 46 | end procedure 47 | ``` 48 | 49 | ### Insertion Sort 50 | | Worst | Average | Best | Space | Notes | 51 | |-------|---------|------|-------|-------| 52 | | O(n^2) | O(n^2) | | O(1) | | 53 | 54 | Insertion sort searches the array sequentially and takes unsorted items and inserts them into the sorted sub-list to their appropriate place. 55 | 56 | #### Pseudocode 57 | 58 | 59 | ### Quick Sort 60 | | Worst | Average | Best | Space | Notes | 61 | |-------|---------|------|-------|-------| 62 | | O(n^2) | O(nlogn) | ? | ? | ? | 63 | 64 | 65 | Quick sort ... 66 | 67 | #### Pseudocode 68 | 69 | 70 | ### Merge Sort 71 | Merge: average and worst O(nlogn) time, 72 | 73 | Merge sort first divides the array into equal halves and then combines them in a sorted manner. 74 | 75 | 76 | ### Heap Sort 77 | 78 | 79 | ## Search 80 | 81 | ### Binary Search 82 | 83 | #### Implementation 84 | 85 | #### Java 86 | - find in documentation 87 | 88 | -------------------------------------------------------------------------------- /DataStructures.mdown: -------------------------------------------------------------------------------- 1 | # Data Structures 2 | 3 | ## Strings 4 | 5 | ### `String` 6 | 7 | Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: 8 | ```java 9 | // These are equivalent: 10 | String str = "abc";` 11 | 12 | char data[] = {'a', 'b', 'c'}; 13 | String str = new String(data); 14 | ``` 15 | 16 | #### Methods 17 | * `int Integer.parseInt(s)` 18 | * int to string 19 | * `int compareTo(String anotherString)` 20 | * `boolean equals(Object anObject)` 21 | * `char charAt(int index)` 22 | * `char[] toCharArray()` 23 | * `String substring(int beginIndex, int endIndex)` 24 | * `String[] split(String regex)` 25 | * `String toLowerCase()` 26 | * `int hashCode()` 27 | * `int indexOf(int ch)` 28 | 29 | ### `StringBuilder` 30 | 31 | 32 | 33 | #### Methods 34 | 35 | #### Example 36 | 37 | ## Arrays 38 | 39 | Common types here: 40 | * fixed-size arrays (E.g. `int[] array = new int[10];`, `String[] wordList = new String[10];`) 41 | * resizable arrays - can grow as needed; use when we don't know the capacity upfront 42 | * `ArrayList` 43 | * `Vector` 44 | 45 | #### Implementation 46 | 47 | ```java 48 | class ResizableArray { 49 | private int[] items = new int[10]; // hardcoding here is a bit sloppy 50 | private int size = 0; 51 | 52 | public int size() { 53 | return size; 54 | } 55 | 56 | public void set(int index, item) { 57 | if (index < 0 || index >= size) { 58 | throw new ArrayIndexOutOfBoundsException(index); 59 | } 60 | items[index] = item; 61 | } 62 | 63 | public void append(int item) { 64 | ensureCapacity(); 65 | items[size] = item; 66 | size++; 67 | } 68 | 69 | public int get(int index) { 70 | if (index < 0 || index >= size) { 71 | throw new ArrayIndexOutOfBoundsException(index); 72 | } 73 | return items[index]; 74 | } 75 | 76 | private void ensureCapacity() { 77 | if (size == items.length) { 78 | int[] copy = new int[2 * size]; // create a new array 79 | System.arraycopy(items, 0, copy, 0, size); // copy all elements over 80 | items = copy; // point items to copy 81 | } 82 | } 83 | } 84 | 85 | ``` 86 | 87 | ### `ArrayList` 88 | 89 | #### Methods 90 | 91 | * Indexing: `E get(int index)` - **O(1)** 92 | * Setting: `E set(int index, E element)` - **O(1)** (this returns previous element at index) 93 | * Appending: `boolean add(E e)` - **amortized O(1)** because very rarely we have to resize 94 | * `int size()` - **O(1)** 95 | * `boolean isEmpty()` - *O(1)* 96 | * `void clear()` - **O(n)** 97 | * `Object clone()` - *O(n)* 98 | * `boolean contains(Object o)` - *O(n)* 99 | * `int indexOf(Object o)` - *O(n)* (this is the index of the first occurence) 100 | * `int lastIndexOf(Object o)` - *O(n)* 101 | * Adding: `void add(int index, E element)` - *O(n)* because remaining elements need to be shifted 102 | * Removing: `E remove(int index)`, `boolean remove(Object o)` - *O(n)* because of the shifting 103 | * `Object[] toArray()` - *O(n)* 104 | 105 | 106 | ### `Vector` 107 | 108 | `Vector` and `ArrayList` are almost equivalent, but generally `ArrayList` is _better_ because: `Vector` is slow as it is thread safe; in comparison `ArrayList` is fast as it is non synchronized. 109 | 110 | Similarities: 111 | * internally, both hold onto their contents using an Array. 112 | Dfiferences 113 | * Synchronization: access to a Vector is synchronized, whereas access to an ArrayList is not. What this means is that only one thread can call methods on a Vector at a time, and there's a slight overhead in acquiring the lock; this is not the case with an ArrayList. Generally, ArrayList is better: in the single-threaded case it's a better choice, and in the multi-threaded case, we get better control over locking. It does require a little more care on our end, but it's likely what we want. The `Collections.synchronizedList` function can be used with an ArrayList to create a synchronized list, thus getting the equivalent of a Vector. 114 | * Data growth: a Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. 115 | 116 | ## Hash Tables 117 | 118 | * A key-value lookup. 119 | * The key and the value can be any type of data structure. 120 | * Hash function 121 | * Mapping is from key -> hash code -> index (hash code != index) 122 | * Collisions: Possible for the same key to map to the same hash code, and two different hash codes can map to the same index. Collisions are possible because there is an infinite number of keys and a finite number of hash codes and even fewer indeces (because the array is often much smaller than the number of hascodes). 123 | * Collision Resolution: 124 | * Chaining 125 | * Find something else! 126 | * Getting (and also Containing) and Setting are O(1) assuming we have a "good" hash table (the hash function distributes our values well) 127 | * *Initial capacity* - *Load factor* tradeoff: The initial capacity is the number of buckets in the hash table at the time it is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets. 128 | 129 | 130 | #### Implementation 131 | 132 | ```java 133 | class HashTable { 134 | LinkedList[] data; 135 | boolean put(String key, Person value) { 136 | int hashCode = getHashCode(key); 137 | int index = convertToIndex(hashCode); 138 | LinkedList list = data[index]; 139 | // check for duplicates.. 140 | list.add(key, value); 141 | } 142 | 143 | 144 | } 145 | ``` 146 | 147 | ### `HashMap` 148 | 149 | - default initial capacity (16) and default load factor (0.75). 150 | 151 | #### Methods 152 | 153 | * Getting: `V get(Object key)` - *O(1)* 154 | * Setting: `V put(K key, V value)` - *O(1)* 155 | * Removing: `V remove(Object key)` - *amortized O(1)* or O(1+a), where a is the load factor and so depends on how many items are in the slot for the hash key of the removed object. 156 | * `int size()` - *O(1)* 157 | * `boolean isEmpty()` - *O(1)* 158 | * `Set keySet()` - *O(1)* because the returned Set is not a copy of the keys, but a wrapper for the actual HashMap's state 159 | * Contains Key: `boolean containsKey(Object key)` - *O(1)* 160 | * Contains Value: `boolean containsValue(Object value)` - *O(n)* because without the key it doesn't know where it is and the algorithm has to go over all the values stored in the map. 161 | * `void clear()` - *O(n)* 162 | * `Object clone()` - *O(n)* (this returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.) 163 | * `Collection values()` - *O(n)* on traversal through iterator 164 | 165 | ### `TreeMap` 166 | 167 | A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. 168 | 169 | #### Methods 170 | * `containsKey` - *O(logn)* 171 | * `get` - *O(logn)* 172 | * `put` - *O(logn)* 173 | * `remove` - *O(logn)* 174 | * `K firstKey()` 175 | * `K lastKey()` 176 | * `NavigableMap descendingMap()` 177 | * `NavigableSet descendingKeySet()` 178 | * [...] 179 | 180 | 181 | ## Sets 182 | 183 | ### `HashSet` 184 | 185 | This class implements the Set interface, backed by a hash table (actually a HashMap instance). HashSet stores the objects in _random order_. It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. 186 | 187 | #### Methods 188 | * `add`- *O(1)* 189 | * `remove`- *O(1)* 190 | * `contains`- *O(1)* 191 | * `size`- *O(1)* 192 | 193 | ### `TreeSet` 194 | 195 | A NavigableSet implementation based on a TreeMap. The elements are ordered using their _natural ordering_, or by a Comparator provided at set creation time, depending on which constructor is used. 196 | 197 | #### Methods 198 | * `add`- *O(logn)* 199 | * `remove`- *O(logn)* 200 | * `contains`- *O(logn)* 201 | 202 | 203 | ## Linked Lists 204 | 205 | * Can contain any types of data structures. 206 | * Elements can be sorted or unsorted. 207 | * Indexing O(n) 208 | * Inserion and deletion (at the beginning of the list) O(1) 209 | * Inserion and deletion (at the end of the list) O(n) 210 | 211 | #### Implementation 212 | 213 | ```java 214 | public class Node { 215 | int data; 216 | Node next; 217 | public Node(int data) { 218 | this.data = data; 219 | } 220 | } 221 | 222 | public class LinkedList { 223 | Node head; 224 | 225 | public boolean isEmpty() { 226 | return head == null; 227 | } 228 | 229 | public void append(int data) { 230 | if (head == null) { 231 | head = new Node(data); 232 | return; 233 | } 234 | Node current = head; 235 | while (current.next != null) { 236 | current = current.next; 237 | } 238 | current.next = new Node(data); 239 | } 240 | 241 | public void prepend(int data) { 242 | Node newHead = new Node(data); 243 | newHead.next = head; 244 | head = newHead; 245 | } 246 | 247 | // delete first node that contains data 248 | public void delete(int data) { 249 | if (head == null) return; 250 | 251 | if (head.data == data) { 252 | head = head.next; 253 | return; 254 | } 255 | 256 | Node current = head; 257 | while (current.next != null) { 258 | if (current.next.data == data) { 259 | current.next = current.next.next; 260 | return; 261 | } 262 | current = current.next; 263 | } 264 | 265 | } 266 | } 267 | ``` 268 | 269 | ## Doubly-Linked Lists 270 | 271 | ### `LinkedList` 272 | 273 | Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations. Can act both as a *Stack* and a *Queue* 274 | 275 | #### Methods 276 | * `boolean add(E e)`, `void addLast(E e)` - *O(1)* (*end*) 277 | * `void add(int index, E element)` - *O(1)* 278 | * `void addFirst(E e)` - *O(1)* 279 | * `E getFirst()` - *O(1)* 280 | * `E getLast()` - *O(1)* 281 | * `boolean offer(E e)`, `boolean offerLast(E e)` - *O(1)* (*tail* = *last*) 282 | * `boolean offerFirst(E e)` - *O(1)* 283 | * `E peek()`, `E peekFirst()` - *O(1)* (*head* = *first*) 284 | * `E peekLast()` - *O(1)* 285 | * `E poll()`, `E pollFirst()` - *O(1)* (*head* = *first*) 286 | * `E pollLast()` - *O(1)* 287 | * `E pop()` - *O(1)* 288 | * `void push(E e)` - *O(1)* 289 | * `E remove()`, `E removeFirst()` - *O(1)* (*head* = *first*) 290 | * `E removeLast()` - *O(1)* 291 | * `int size()` - *O(1)* 292 | * `void clear()` - *O(n)* 293 | * `Object clone()` - *O(n)* 294 | * `Object[] toArray()` - *O(n)* 295 | * `E set(int index, E element)` - *O(n)* 296 | * `E get(int index)` - *O(n)* 297 | * `int indexOf(Object o)` - *O(n)* 298 | * `int lastIndexOf(Object o)` - *O(n)* 299 | * `boolean contains(Object o)` - *O(n)* 300 | * `E remove(int index)`, `boolean removeFirstOccurrence(Object o)`, `boolean removeLastOccurrence(Object o)` - *O(n)* 301 | 302 | ## Stacks 303 | 304 | ### Implementation 305 | ```java 306 | public class Stack { 307 | private static class Node { 308 | private int data; 309 | private Node next; 310 | private Node(int data) { 311 | this.data = data; 312 | } 313 | } 314 | 315 | private Node top; // add and remove from here 316 | 317 | public boolean isEmpty(){ 318 | return top == null; 319 | } 320 | 321 | public int peek() { 322 | // Add null pointer checks 323 | return top.data; 324 | 325 | } 326 | 327 | public void push(int data) { 328 | Node node = new Node(data); 329 | node.next = top; 330 | top = node; 331 | } 332 | 333 | public int pop() { 334 | // Add null pointer checks 335 | int data = top.data; 336 | top = top.next; 337 | return data; 338 | } 339 | } 340 | 341 | ``` 342 | ### `Stack` 343 | 344 | #### Methods 345 | * `E peek()` - *O(1)* (*head* = *first*) 346 | * `E pop()` - *O(1)* 347 | * `void push(E e)` - *O(1)* 348 | 349 | 350 | ## Queues 351 | 352 | ### Implementation 353 | 354 | public class Queue { 355 | private static class Node { 356 | private int data; 357 | private Node next; 358 | private Node(int data) { 359 | this.data = data; 360 | } 361 | } 362 | 363 | private Node head; // remove from the head 364 | private Node tail; // add to the tail 365 | 366 | public boolean isEmpty() { 367 | return head == null; 368 | } 369 | 370 | public int peek() { 371 | // Add null pointer exception 372 | return head.data; 373 | } 374 | 375 | public void add(int data) { 376 | Node node = new Node(data); 377 | 378 | if (tail != null) { 379 | tail.next = node; 380 | } 381 | tail = node; 382 | if (head == null) { 383 | head = node 384 | } 385 | 386 | } 387 | 388 | public int remove() { 389 | // Add null pointer exception 390 | int data = head.data; 391 | head = head.next; 392 | if (head == null) { 393 | tail = null; 394 | } 395 | return data; 396 | } 397 | } 398 | 399 | 400 | ### `Queue` - Interface 401 | 402 | ## Deques (double ended queue) 403 | 404 | ### Implementation 405 | 406 | [work in progress] 407 | 408 | ### `Deque` - Interface 409 | 410 | 411 | ## Trees 412 | 413 | ## Binary Search Trees 414 | 415 | ### Implementation 416 | 417 | ```java 418 | class Node { 419 | int data; 420 | Node left; 421 | Node right; 422 | public Node(int data) { 423 | this.data = data; 424 | } 425 | 426 | public void insert(int value) { 427 | if (value <= data) { 428 | if (left == null) { 429 | left = new Node(value); 430 | } 431 | else { 432 | left.insert(value); 433 | } 434 | } 435 | else { 436 | if (right == null) { 437 | right = new Node(value); 438 | } 439 | else { 440 | right.insert(value); 441 | } 442 | } 443 | } 444 | 445 | public boolean contains(int value) { 446 | if (value == data) { 447 | return true; 448 | } 449 | else if (value < data) { 450 | if (left == null) { 451 | return false; 452 | } 453 | else { 454 | return left.contains(value); 455 | } 456 | } 457 | else { 458 | if (right == null) { 459 | return false; 460 | } 461 | else { 462 | return right.contains(value); 463 | } 464 | } 465 | } 466 | 467 | public void delete(value) { 468 | 469 | // 470 | 471 | 472 | 473 | 474 | 475 | 476 | } 477 | 478 | public void inOrderTraversal() { 479 | if (left != null) { 480 | left.inOrderTraversal(); 481 | } 482 | System.out.println(data); 483 | if (right != null) { 484 | right.inOrderTraversal(); 485 | } 486 | } 487 | 488 | public void preOrderTraversal() { 489 | System.out.println(data); 490 | if (left != null) { 491 | left.inOrderTraversal(); 492 | } 493 | if (right != null) { 494 | right.inOrderTraversal(); 495 | } 496 | } 497 | } 498 | ``` 499 | 500 | ## Heaps 501 | 502 | ### Implementation 503 | 504 | ```java 505 | class minHeap { 506 | private int capacity; 507 | private int size; 508 | int[] items; 509 | 510 | minHeap(int n) { 511 | this.capacity = n; 512 | this.size = 0; 513 | items = new int[n]; 514 | } 515 | 516 | int getParentIndex(int childIndex) { return (childIndex-1)/2; } 517 | int getLeftChildIndex(int parentIndex) { return parentIndex*2 + 1; } 518 | int getRightChildIndex(int parentIndex) { return parentIndex*2 + 2; } 519 | 520 | boolean hasParent(int index) { return getParentIndex(index) >= 0; } 521 | boolean hasLeftChild(int index) {return getLeftChildIndex(index) < size; } 522 | boolean hasRightChild(int index) {return getRightChildIndex(index) < size; } 523 | 524 | int parent(int index) { return (hasParent(index)) ? items[getParentIndex(index)] : null; } 525 | int leftChild(int index) { return (hasLeftChild(index)) ? items[getLeftChildIndex(index)] : null; } 526 | int rightChild(int index) { return (hasRightChild(index)) ? items[getRightChildIndex(index)] : null; } 527 | 528 | void swap(int index1, int index2) { 529 | int temp = items[index1]; 530 | items[index1] = items[index2]; 531 | items[index2] = temp; 532 | } 533 | 534 | void ensureCapacity() { 535 | if (size == capacity) { 536 | capacity = capacity * 2; 537 | items = Arrays.copyOf(items, capacity); 538 | } 539 | } 540 | 541 | int peek() { 542 | if (this.size == 0) throw new IllegalStateException(); 543 | return items[0]; 544 | } 545 | 546 | int extractMin() { 547 | if (this.size == 0) throw new IllegalStateException(); 548 | int min = items[0]; 549 | items[0] = items[size-1]; 550 | size--; 551 | heapifyDown(); 552 | return min; 553 | } 554 | 555 | void add(int item) { 556 | ensureCapacity(); 557 | items[size] = item; 558 | size++; 559 | heapifyUp(); 560 | } 561 | 562 | void heapifyDown() { 563 | int index = 0; 564 | while (hasLeftChild(index)) { 565 | int smallestChildIndex = (hasRightChild(index) && rightChild(index) < leftChild(index)) ? getRightChildIndex(index) : getLeftChildIndex(index); 566 | if (items[index] < items[smallestChildIndex]) 567 | break; 568 | else { 569 | swap(index, smallestChildIndex); 570 | index = smallestChildIndex; 571 | } 572 | } 573 | } 574 | 575 | void heapifyUp() { 576 | int index = size - 1; 577 | while (hasParent(index) && parent(index) > items[index]) { 578 | swap(index, getParentIndex(index)); 579 | index = getParentIndex(index); 580 | } 581 | } 582 | 583 | int getSize() { 584 | return this.size; 585 | } 586 | } 587 | ``` 588 | 589 | ```java 590 | class maxHeap { 591 | private int capacity; 592 | private int size; 593 | int[] items; 594 | 595 | maxHeap(int n) { 596 | this.capacity = n; 597 | this.size = 0; 598 | items = new int[n]; 599 | } 600 | 601 | int getParentIndex(int childIndex) { return (childIndex-1)/2; } 602 | int getLeftChildIndex(int parentIndex) { return parentIndex*2 + 1; } 603 | int getRightChildIndex(int parentIndex) { return parentIndex*2 + 2; } 604 | 605 | boolean hasParent(int index) { return getParentIndex(index) >= 0; } 606 | boolean hasLeftChild(int index) {return getLeftChildIndex(index) < size; } 607 | boolean hasRightChild(int index) {return getRightChildIndex(index) < size; } 608 | 609 | int parent(int index) { return (hasParent(index)) ? items[getParentIndex(index)] : null; } 610 | int leftChild(int index) { return (hasLeftChild(index)) ? items[getLeftChildIndex(index)] : null; } 611 | int rightChild(int index) { return (hasRightChild(index)) ? items[getRightChildIndex(index)] : null; } 612 | 613 | void swap(int index1, int index2) { 614 | int temp = items[index1]; 615 | items[index1] = items[index2]; 616 | items[index2] = temp; 617 | } 618 | 619 | void ensureCapacity() { 620 | if (size == capacity) { 621 | capacity = capacity * 2; 622 | items = Arrays.copyOf(items, capacity); 623 | } 624 | } 625 | 626 | int peek() { 627 | if (this.size == 0) throw new IllegalStateException(); 628 | return items[0]; 629 | } 630 | 631 | int extractMax() { 632 | if (this.size == 0) throw new IllegalStateException(); 633 | int max = items[0]; 634 | items[0] = items[size-1]; 635 | size--; 636 | heapifyDown(); 637 | return max; 638 | } 639 | 640 | void add(int item) { 641 | ensureCapacity(); 642 | items[size] = item; 643 | size++; 644 | heapifyUp(); 645 | } 646 | 647 | void heapifyDown() { 648 | int index = 0; 649 | while (hasLeftChild(index)) { 650 | int biggestChildIndex = (hasRightChild(index) && rightChild(index) > leftChild(index)) ? getRightChildIndex(index) : getLeftChildIndex(index); 651 | if (items[index] > items[biggestChildIndex]) 652 | break; 653 | else { 654 | swap(index, biggestChildIndex); 655 | index = biggestChildIndex; 656 | } 657 | } 658 | } 659 | 660 | void heapifyUp() { 661 | int index = size - 1; 662 | while (hasParent(index) && parent(index) < items[index]) { 663 | swap(index, getParentIndex(index)); 664 | index = getParentIndex(index); 665 | } 666 | } 667 | 668 | int getSize() { 669 | return this.size; 670 | } 671 | } 672 | ``` 673 | 674 | ### `PriorityQueue` 675 | 676 | An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. 677 | 678 | ```java 679 | PriorityQueue minHeap = new PriorityQueue (); 680 | PriorityQueue maxHeap = new PriorityQueue (new Comparator () { 681 | public int compare(Integer a, Integer b) { 682 | return -1 * a.compareTo(b); 683 | } 684 | }); 685 | ``` 686 | 687 | #### Methods 688 | 689 | ## Tries 690 | 691 | A trie, also called digital tree and sometimes radix tree or prefix tree (as they can be searched by prefixes), is a kind of search tree — an ordered tree data structure that is used to store a dynamic set or associative array where the keys are usually strings. 692 | 693 | ### Implementation 694 | 695 | ```java 696 | class Node { 697 | char letter; 698 | HashMap children; 699 | int leafCount = 0; 700 | // boolean isWord = false; 701 | 702 | public Node(char letter) { 703 | this.letter = letter; 704 | this.children = new HashMap(); 705 | } 706 | 707 | // Inserts node (letter) and returns pointer to the node 708 | public Node insert(char letter) { 709 | if (!this.children.containsKey(letter)) 710 | this.children.put(letter, new Node(letter)); 711 | return this.children.get(letter); 712 | } 713 | 714 | // If the letter is found among the children of the node, return it, otherwise return null 715 | public Node contains(char letter) { 716 | if (this.children.containsKey(letter)) 717 | return this.children.get(letter); 718 | else 719 | return null; 720 | } 721 | } 722 | 723 | public class Solution { 724 | 725 | // This is the root of the trie 726 | private static Node trie = new Node('*'); 727 | 728 | public static void printTrie(Node root) { 729 | System.out.print(root.letter + " - "); 730 | for (Node child : root.children.values()) { 731 | printTrie(child); 732 | System.out.println(""); 733 | } 734 | } 735 | 736 | public static void add(String contact) { 737 | 738 | char[] letters = contact.toCharArray(); 739 | Node temp = trie; 740 | int i = 0; 741 | 742 | while (i < letters.length) { 743 | temp.leafCount++; 744 | Node child = temp.contains(letters[i]); 745 | if (child != null) { 746 | temp = child; 747 | } 748 | else { 749 | temp = temp.insert(letters[i]); 750 | } 751 | i++; 752 | } 753 | // Insert '*' to mark end of word 754 | temp.insert('*'); 755 | temp.leafCount++; 756 | } 757 | 758 | public static void find(String contact) { 759 | 760 | char[] letters = contact.toCharArray(); 761 | Node temp = trie; 762 | int i = 0; 763 | 764 | while (temp != null && i < letters.length) { 765 | temp = temp.contains(letters[i]); 766 | i++; 767 | } 768 | // If contact found, this will basically return the number of children of the node 769 | if (temp != null) 770 | System.out.println(temp.leafCount); 771 | else 772 | System.out.println(0); 773 | } 774 | 775 | public static void main(String[] args) { 776 | Scanner in = new Scanner(System.in); 777 | int n = in.nextInt(); 778 | for(int a0 = 0; a0 < n; a0++){ 779 | String op = in.next(); 780 | String contact = in.next(); 781 | 782 | if (op.compareTo("add") == 0) { 783 | add(contact); 784 | //printTrie(trie); 785 | } 786 | else if (op.compareTo("find") == 0) 787 | find(contact); 788 | else 789 | System.out.println("Invalid operation"); 790 | } 791 | in.close(); 792 | } 793 | } 794 | 795 | ``` 796 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # the-ultimate-java-cheat-sheet 2 | The ultimate cheat sheet that will refresh (or teach you) everything you need to know about data structures and algorithms in Java. 3 | 4 | [UNDER CONSTRUCTION] 5 | 6 | Contents: 7 | 8 | 1. [Review of Basic OOP Concepts](ReviewOfBasicOOPConcepts.mdown) 9 | 2. [Review of Basic Java](ReviewOfBasicJava.mdown) 10 | 3. [Data Structures](DataStructures.mdown) This includes a brief review of data structures, their implementations and their ussage (with a list of commonly used methods). 11 | 4. [Algorithms](Algorithms.mdown) 12 | -------------------------------------------------------------------------------- /ReviewOfBasicJava.mdown: -------------------------------------------------------------------------------- 1 | # Review of Basic Java 2 | 3 | ## Term Definitions 4 | 5 | #### Class 6 | a collection of variables called *fields* and functions called *methods*. 7 | 8 | *Naming convention:* the name should always start with a capital letter; this signifies to certain compilers (and human readers) that it is a class (or ?); it is a best practice to use CamelCase; class names cannot begin with numbers or contain any spaces. 9 | 10 | ```java 11 | class MyClass { 12 | // declare a Java class 13 | } 14 | ``` 15 | 16 | #### Program 17 | a collection of classes. 18 | 19 | #### Variable 20 | a name (identifier) that points to (references) a location in memory where information associated with that name can be stored. Each variable has a *data type* associated with it, which essentially restricts what that variable is allowed to reference and the operations that can be performed on it. 21 | 22 | *Naming convention:* it is a best practice to always start variable names with a lowercase letter and use CamelCase for variable names composed from compound phrases; variable names cannot contain spaces or special characters (except underscores), and cannot begin with numbers; occasionally, Java coders begin certain special variable names (e.g.: private class variables or constants) with an underscore to distinguish them from other variables used throughout their program. 23 | 24 | ```java 25 | DataType myVar1; // declare a variable named myVar1 having the data type DataType 26 | DataType myVar2 = value; // declare a variable of type DataType named myVar2 and initialize it to be value 27 | ``` 28 | 29 | #### Field 30 | a variable that is a member of a class. 31 | 32 | #### Function 33 | a sequence of packaged instructions that perform a task. 34 | 35 | *Naming convention:* it is a best practice to always start function names with a lowercase letter and use CamelCase for function names composed from compound phrases; function names cannot contain spaces or special characters (except underscores), and cannot begin with numbers. 36 | 37 | ```java 38 | int myFunction() { 39 | // declare a function 40 | } 41 | void myFunction(int myInt) { 42 | // declare another function that does not return anything 43 | } 44 | ``` 45 | 46 | #### Method 47 | a type of function that operates on the fields of a class. 48 | 49 | #### Object 50 | an instance (or variable) of a class. 51 | 52 | #### Stream 53 | the flow of data from one place to another. Very often it is required to read input from stdin (standard input) and write output to stdout (standard output). One popular way to read input from stdin is by using the `Scanner` class and specifying the input stream as *System.in*. Once finished reading from an input stream, it is important to close it to avoid a resource leak. 54 | 55 | 56 | ```java 57 | Scanner scan = new Scanner(System.in); // create a new Scanner object that reads from the System.in stream 58 | scan.next(); // returns the next token of input 59 | int n = scan.nextInt(); // returns the next token of input as an int 60 | int n = Integer.parseInt(in.nextLine()); // returns the next token of input as an int and eats the whitespace (newline) 61 | scan.hasNext(); // returns true if there is another token of input (false otherwise) 62 | scan.nextLine() // reads from the Scanner's current location until the beginning of the next line 63 | scan.hasNextLine(); // returns true if there is another line of iput 64 | scan.close(); // closes the Scanner object referenced by the scan variable 65 | System.out.println("some output"); // prints to stdout 66 | System.out.printf("%-15s%03d%n", s, x); // print formatted output "java 100" 67 | System.out.format("%-15s%03d%n", s, x); // print formatted output "cpp 065" 68 | ``` 69 | 70 | [INCLUDE TABLE HERE WITH FORMATTING TAGS AND STUFF] 71 | 72 | ## Data Types 73 | 74 | Java is considered as a *strongly typed* programming language: all variables have a particular data type. Java is also known as a *hybrid* language: it offers both *object types* and *primitive types*. 75 | 76 | ### Primitive Types 77 | the most basic data types. They serve as the building blocks of data manipulation in Java, with only one purpose — containing pure, simple values of a kind. Because these data types are defined into the Java type system by default, they come with a number of operations predefined. We cannot define new operations for such primitive types. 78 | 79 | | Category | Type | Size(bits) | Precision | Default Value | 80 | |----------|--------|------------|-------------------------------------------------|---------------| 81 | Textual | `char` | 16 | All Unicode characters | '\u0000' 82 | Textual (Integer) | `byte` | 8 | From +127 to -128 | 0 83 | Numeric (Integer) | `short` | 16 | From +32,767 to -32,768 | 0 84 | Numeric (Integer) | `int` | 32 | From +2,147,483,647 to -2,147,483,648 | 0 85 | Numeric (Integer) | `long` | 64 | From +9,223,372,036,854,775,807 to -9,223,372,036,854,775,808 | 0L 86 | Numeric (Floating point) | `float` | 32 | From 3.402,823,5 E+38 to 1.4 E-45 | 0.0f 87 | Numeric (Floating point) | `double` | 64 | From 1.797,693,134,862,315,7 E+308 to 4.9 E-324 | 0.0d 88 | Other | `boolean` | 1 | false, true | false 89 | Other | `null` | -- | -- | -- 90 | Other | `void` | -- | -- | -- 91 | Other | `String` | -- | -- | null 92 | 93 | The `String` class is not technically a primitive data type, but considering the special support given to it by the language, we could think of it as such. Enclosing a character string within double quotes automatically creates a new `String` object. 94 | 95 | #### Operations 96 | * Simple Assignment Operator `=` 97 | * Arithmetic Operators `+`, `-`, `*`, `/`, `%` 98 | * Unary Operators `+`, `-`, `++`, `--`, `!` 99 | * Equality and Relational Operators `==`, `!=`, `>`, `>=`, `<`, `<=` 100 | * Conditional Operators `&&`, `||` 101 | * Ternary Operator `?:` shorthand for if-then-else statement, i.e.: if ? then : else 102 | * Type Comparison Operator `instanceof` 103 | * Bitwise and Bit Shift Operators 104 | * `~` Unary bitwise complement 105 | * `<<` Signed left shift 106 | * `>>` Signed right shift 107 | * `>>>` Unsigned right shift 108 | * `&` Bitwise AND 109 | * `^` Bitwise exclusive OR 110 | * `|` Bitwise inclusive OR 111 | 112 | 113 | ### Arrays 114 | container objects that hold a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Each item in an array is called an element, and each element is accessed by its numerical index. Indexing begins with 0. 115 | 116 | ```java 117 | byte[] anArrayOfBytes; // declares a variable to refer to an array of bytes 118 | short[] anArrayOfShorts; // does not actually create an array 119 | long[] anArrayOfLongs; // tells the compiler that this variable will hold an array of the specified type (long) 120 | double anArrayOfDoubles[]; // this form is discouraged 121 | anArrayOfLongs = new long[10]; // create an array of longs 122 | int[] anArrayOfInts = {100, 200, 300, 400, 500}; // shortcut syntax to create and initialize an array 123 | ``` 124 | 125 | We can also declare a *multidimensional array* by using two or more sets of brackets, e.g. `int[][]`. Each element, therefore, must be accessed by a corresponding number of index values. In Java, a multidimensional array is an array whose components are themselves arrays. As a consequence, the rows are allowed to vary in length. 126 | 127 | #### Operations 128 | Methods to perform some of the most common manipulations related to arrays: 129 | * `arraycopy` method of the `System` class 130 | * `copyOfRange`, `binarySearch`, `equals`, `fill`, `sort`, `parallelSort`, `toString` methods of the `java.util.Arrays` class 131 | 132 | A note about the different ways to *copy* arrays: 133 | * `static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)` Copies a subrray of specified length from the specified source array, beginning at the specified position, to the specified position of the destination array. 134 | * `static T[] copyOf(T[] original, int newLength)` Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length. 135 | * `static T[] copyOfRange(T[] original, int from, int to)` Copies the specified range of the specified array into a new array. 136 | * `Object ArrayList.clone()` Returns a __shallow__ copy of this ArrayList instance. 137 | 138 | *Shallow* vs *deep* copying 139 | A shallow copy can be made by simply copying the reference. This can lead to unpleasant side effects if the elements of values are changed via some other reference. 140 | A deep copy means actually creating a new array and copying over the values. (best to do it by hand: create a new array and copy each element's value - using `arraycopy` for example.) 141 | 142 | ## Control Flow Statements 143 | 144 | ### Decision-Making Statements 145 | 146 | ### Looping Statements 147 | 148 | Diffrent types of for 149 | ```java 150 | for (int elem : arrayOfInts) { 151 | // do something 152 | } 153 | 154 | 155 | ``` 156 | 157 | 158 | ### Branching Statements 159 | 160 | ## Math 161 | 162 | `Math.random()` (between 0 and 1) 163 | `Math.ceil(double a)` 164 | `Math.floor(double a` 165 | `Math.sqrt(double a)` 166 | `Math.max(int a, int b)` (works for long, int, float, double) 167 | `Math.pow(double a, double b)` 168 | `Math.exp(double a)` 169 | 170 | ## Error Handling 171 | 172 | ```java 173 | try { 174 | int n = Integer.parseInt(s); 175 | System.out.println(n); 176 | } 177 | catch(Exception e) { 178 | System.out.println("Bad String"); 179 | } 180 | ``` 181 | ### Propagating Exceptions 182 | 183 | ```java 184 | class PropagatedException { 185 | 186 | void example() throws Exception{ 187 | throw new Exception("This exception will always be thrown."); 188 | } 189 | 190 | public static void main(String[] args) { 191 | PropagatedException p = new PropagatedException(); 192 | try{ 193 | p.example(); 194 | } 195 | catch(Exception e){ 196 | System.err.println( e.getClass().getSimpleName() + ": " + e.getMessage() ); 197 | } 198 | } 199 | } 200 | ``` 201 | 202 | ## Regular Expressions 203 | 204 | ```java 205 | String myRegEx = ".+@gmail\\.com$"; 206 | Pattern p = Pattern.compile(myRegEx); 207 | String firstName = in.next(); 208 | String emailID = in.next(); 209 | Matcher m = p.matcher(emailID); 210 | if (m.matches()) 211 | names.add(firstName); 212 | ``` -------------------------------------------------------------------------------- /ReviewOfBasicOOPConcepts.mdown: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GENERINCS 5 | 6 | INHERITANCE 7 | 8 | ALSO WHEN TO USE STATIC AND WHEN NOT - what does it mean to instantiate a class???- is it the same as using the constructor? shouldn't be because see node class for example 9 | 10 | 11 | ### Abstract Class 12 | This type of class can have abstract methods as well as defined methods, but it cannot be instantiated (meaning you cannot create a new instance of it). To use an abstract class, you must create and instantiate a subclass that **extends** the abstract class. Any abstract methods declared in an abstract class must be implemented by its subclasses (unless the subclass is also abstract). 13 | 14 | ### Class variables vs instance variables 15 | Class variables point to the same (static) variable across all instances of a class, and instance variables have distinct values that vary from instance to instance. 16 | 17 | ### Class Constructor 18 | Creates an instance of a class. A class can have one or more constructors that build different versions of the same type of object. A constructor with no parameters is called a default constructor; it creates an object with default initial values specified by the programmer. A constructor that takes one or more parameters (i.e.: values in parentheses) is called a parameterized constructor. Many languages allow you to have multiple constructors, provided that each constructor takes different types of parameters; these are called overloaded constructors. 19 | 20 | 21 | ### Comparable Interface 22 | Comparable is an public interfaces which is used to impose an natural ordering (if numbers then 1,2,3 or in alphabetical order 'a','b','c' ) of the class that implements it. 23 | 24 | ### Comparator Interface 25 | A comparison function, which is used to impose ordering on some collection of objects. To allow precisely control over the sort order , Comparators can be passed to a sort method (e.g Collections.sort()). Certain type of data structures such as TreeSet or TreeMap can also be sorted using Comparator. 26 | 27 | [TODO: include comparator example here] 28 | 29 | 30 | ### Inheritance 31 | 32 | class MySubclass *extends* MySuperclass 33 | 34 | ```java 35 | class MySubclass extends MySuperclass{ 36 | // subclass constructor: 37 | MySubclass(String myString){ 38 | // explicit call to superclass constructor: 39 | super(myString); 40 | } 41 | } 42 | ``` 43 | ```java 44 | class MySubclass extends MySuperclass{ 45 | MySubclass(String myString){ 46 | // behind-the-scenes implicit call to superclass' default constructor happens 47 | 48 | // subclass can now initialize superclass instance variable: 49 | this.myString = myString; 50 | } 51 | } 52 | ``` 53 | 54 | 55 | Note: If a superclass does not have a default constructor, any subclasses extending it must make an explicit call to one of the superclass' parameterized constructors. 56 | 57 | 58 | ### Interface 59 | A collection of abstract methods and constants that form a common set of base rules/specifications for those classes that implement it. Much like an abstract class, an interface cannot be instantiated and must be **implemented** by a class. 60 | 61 | 62 | ### Iterator 63 | An object that implements either the Iterator (or the ListIterator) interface. 64 | Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. 65 | 66 | ```java 67 | import java.util.*; 68 | public class IteratorDemo { 69 | 70 | public static void main(String args[]) { 71 | // Create an array list 72 | ArrayList al = new ArrayList(); 73 | 74 | // add elements to the array list 75 | al.add("C"); 76 | al.add("A"); 77 | al.add("E"); 78 | al.add("B"); 79 | al.add("D"); 80 | al.add("F"); 81 | 82 | // Use iterator to display contents of al 83 | System.out.print("Original contents of al: "); 84 | Iterator itr = al.iterator(); 85 | 86 | while(itr.hasNext()) { 87 | Object element = itr.next(); 88 | System.out.print(element + " "); 89 | } 90 | System.out.println(); 91 | } 92 | } 93 | ``` 94 | 95 | ### Generics 96 | 97 | ```java 98 | public static void printArray(T[] generic){ 99 | for(T element : generic) { 100 | System.out.println(element); 101 | } 102 | } 103 | ``` 104 | 105 | ### Serializible 106 | Means that instances of the class can be turned into a byte-stream (for example, to be saved to a file) and then converted back into classes again. This reloading could happen in a different instance of the program, or even on a different machine. 107 | 108 | ### Synchronization 109 | When an implementation is not synchronized it means that: If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it _must_ be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list: 110 | 111 | List list = Collections.synchronizedList(new LinkedList(...)); 112 | 113 | 114 | 115 | ### Visibility 116 | In Java, ordered from most visible to least, there are public, protected, package (default), and private visibilities. This means that if we do not specify it, by default the visibility is package. 117 | 118 | ```java 119 | package mytest.myvisibility; 120 | 121 | public class MyClass { 122 | public int myPublicInt; // visible to all 123 | protected myProtectedInt; // visible to subclasses of MyClass and to other members of the mytest.myvisibility package 124 | int myPackageInt; // visible only to other members of the mytest.myvisibility package 125 | private int myPrivateInt; // visible only to MyClass objects. 126 | } 127 | ``` 128 | 129 | ### equals vs == 130 | ``` 131 | String s1 = new String("HELLO"); 132 | String s2 = new String("HELLO"); 133 | System.out.println(s1 == s2); // false 134 | System.out.println(s1.equals(s2)); // true 135 | ``` 136 | 137 | 138 | ## Some other theoretical definitions 139 | 140 | ### P versus NP problem 141 | **P** - the general class of questions for which some algorithm can provide an answer in polynomial time 142 | **NP** - "nondeterministic polynomial" - the class of questions for which an answer can be verified in polynomial time 143 | **NPC** - "NP-complete" - problems that are harder to compute than to verify: they could not be solved in polynomial time, but the answer could be verified in polynomial time 144 | **NP-hard** - a class of problems that are, informally, "at least as hard as the hardest problems in NP." 145 | -------------------------------------------------------------------------------- /to_do.mdown: -------------------------------------------------------------------------------- 1 | TODO: 2 | 3 | * ADD FUNCTIONS TO EACH TYPE AND THEIR COMPLEXITIES (FIND A WAY TO NICELY FORMAT COMPLEXITY) 4 | * go through everything I learned so far and make a summary 5 | 6 | * use basic examples from hacker rank (ex static initialzation, error handling etc) 7 | * static initializ https://stackoverflow.com/questions/9379426/java-when-is-a-static-initialization-block-useful 8 | * string to int https://www.mkyong.com/java/java-convert-string-to-int/ 9 | * int to string: see corresp hakercode challenge and imp details at https://stackoverflow.com/questions/3930210/java-int-to-string-integer-tostringi-vs-new-integeri-tostring 10 | * 11 | 12 | * give credits to hacker rank, oracle tutorial, wikibooks, stackoverflow 13 | --------------------------------------------------------------------------------