1. Home
  2. Explore
  3. Computer Science
  4. Key Computer Science Algorithms

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Key Computer Science Algorithms

Famous Computer Science Algorithms - Study Notes

Recursion

What is Recursion?

Recursion is a problem-solving strategy where a function calls itself within its own body. The key to designing recursive algorithms is identifying two components:

  • Base case(s): a condition where the answer is known directly, without further recursion

  • Recursive case(s): a condition where the function calls itself on a smaller subproblem

This approach follows the divide and conquer paradigm: break a large problem into smaller subproblems, solve those subproblems (recursively or directly), and combine their solutions to solve the original problem.

Fibonacci Sequence: A Classic Recursive Example

The Fibonacci sequence is defined as: 1,1,2,3,5,8,13,21,…1, 1, 2, 3, 5, 8, 13, 21, \ldots1,1,2,3,5,8,13,21,… where each term is the sum of the two previous terms.

Recursive definition:

  • Base cases: F(1)=1F(1) = 1F(1)=1, F(2)=1F(2) = 1F(2)=1

  • Recursive case: F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2) for n>2n > 2n>2

Naive recursive implementation has time complexity Θ(2n)\Theta(2^n)Θ(2n) because it repeatedly recalculates the same values. For example, F(5)F(5)F(5) calls F(4)F(4)F(4) and F(3)F(3)F(3), which themselves call overlapping subproblems.

Memoization improves this dramatically by storing already computed results in a cache (often a dictionary or array). Before computing a value, the algorithm checks the cache; if the value exists, it returns it directly. This reduces time complexity to Θ(n)\Theta(n)Θ(n) but uses Θ(n)\Theta(n)Θ(n) space for the cache.

Iterative Fibonacci uses only two variables to track the last two terms:

let last = 1, secondLast = 1;
for (let i = 2; i < n; i++) {
    let temp = last;
    last = last + secondLast;
    secondLast = temp;
}
return last;

This runs in Θ(n)\Theta(n)Θ(n) time and Θ(1)\Theta(1)Θ(1) space — the most efficient approach for Fibonacci.

Binary Tree Traversal (Recursive)

Three common recursive traversals of a binary tree:

  • Inorder: left subtree → node → right subtree

  • Preorder: node → left subtree → right subtree

  • Postorder: left subtree → right subtree → node

The base case is when the node is null (empty), at which point the function simply returns. The recursive cases call the same function on the left and right children.

String Reversal with Recursion

A string can be reversed recursively by defining:

  • Base case: empty string → return empty string

  • Recursive case: reverse(str) = reverse(str.slice(1)) + str[0]

This moves the first character to the end after reversing the remainder. In practice, using an array to collect characters is more space-efficient because string concatenation in many languages is O(k)O(k)O(k) (where kkk is the length), while appending to an array is amortized O(1)O(1)O(1).


Searching Algorithms

Linear Search

Linear search examines every element of an array until the target is found or all elements have been checked. Time complexity is O(n)O(n)O(n) — in the worst case, the target may be the last element or not present.

Binary Search

Binary search works only on sorted arrays. It repeatedly divides the search interval in half by comparing the target to the middle element:

  • If the target equals the middle element, the search is complete.

  • If the target is smaller, search the left half.

  • If the target is larger, search the right half.

Time complexity is O(log⁡2n)O(\log_2 n)O(log2​n). Each step halves the remaining data, so a sorted array of 1000 elements requires at most about 10 comparisons.

Recursive implementation uses a helper function that takes the array, target, start index, and end index. The base case occurs when start > end (element not found). The recursive case recalculates the middle and calls itself on the appropriate half.

Depth-First Search (DFS) and Breadth-First Search (BFS)

Both algorithms traverse graph or grid structures. They are illustrated with a maze represented as a 2D array where is open space, # is a wall, and X is the goal.

DFS uses a stack (Last In, First Out). It explores as far as possible along each branch before backtracking. In a maze, DFS will follow one path deep into the maze, only switching paths when it hits a dead end.

BFS uses a queue (First In, First Out). It explores all neighbors of the current node before moving to the next level. In a maze, BFS expands outward like a wave, ensuring it finds the shortest path (in terms of number of steps) if all edges have equal weight.

Both algorithms need a visited set to prevent revisiting nodes and infinite loops. The visited set stores serialized string representations of positions (e.g., "y,x") because JavaScript sets compare by reference for arrays, not by value.

Time complexity for both DFS and BFS on a grid of width WWW and height HHH is O(W×H)O(W \times H)O(W×H), assuming the stack/queue operations are O(1)O(1)O(1). However, using a JavaScript array as a queue (with shift()) degrades BFS to O((W×H)2)O((W \times H)^2)O((W×H)2) because shift() is O(n)O(n)O(n). Using a proper linked-list queue keeps BFS at linear time.

The order of neighbor exploration affects the path DFS finds. By changing the order in which left, right, top, and bottom are added to the stack, DFS can produce different traversals of the same maze.


Sorting Algorithms

Sorting Algorithm Properties

  • Stable: elements with equal keys maintain their original relative order after sorting

  • In-place: the algorithm sorts the array by mutating it directly, using only O(1)O(1)O(1) extra space

Inefficient Sorts ( O(n2)O(n^2)O(n2) )

These are simple to understand but perform poorly on large datasets.

Selection Sort

Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion and swaps it with the first element of the unsorted portion.

  • Unstable (in typical implementations)

  • Time: O(n2)O(n^2)O(n2) — the sum n+(n−1)+…+1=n(n+1)/2≈O(n2)n + (n-1) + \ldots + 1 = n(n+1)/2 \approx O(n^2)n+(n−1)+…+1=n(n+1)/2≈O(n2)

  • Space: O(1)O(1)O(1) (in-place)

Example: [4,6,1,2,3,9] → find minimum 1, swap with 4 → [1,6,4,2,3,9] → sorted prefix [1] → repeat on [6,4,2,3,9] → find 2, swap with 6 → [1,2,4,6,3,9] → continue.

Insertion Sort

Insertion sort builds a sorted portion at the left of the array. Each new element from the unsorted part is inserted into its correct position in the sorted part by shifting larger elements to the right.

  • Stable

  • Time: O(n2)O(n^2)O(n2) worst case; O(n)O(n)O(n) best case (already sorted or nearly sorted)

  • Space: O(1)O(1)O(1) (in-place)

  • Excellent for partially sorted data because insertions are few.

Example: Start with [4] sorted. Next element 6 is larger → [4,6]. Next 1 is smaller than 6, shift 6 right, then smaller than 4, shift 4 right → [1,4,6]. Continue.

Bubble Sort

Bubble sort repeatedly steps through the list, comparing adjacent elements and swapping them if they are in the wrong order. Each pass "bubbles" the largest (or smallest) element to its correct position.

  • Stable

  • Time: O(n2)O(n^2)O(n2)

  • Space: O(1)O(1)O(1) (in-place)

  • Can be optimized to stop early if no swaps occur in a pass.

Example: [4,6,1,2,3,9] → compare 4,6 (no swap) → 6,1 (swap → [4,1,6,2,3,9]) → 6,2 (swap) → 6,3 (swap) → 6,9 (no swap). After one pass, largest element 9 is at the end. Repeat on remaining unsorted portion.

Efficient Sorts ( O(nlog⁡n)O(n \log n)O(nlogn) )

These algorithms are more complex but scale well.

Merge Sort

Merge sort is a divide and conquer algorithm:

  1. Recursively divide the array into halves until each subarray has one element (base case)

  2. Merge the sorted subarrays back together

Merging two sorted arrays uses two pointers and compares elements one by one, building a new sorted array.

  • Stable

  • Time: O(nlog⁡n)O(n \log n)O(nlogn) — the array is divided log⁡2n\log_2 nlog2​n times, and merging each level takes O(n)O(n)O(n)

  • Space: O(n)O(n)O(n) (requires temporary arrays for merging)

Merge process example: Left [1,4,6], Right [2,3,9] → compare 1 and 2, pick 1 → compare 4 and 2, pick 2 → compare 4 and 3, pick 3 → compare 4 and 9, pick 4 → compare 6 and 9, pick 6 → pick remaining 9 → result [1,2,3,4,6,9].

The recursion tree splits the array until single elements, then merges upward.

Heap Sort

Heap sort uses a binary heap data structure:

  1. Build a max-heap from the array (or min-heap for descending order) — O(n)O(n)O(n) time using heapify

  2. Repeatedly extract the root (maximum element) and place it at the end of the array, then restore the heap property — O(log⁡n)O(\log n)O(logn) per extraction

  • Unstable

  • Time: O(nlog⁡n)O(n \log n)O(nlogn) — building heap O(n)O(n)O(n), nnn extractions each O(log⁡n)O(\log n)O(logn)

  • Space: O(1)O(1)O(1) (in-place)

Conceptual example: Insert all elements into a max-heap. Then repeatedly take the root (largest) and put it in a new sorted array. The heap rebuilds after each removal.

Quicksort

Quicksort selects a pivot element and partitions the array such that all elements less than the pivot come before it, and all greater come after. It then recursively sorts the two partitions.

  • Unstable

  • Time: Average O(nlog⁡n)O(n \log n)O(nlogn), worst case O(n2)O(n^2)O(n2) (rare with good pivot selection)

  • Space: O(log⁡n)O(\log n)O(logn) (due to recursion stack)

  • Most implementations of built-in sort functions in programming languages use a variant of quicksort (e.g., introsort).

The algorithm is not covered in full detail in this course, but its core idea is partitioning around a pivot.

Summary Table of Sorting Algorithms

  • Selection sort: O(n2)O(n^2)O(n2), unstable, in-place

  • Insertion sort: O(n2)O(n^2)O(n2) (best O(n)O(n)O(n)), stable, in-place

  • Bubble sort: O(n2)O(n^2)O(n2), stable, in-place

  • Merge sort: O(nlog⁡n)O(n \log n)O(nlogn), stable, requires O(n)O(n)O(n) extra space

  • Heap sort: O(nlog⁡n)O(n \log n)O(nlogn), unstable, in-place

  • Quicksort: Average O(nlog⁡n)O(n \log n)O(nlogn), unstable, in-place (with O(log⁡n)O(\log n)O(logn) stack)


Pathfinding Algorithms

Dijkstra's Algorithm

Dijkstra's algorithm finds the shortest path from a single source vertex to all other vertices in a weighted, undirected graph (works for directed graphs as well, with non-negative edges).

Setup:

  • A distance table with three columns: vertex, shortest distance from source (initialized to ∞ except source = 0), and previous vertex (to reconstruct paths)

  • A visited set to track processed vertices

  • A min-heap (priority queue) to efficiently retrieve the vertex with the smallest current distance

Algorithm steps:

  1. Initialize source distance to 0, all others to ∞.

  2. While there are unvisited vertices: a. Extract the unvisited vertex with the smallest distance (using min-heap). b. For each unvisited neighbor, calculate the distance through the current vertex: currentDist + edgeWeight. c. If this new distance is less than the stored distance, update the table and the heap. d. Mark the current vertex as visited.

Example walkthrough on a small graph (vertices A, B, C, D, E with edge weights):

  • Start at A: distances to B=1, C=6. Set previous: B←A, C←A.

  • Visit B (shortest unvisited): from B to C distance 1+2=3 (better than 6, update C←B), to D distance 1+1=2 (update D←B).

  • Visit D: from D to C distance 2+2=4 (not better than 3), to E distance 2+5=7 (update E←D).

  • Visit C: from C to E distance 3+5=8 (not better than 7).

  • Visit E: no unvisited neighbors.

  • Final distances: A=0, B=1, C=3, D=2, E=7. Shortest path to E: A→B→D→E (weight 7).

Time complexity: With a binary heap, O((V+E)log⁡V)O((V+E) \log V)O((V+E)logV), where VVV is the number of vertices and EEE the number of edges. This comes from VVV extract-min operations and EEE decrease-key operations, each O(log⁡V)O(\log V)O(logV).

A* Algorithm (Overview)

A (A-star)* is an extension of Dijkstra's algorithm used for finding the shortest path to a single destination. It adds a heuristic to guide the search, making it more efficient than Dijkstra's when a goal is specified.

  • The heuristic estimates the remaining distance from a node to the goal (e.g., Euclidean distance in a grid).

  • The priority of a node is current shortest distance + heuristic.

  • By prioritizing nodes closer to the goal, A* often explores far fewer nodes than Dijkstra's.

  • A* requires the heuristic to be admissible (never overestimates the true cost) to guarantee optimality.

Example: In a grid maze, instead of expanding uniformly in all directions, A* expands toward the target, avoiding unnecessary exploration of opposite regions.


Minimum Spanning Tree (MST)

A spanning tree of a connected, undirected graph is a subset of edges that connects all vertices without forming cycles. The minimum spanning tree (MST) is the spanning tree with the smallest total edge weight.

Kruskal's Algorithm

Kruskal's algorithm builds the MST by repeatedly selecting the cheapest edge that does not create a cycle.

Steps:

  1. Sort all edges by weight in ascending order.

  2. Initialize an empty set of edges for the MST.

  3. Initialize a union-find data structure to keep track of connected components.

  4. For each edge (u, v) in sorted order:

    • If u and v are in different components (adding the edge does not create a cycle), add the edge to the MST and union the components.

  5. Stop when the MST has exactly V−1V-1V−1 edges (where VVV is the number of vertices).

Example graph with vertices A, B, C, D, E and edges sorted by weight:

  • Edges: (B-D, weight 1), (A-B, 1), (B-C, 2), (C-D, 2), (D-E, 5), (C-E, 5), (A-C, 6)

  • Process: add (B-D), add (A-B), add (B-C) → MST now has 3 edges. Next edge (C-D) would create cycle B-C-D-B, so skip. Add (D-E) → total edges = 4 = V-1. MST weight = 1+1+2+5 = 9.

  • Alternative MST: replace (B-C) with (C-E) of weight 5 yields same total weight 9.

Time complexity: Sorting edges takes O(Elog⁡E)O(E \log E)O(ElogE). Each union-find operation takes about O(α(V))O(\alpha(V))O(α(V)) (inverse Ackermann, nearly constant). Overall O(Elog⁡E)O(E \log E)O(ElogE), which is equivalent to O(Elog⁡V)O(E \log V)O(ElogV) because E≤V2E \leq V^2E≤V2 implies log⁡E≤2log⁡V\log E \leq 2 \log VlogE≤2logV.

Prim's Algorithm (Mentioned)

Prim's algorithm is another MST algorithm that grows the MST from a starting vertex by repeatedly adding the smallest edge connecting the tree to a vertex outside it. It is not covered in detail in this material but is a common alternative to Kruskal's.


Dynamic Programming

Dynamic programming is a technique for solving optimization problems by breaking them into overlapping subproblems, solving each subproblem once, and storing their results (often using memoization or tabulation) to avoid redundant work.

Minimum Sum Subarray (Kadane's Algorithm Variant)

Problem: Given an array of integers, find the minimum possible sum of any contiguous subarray.

Naive approach: Compute the sum of every possible subarray. This requires O(n2)O(n^2)O(n2) subarrays (each sum computed in O(k)O(k)O(k)) leading to O(n3)O(n^3)O(n3) time.

Dynamic programming solution (O(n)O(n)O(n) time, O(1)O(1)O(1) space): Define minEnding[i] as the minimum sum of a contiguous subarray that ends at index i. The recurrence is:

minEnding[i]=min⁡(array[i],array[i]+minEnding[i−1])\text{minEnding}[i] = \min( \text{array}[i], \text{array}[i] + \text{minEnding}[i-1] )minEnding[i]=min(array[i],array[i]+minEnding[i−1])

This states that the best subarray ending at i either consists of only the element at i, or includes the element at i plus the best subarray ending at i-1. The overall minimum subarray sum is the minimum of all minEnding[i].

Example walkthrough: Array: [20, -7, -3, 9, -4, 6, -9, 10]

  • i=0: minEnding = 20, global min = 20

  • i=1: minEnding = min(-7, -7+20) = -7, global min = -7

  • i=2: minEnding = min(-3, -3+(-7)) = -10, global min = -10

  • i=3: minEnding = min(9, 9+(-10)) = -1, global min remains -10

  • i=4: minEnding = min(-4, -4+(-1)) = -5, global min = -10

  • i=5: minEnding = min(6, 6+(-5)) = 1, global min = -10

  • i=6: minEnding = min(-9, -9+1) = -9, global min = -10

  • i=7: minEnding = min(10, 10+(-9)) = 1, global min = -10

Minimum subarray sum is -10 (the subarray [-7, -3] or [-7, -3, 9, -4, 6] would not be contiguous? Wait, check: subarray [-7, -3] gives -10, yes contiguous. The DP correctly tracks the best ending at each index.

Space optimization: Instead of storing all minEnding values, only the previous value is needed. This reduces space from O(n)O(n)O(n) to O(1)O(1)O(1).

Pseudocode:

function minSubarraySum(arr):
    if arr.length == 0: return 0
    minEndingPrev = arr[0]
    globalMin = arr[0]
    for i from 1 to arr.length-1:
        minEndingCurr = min(arr[i], arr[i] + minEndingPrev)
        globalMin = min(globalMin, minEndingCurr)
        minEndingPrev = minEndingCurr
    return globalMin

This classic example illustrates how dynamic programming transforms an exponential or quadratic problem into a linear-time solution by reusing results of subproblems.


End of study notes.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent