10 ALGORITHMS

Algorithm Arcade

Mind-bending algorithms that will change how you think about code.
Each one is a small miracle of human ingenuity.

10 Algorithms
2300+ Years of History
Brain Cells Lost
Start Exploring

The Collection

Click any card to reveal the code and secrets within

#01

Collatz Conjecture

The Simplest Impossible Problem

Pick any positive integer. If it's even, divide by 2. If it's odd, multiply by 3 and add 1. Repeat. It ALWAYS reaches 1... but nobody on Earth can prove why. Mathematicians have checked every number up to 2^68 — still no proof.

Unknown — that's the whole point
#01

Collatz Conjecture

algorithm.js
function collatz(n) {
  let steps = [n];
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    steps.push(n);
  }
  return steps;
}
Fun Fact

Paul Erdős said: 'Mathematics is not yet ready for such problems.' There's a $500 bounty on it — still unclaimed since 1937.

#02

Floyd's Tortoise & Hare

Two Pointers, One Truth

How do you detect a cycle in a linked list using O(1) memory? Send two pointers — one moves 1 step, the other 2 steps. If there's a cycle, they MUST meet. It's mathematically inevitable. Then, to find where the cycle starts, reset one pointer to the head and move both at speed 1.

O(n) time, O(1) space
#02

Floyd's Tortoise & Hare

algorithm.js
function detectCycle(head) {
  let slow = head, fast = head;
  while (fast?.next) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) {
      slow = head;
      while (slow !== fast) {
        slow = slow.next;
        fast = fast.next;
      }
      return slow; // cycle start
    }
  }
  return null;
}
Fun Fact

Robert Floyd never formally published this algorithm. It spread through oral tradition among computer scientists in the 1960s.

#03

Fisher-Yates Shuffle

The Only Fair Shuffle

Most 'random' shuffles are biased. Fisher-Yates is the ONLY algorithm that gives every permutation exactly equal probability. Walk backwards through the array, swapping each element with a random one before it (including itself). That's it. Perfect randomness.

O(n) time, O(1) space
#03

Fisher-Yates Shuffle

algorithm.js
function shuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(
      Math.random() * (i + 1)
    );
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}
Fun Fact

A naive shuffle (swap each element with any random position) creates a biased distribution. For 3 elements, it produces 27 outcomes mapped to 6 permutations — impossible to distribute evenly.

#04

Boyer-Moore Majority Vote

Cancellation Magic

Find the element that appears more than n/2 times in an array — using O(1) space. The trick? Keep a candidate and a counter. When you see your candidate, increment. Otherwise, decrement. When counter hits 0, switch candidates. The majority element always survives the cancellation war.

O(n) time, O(1) space
#04

Boyer-Moore Majority Vote

algorithm.js
function majorityElement(nums) {
  let candidate = null, count = 0;
  for (const num of nums) {
    if (count === 0) candidate = num;
    count += num === candidate ? 1 : -1;
  }
  return candidate;
}
Fun Fact

Imagine an arena where different numbers fight each other. Each fight eliminates one of each type. The majority element has more soldiers than all others combined — it always has survivors.

#05

Sieve of Eratosthenes

2,200 Years of Prime Finding

Ancient Greek mathematician Eratosthenes invented this in ~240 BC. Start with all numbers. 2 is prime — cross out all its multiples. Next uncrossed number (3) is prime — cross out its multiples. Repeat. What survives is every prime number. Brutally simple, shockingly fast.

O(n log log n) time
#05

Sieve of Eratosthenes

algorithm.js
function sieve(limit) {
  const primes = new Array(limit + 1)
    .fill(true);
  primes[0] = primes[1] = false;
  for (let i = 2; i * i <= limit; i++) {
    if (primes[i]) {
      for (let j = i * i; j <= limit; j += i)
        primes[j] = false;
    }
  }
  return primes.flatMap(
    (v, i) => v ? [i] : []
  );
}
Fun Fact

Eratosthenes also calculated Earth's circumference to within 2% accuracy using shadows and geometry. The man was a polymath machine.

#06

Kadane's Algorithm

Maximum Subarray in One Pass

Given an array of integers (positive and negative), find the contiguous subarray with the largest sum. Brute force is O(n³). Kadane does it in ONE PASS: at each position, either extend the current subarray or start fresh. That's the entire insight. Beautiful greed.

O(n) time, O(1) space
#06

Kadane's Algorithm

algorithm.js
function maxSubarray(nums) {
  let maxSum = nums[0];
  let current = nums[0];
  for (let i = 1; i < nums.length; i++) {
    current = Math.max(
      nums[i],
      current + nums[i]
    );
    maxSum = Math.max(maxSum, current);
  }
  return maxSum;
}
Fun Fact

This was originally a O(n log n) divide-and-conquer solution by Shamos. Jay Kadane stunned everyone by solving it in O(n) during a seminar — on the spot.

#07

Binary Exponentiation

Powers in Logarithmic Time

Computing a^n normally takes n multiplications. Binary exponentiation does it in log(n). The secret: a^13 = a^8 × a^4 × a^1 (because 13 = 1101 in binary). Square the base repeatedly and multiply when the corresponding bit is 1. Used in all modern cryptography.

O(log n) time
#07

Binary Exponentiation

algorithm.js
function power(base, exp, mod) {
  let result = 1;
  base %= mod;
  while (exp > 0) {
    if (exp % 2 === 1)
      result = (result * base) % mod;
    exp = Math.floor(exp / 2);
    base = (base * base) % mod;
  }
  return result;
}
Fun Fact

RSA encryption relies on this. When your browser shows that little lock icon, binary exponentiation is doing modular arithmetic with 2048-bit numbers behind the scenes.

#08

Reservoir Sampling

Random Pick from Infinity

You have a stream of unknown (possibly infinite) length. You need to pick exactly k items uniformly at random, but you can only pass through the data ONCE and can't store it all. Reservoir sampling: keep the first k items, then for each new item i, replace a random reservoir item with probability k/i. Proof: each item has exactly k/n chance.

O(n) time, O(k) space
#08

Reservoir Sampling

algorithm.js
function reservoirSample(stream, k) {
  const reservoir = stream.slice(0, k);
  for (let i = k; i < stream.length; i++){
    const j = Math.floor(
      Math.random() * (i + 1)
    );
    if (j < k) reservoir[j] = stream[i];
  }
  return reservoir;
}
Fun Fact

Google uses reservoir sampling to select random search queries for analysis. They can't store every query — the stream never ends.

#09

Euclidean Algorithm

The Oldest Algorithm Still in Use

Finding the Greatest Common Divisor. Euclid discovered this around 300 BC: GCD(a, b) = GCD(b, a mod b). Keep taking remainders until you hit 0. The last non-zero value is your GCD. It's the oldest known non-trivial algorithm and it's STILL the fastest way to compute GCD.

O(log(min(a, b))) time
#09

Euclidean Algorithm

algorithm.js
function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}
// gcd(48, 18) → gcd(18, 12)
//             → gcd(12, 6)
//             → gcd(6, 0) → 6
Fun Fact

This algorithm is over 2,300 years old — older than the concept of zero in Western mathematics. Euclid described it with line segments, not numbers.

#10

KMP String Matching

Never Look Back

Searching for a pattern in a string? Naive approach backtracks on every mismatch. KMP builds a 'failure function' — a table of how far back you ACTUALLY need to go. The result? You never re-examine a character you've already seen. The text pointer only moves forward.

O(n + m) time, O(m) space
#10

KMP String Matching

algorithm.js
function kmpSearch(text, pattern) {
  const lps = buildLPS(pattern);
  let i = 0, j = 0;
  while (i < text.length) {
    if (text[i] === pattern[j]) {
      i++; j++;
      if (j === pattern.length) return i - j;
    } else if (j > 0) {
      j = lps[j - 1]; // don't reset i!
    } else {
      i++;
    }
  }
  return -1;
}
Fun Fact

Three people (Knuth, Morris, Pratt) independently discovered this in 1970. Knuth's version came from automata theory, Morris's from a text editor bug, and Pratt's from his PhD research.

Try It Yourself

Enter any positive integer and watch the Collatz Conjecture in action

Steps: — Peak: —