You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
choose pivot (usually rightmost), between lo and hi find all lower than pivot, insert pivot when lo = hi. Probably good for partially sorted data. choosing a random partition makes worst case less likely for a bad array.
(check if more than just these two) bucket sort good for uniformially distributed data or we could have tons of empty buckets Create buckets, hash values to each bucket, sort buckets individually, iterate buckets one by one to sorted array.
best for keys in a small specific range make array size of data range, add number of values appearances up in counting array. Use counting array to create sorted array.
Use insetion Sort on sub arrays. Sub arrays are determined by an interval: h = h*3+1. Shrink interval. Useful for sorting small arrays in place, worst case is better than some other algos. Also simplier to implement
Need practice for linked list, binary search, and others. Bottom up or top down. Bottom-up think mergesort - solve small subsets, then combine result. top-down - ?
Memomiztion and bottom up. Memomization - solve each problem, cache results i.e. making a fib call to each number once. Bottom-up solve the small problems, use the results to add to your new set of sub-problems i.e. step counting problem, only set amount of ways to reach a new step, add prev totals also. start with recursion then cache the result. Bottom up => build from previous, Top down => save results, check if you already solved
With 802 digit at place 2 is 8, place 1 is 0, place 0 is 2
Extra
BitSet & BitVector classes - 8.4 bits
8.9, possible common FB question 2D array
Review LinkedList Recursion
Super usage, ctci 3.2
External sort, ctci 10.6
BFS 4.1, look at code
5.3 look at code
1.6, string builder ops
Data Structures
LinkedList
Whatever you do, do not sort it
Implementation
implement Node(), appendToTail(), deleteNode(Object data)
Run Times - Single and Double
O(n)Θ(n) Access, search
O(1)Θ(1) Insert, delete
Space
O(n)
Binary Tree
Implementation/* Inorder - left subtree, root, right subtree * Preorder - left subtree, right subtree, root. Bottom up. * Postorder - root, left subtree, right subtree. Start with root, recurse through left, recurse through right. top down. */publicstaticvoidinOrder(TreeNodenode) {
/* * Searched smallest to largest */if (node != null) {
inOrder(node.left);
System.out.println(node.data);
inOrder(node.right);
}
}
publicstaticvoidpreOrder(TreeNodenode) {
/* * Check the root first */if (node != null) {
System.out.println(node.data);
preOrder(node.left);
preOrder(node.right);
}
}
publicstaticvoidpostOrder(TreeNodenode) {
/* * Root is always last visited */if (node != null) {
postOrder(node.right);
postOrder(node.left);
System.out.println(node.data);
}
}
RunTimesInsertWorst/Avg. O(log(n)), findanyworstO(log(n)), createworstO(nlog(n))
SpaceO(n)
Hash(Maps, Sets, Tables)
Implementation
key % hashTableSize
Use an array of lists to store the values.
If there is a collision append the value to that keys location in the array.
Run Times
Θ(1) lookup, insert, delete
This is amortized based off if the hash function has no collisions - worst is O(n) for above
Space
O(n) Best and worst
HashMap - Not Synchronized, not thread safe, but faster. Allows nulls.
HashTable - Synchronized, slower, thread safe. Does not allow nulls.
HashSet - Does not allow duplicate values, use when we need a unique list.
Stack
Implementation (Not Done)
pop() push() peek(), use Obeject data for node data
Run Times
O(1)Θ(1) push, pop, head
O(n) search
Space
O(n)Θ(n) search, access
Queue
Implementation (Not Done)
enqueue(), dequeue(), size(), peek()
Run Times
O(1)Θ(1) enqueue(), dequeue(), peek()
O(n)Θ(n) search, access
Space
O(n)
Graphs
Implementation (Need construction of a graph)
Implement by..
Run Times
O
Trie
Implementation (Not Done)
implement by...
Run Times
O
Heap
Implementation/* * Insert - insert element at bottom, rightmost spot => bubble up swapping with parent * Extract min/max - remove root by swapping with bottommost rightmost element => bubble down */publicstaticvoidheapInsert(int[] heap, intvalue) {
heap[tailIndex] = value;
bubbleUp(heap, tailIndex);
tailIndex++;
}
privatestaticvoidbubbleUp(int[] heap, intindex) {
if (index == 0) {return;}
intparentIndex = (int) Math.floor((index-1)/2);
if (heap[index] > heap[parentIndex]) {
swap(heap, index, parentIndex);
bubbleUp(heap, parentIndex);
}
}
publicstaticintextractMax(int[] heap) {
intmax = heap[0];
heap[0] = heap[tailIndex];
heap[tailIndex] = max;
tailIndex--;
bubbleDown(heap, 0);
returnmax;
}
privatestaticvoidbubbleDown(int[] heap, intindex) {
if (index >= tailIndex) {return;}
intleftChild = (2*index)+1;
intrightChild = (2*index)+2;
if (leftChild >= tailIndex) return;
// If right child exists and is greater than the left child// Compare heap[index] with right childif (rightChild <= tailIndex && heap[leftChild] < heap[rightChild] && heap[index] < heap[rightChild]) {
swap(heap, index, rightChild);
bubbleDown(heap, rightChild);
}
// Else we can compare the left child elseif (heap[index] < heap[leftChild]) {
swap(heap, index, leftChild);
bubbleDown(heap, leftChild);
}
}
RunTimesΘ(logn) O(logn) Extractandinsert <=makesureSpaceO(n)
Vector + ArrayList
Implementation (Not Done)
implement by...
Run Times
O
ImplementationPickpartition (middleoflow-high).
Putallelementslowerthanpartitiontotheleft, allelementshighertotheright.
performquicksortonlow-partition-1, partition+1-high.
voidsort(intarr[], intlow, inthigh)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is now at right place */intpi = partition(arr, low, high);
// Recursively sort elements before// partition and after partitionsort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
/* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */intpartition(intarr[], intlow, inthigh)
{
intpivot = arr[high];
inti = (low-1); // index of smaller elementfor (intj=low; j<high; j++)
{
// If current element is smaller than or// equal to pivotif (arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]inttemp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)inttemp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
returni+1;
}
RunTimesΘ(nlog(n)) O(n^2) - RandomizedpivotmakesO(nlogn) muchmorelikelySpaceO(log(n))
Bucket Sort
Implementation// Like using hash functions. // To choose which bucket to put value in: ((value-minvalue) / bucketSize). // Sort the buckets individually, then place back into original array.RunTimesΘ(n+k) O(n^2) - wherekisnumberofbucketsSpaceO(n) - numberofbuckets
Radix Sort
Implementationprivatestaticint[] sort(int[] array) {
// Find the maximum number to know number of digitsintm = getMax(array, array.length);
// Do counting sort for every digit. Note that instead// of passing digit number, exp is passed. exp is 10^i// where i is current digit numberfor (intexp = 1; m/exp > 0; exp *= 10) {
countSort(array, array.length, exp);
}
returnarray;
}
RunTimesΘ(nk) O(nk) => kisrangeadigitcanbe. innormaldecimalitis0-9 (or10).
SpaceO(n+k)
Counting Sort
Implementation/* For simplicity, consider the data in the range 0 to 9. Input data: 1, 4, 1, 2, 7, 5, 2 1) Take a count array to store the count of each unique object. Index: 0 1 2 3 4 5 6 7 8 9 Count: 0 2 2 0 1 1 0 1 0 0 2) Modify the count array such that each element at each index stores the sum of previous counts. Index: 0 1 2 3 4 5 6 7 8 9 Count: 0 2 4 4 5 6 6 7 7 7 The modified count array indicates the position of each object in the output sequence. 3) Output each object from the input sequence followed by decreasing its count by 1. Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 2. Put data 1 at index 2 in output. Decrease count by 1 to place next data 1 at an index 1 smaller than this index. */voidsort(chararr[])
{
intn = arr.length;
// The output character array that will have sorted arrcharoutput[] = newchar[n];
// Create a count array to store count of inidividul// characters and initialize count array as 0intcount[] = newint[256];
for (inti=0; i<256; ++i)
count[i] = 0;
// store count of each characterfor (inti=0; i<n; ++i)
++count[arr[i]];
// Change count[i] so that count[i] now contains actual// position of this character in output arrayfor (inti=1; i<=255; ++i)
count[i] += count[i-1];
// Build the output character arrayfor (inti = 0; i<n; ++i)
{
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
// Copy the output array to arr, so that arr now// contains sorted charactersfor (inti = 0; i<n; ++i)
arr[i] = output[i];
}
RunTimesΘ(n+k) O(n+k) - nisnumberofelements, kisrangeelementscanbefrom1-k. i.e. onlyvalues0to9appearinanarray, k=9SpaceO(k)
BFS
Implementation (Not Done)
Using a Queue -> Need to mark visited nodes if we are worried about a cycle.
I.e. BFS of a binarytree does not need to mark nodes
Run Times
O
DFS
Implementation (Not Done)
Recursion, track the depths
Run Times
O
*Selection Sort
Implementation
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
Run Times
Θ(n^2) O(n^2)
Space
O(1)
*Insertion Sort
Implementation/* Step 1 − If it is the first element, it is already sorted. return 1; Step 2 − Pick next element Step 3 − Compare with all elements in the sorted sub-list Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be sorted Step 5 − Insert the value Step 6 − Repeat until list is sorted */privatestaticint[] insertionSort(int[] array) {
for (inti = 1; i < array.length; i++) {
for (intj = 0; j < i; j++) {
// Found where to insert iif (array[i] <= array[j] ) {
array = insert(array, i, j);
}
}
}
returnarray;
}
privatestaticint[] insert(int[] array, intindexToInsertFrom, intindexToInsertAt) {
intvalueToInsert = array[indexToInsertFrom];
for (inti = indexToInsertFrom; i > indexToInsertAt; i--){
array[i] = array[i-1];
}
array[indexToInsertAt] = valueToInsert;
returnarray;
}
RunTimesΘ(n^2) O(n^2)
*Heap Sort
Implementation/* HeapSort - Remove root, insert at end, heapify the remaining nodes * children at indices 2i + 1 and 2i + 2 * parent at index floor((i − 1) ∕ 2) */publicstaticintextractMax(int[] heap) {
intmax = heap[0];
heap[0] = heap[tailIndex];
heap[tailIndex] = max;
tailIndex--;
bubbleDown(heap, 0);
returnmax;
}
privatestaticvoidbubbleDown(int[] heap, intindex) {
if (index >= tailIndex) {return;}
intleftChild = (2*index)+1;
intrightChild = (2*index)+2;
if (leftChild >= tailIndex) return;
// If right child exists and is greater than the left child// Compare heap[index] with right childif (rightChild <= tailIndex && heap[leftChild] < heap[rightChild] && heap[index] < heap[rightChild]) {
swap(heap, index, rightChild);
bubbleDown(heap, rightChild);
}
// Else we can compare the left child elseif (heap[index] < heap[leftChild]) {
swap(heap, index, leftChild);
bubbleDown(heap, leftChild);
}
}
RunTimesΘ(nlog(n)) O(nlog(n))
SpaceO(1) takesO(n) tomaintainstructure
*Tree Sort
Implementation (Not Done)
implement by...
Run Times
O
*Cube Sort
Implementation (Not Done)
implement by...
Run Times
O
*Shell Sort
Implementation/* Step 1 − Initialize the value of h Step 2 − Divide the list into smaller sub-list of equal interval h Step 3 − Sort these sub-lists using insertion sort Step 3 − Repeat until complete list is sorted */privatestaticint[] shellSort(int[] array) {
intinterval = 0;
while( interval < array.length / 3) {
interval = interval * 3 + 1;
}
for (; interval > 0; interval-- ) {
for (inti = 0; i < interval; i++) {
array = sortIntervalValues(array, interval, i);
}
}
returnarray;
}
privatestaticint[] sortIntervalValues(int[] array, intintervalSize, intstartLoc) {
intinterval = startLoc;
while (interval < array.length) {
intminIndex = getMinIndexFromInterval(array, interval, intervalSize);
array = swapAndShiftWithInterval(array, minIndex, interval, intervalSize);
interval += intervalSize;
}
returnarray;
}
privatestaticint[] swapAndShiftWithInterval(int[] array, intminIndex, intindexToInsert, intintervalSize) {...}
privatestaticintgetMinIndexFromInterval(int[] array, intinterval, intintervalSize) {...}
RunTimesΩ(nlog(n))
Θ(n(log(n))^2)
O(n(log(n))^2)
SpaceO(1)