Sorting Algos Flashcards
merge sort
function mergeArrs(arr1, arr2) {
let result = [];
let i = 0;
let j = 0;
while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) { result.push(arr1[i]); i++; } if (arr2[j] < arr1[i]) { result.push(arr2[j]); j++ } } while (i < arr1.length) { result.push(arr1[i]); i++ } while (j < arr2.length) { result.push(arr2[j]); j++; } return result; }
merge sort runtime
O(n*log n)
insertion sort
function insertion(arr) { for (let i = 0; i < arr.length; i++) { let key = arr[i]; let j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } return arr; }
insertion sort runtime
0(n*n)
Pathfinding and Maze Solving
DFS
Detecting Cycles in Graphs
DFS
Connected Components in Graphs
DFS
Topological Sorting (push to stack after visiting all dependencies)
DFS post-order
Solving Puzzles and Backtracking
DFS, backtracks when it finds deadends
Binary Tree Traversal
DFS
Binary Tree Traversal: Preorder
DFS, process root first
Binary Tree Traversal: inorder
DFS, process left subtree first
Binary Tree Traversal: postorder
DFS, process root last
Solving Island Problems in Grids
DFS, explore each island, traverse adjacent cells in multiple directions
Generating All Possible Subsets or Combos
DFS - explore each subset by including or excluding each el in set
Word Search in Grid
DFS explores each cell recursively to see if it can form word moving in all directions
Tree/Graph Cloning
DFS traverses each node in graph, copying it and connections to make identical copy
DFS - inorder
function inorder(root) {
let result = [];
function traverse(node) {
if (node) {
traverse(node.left);
result.push(node.value);
traverse(node.right)
}
}
traverse(root)
return result;
}
DFS -preorder
function preorder(root) {
let result = [];
function traverse(node) {
if (node) {
result.push(node.value);
traverse(node.left);
traverse(node.right);
}
}
traverse(root)
return result;
}
post order
function postorder(root) {
let result = [];
function traverse(node) {
if (node) {
traverse(node.left);
traverse(node.right);
result.push(node.value);
}
}
traverse(root)
return result;
}
delete at position in linked list
function deletePosition(list, position) {
if (list === null) return null;
if (position === 1) {
return list.next;
}
let prev = list;
let curr = list.next;
let count = 2;
while (curr && count < position) {
prev = curr;
curr = curr.next;
count++;
}
prev.next = curr.next;
return list;
}
delete head linked list
function deleteHead(list, node) {
if (list === null) return null;
list = list.next;
return list;
}
delete tail linked list
function deleteNode(list) {
if (!list || list.next === null) return null;
let prev = list;
let curr = list.next;
while (curr.next) {
prev = curr;
curr = curr.next
}
prev.next = null;
return list;
}