Randomized algorithms
Advanced · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A randomized algorithm uses chance (a random pick) at key moments so that no particular input can reliably make it slow. It is worth knowing because it often gives simple, fast and safe solutions.
Practical use cases
- Web app: Sorting that cannot be attacked. An API sorts user-submitted lists. If it always picks the first item as the pivot, a malicious user can send a pre-sorted list that makes the server crawl. Picking the pivot at random makes such an attack impossible to plan, and response times stay steady.
- Web app: Random load balancing across servers. A site with 10 app servers sends each request to a randomly chosen server. No one server gets overwhelmed in the long run, and no complex tracking of who is busy is needed.
- Web app: Fast prime checks for generating keys. When a login system creates encryption keys, it needs big prime numbers. Random tests can say "very likely prime" in milliseconds, whereas exact checks take far too long on huge numbers. This lets key generation finish in a fraction of a second, with a chance of error so small that it can be ignored.
- System: Hash tables and game AI. Hash tables use random hash seeds so attackers cannot make all keys collide, and game AIs use randomness to play unpredictably and explore many options cheaply. The same trick keeps lookups quick in practice even when someone tries to deliberately break them.
The story: The Coach and the Lucky Die
Coach Bhatt had a funny rule for picking Kabir's cricket team: "Take the first player on my list as the benchmark and split everyone into weaker and stronger." It worked great. Until the list happened to be written in order of strength. Then the first player was always the weakest, the split was useless, and the coach spent all evening.
A clever boy named Aarav stuck his hand up. "Coach, don't always take the first name. Roll a die and take whoever it points to." Now no one could build a list that always ruins the plan, because even the coach did not know who would be picked.
Most of the time the random benchmark landed somewhere in the middle and the split was balanced. Sometimes it was unlucky, but unlucky evenings were rare and short. On average the work was small, and the final answer was always correct.
Using random choices to dodge bad inputs is the heart of randomized algorithms.
How to spot this problem, and where you need it
A fixed rule works well on normal data but can be made very slow by unlucky or deliberately crafted input, or the exact answer is too expensive when a very likely answer would do.
Signs you need it
- Your algorithm is fast on random data but has a nasty worst case on sorted or repeated data.
- Users can submit the data, so someone could craft input to slow you down.
- An exact answer takes too long, but being right with very high probability is acceptable.
Where to use it in a project
- Choosing pivots in sorting, or choosing a random item to sample, test or try next.
- Spreading requests across servers or queue workers without tracking who is busy.
- Security-related number checks, token generation and hash seeds that must not be predictable.
The solution
Add a random choice at the point where a fixed choice could be exploited: pick a random pivot, a random server, a random hash seed, or random test numbers. On average the work stays small whatever the input is, and for yes-or-no tests you repeat a few times so the chance of error falls below one in a billion.
Payoff: Before: a crafted input could make sorting 10,000 times slower. After: no input can reliably do that, and typical time stays low.
Explain it like I am 8
Imagine guessing someone's birthday month. If you always ask about January first, a tricky friend will pick December every time. If you pick months by spinning a spinner, nobody can beat you on purpose.
How it works, step by step
- Spot where a bad input hurts (for example, always picking the first item as the pivot).
- Replace that choice with a random one: random pivot, random order, random sample.
- Two flavours: Las Vegas algorithms are always right but their time varies (random quicksort/quickselect). Monte Carlo algorithms are fast but have a tiny chance of a wrong answer.
- In quickselect, pick a random pivot, split into smaller / same / bigger, and keep only the side that holds the answer.
- Expect good speed on average: bad luck is possible but very unlikely for big inputs.
The code in four languages
PHP
<?php
// Randomized quickselect: the k-th smallest (k = 1 means smallest).
function quickselect(array $a, int $k): int {
$pivot = $a[array_rand($a)]; // random pivot
$less = array_values(array_filter($a, fn($x) => $x < $pivot));
$same = array_values(array_filter($a, fn($x) => $x === $pivot));
$more = array_values(array_filter($a, fn($x) => $x > $pivot));
if ($k <= count($less)) return quickselect($less, $k); // answer is among the smaller
if ($k <= count($less) + count($same)) return $pivot; // the pivot itself
return quickselect($more, $k - count($less) - count($same)); // among the bigger
}
$scores = [7, 2, 9, 4, 1, 8, 3];
echo quickselect($scores, 3), "\n"; // always 3, however the dice fallJavaScript
// Randomized quickselect: the k-th smallest (k = 1 means smallest).
function quickselect(a, k) {
const pivot = a[Math.floor(Math.random() * a.length)]; // random pivot
const less = a.filter(x => x < pivot);
const same = a.filter(x => x === pivot);
const more = a.filter(x => x > pivot);
if (k <= less.length) return quickselect(less, k); // answer is among the smaller
if (k <= less.length + same.length) return pivot; // the pivot itself
return quickselect(more, k - less.length - same.length); // among the bigger
}
const scores = [7, 2, 9, 4, 1, 8, 3];
console.log(quickselect(scores, 3)); // always 3, however the dice fallJava
import java.util.*;
public class Main {
static final Random dice = new Random(42); // fixed seed so every run prints the same
// Randomized quickselect: the k-th smallest (k = 1 means smallest).
static int quickselect(List<Integer> a, int k) {
int pivot = a.get(dice.nextInt(a.size())); // random pivot
List<Integer> less = new ArrayList<>(), same = new ArrayList<>(), more = new ArrayList<>();
for (int x : a) {
if (x < pivot) less.add(x);
else if (x == pivot) same.add(x);
else more.add(x);
}
if (k <= less.size()) return quickselect(less, k); // answer is among the smaller
if (k <= less.size() + same.size()) return pivot; // the pivot itself
return quickselect(more, k - less.size() - same.size()); // among the bigger
}
public static void main(String[] args) {
List<Integer> scores = List.of(7, 2, 9, 4, 1, 8, 3);
System.out.println(quickselect(scores, 3)); // always 3, however the dice fall
}
}Go
package main
import (
"fmt"
"math/rand"
)
var dice = rand.New(rand.NewSource(42)) // fixed seed so every run prints the same
// quickselect returns the k-th smallest (k = 1 means smallest), using a random pivot.
func quickselect(a []int, k int) int {
pivot := a[dice.Intn(len(a))] // random pivot
var less, same, more []int
for _, x := range a {
switch {
case x < pivot:
less = append(less, x)
case x == pivot:
same = append(same, x)
default:
more = append(more, x)
}
}
if k <= len(less) { // answer is among the smaller
return quickselect(less, k)
}
if k <= len(less)+len(same) { // the pivot itself
return pivot
}
return quickselect(more, k-len(less)-len(same)) // among the bigger
}
func main() {
scores := []int{7, 2, 9, 4, 1, 8, 3}
fmt.Println(quickselect(scores, 3)) // always 3, however the dice fall
}Time: O(n) expected, O(n²) worst case (very unlikely) · Extra space: O(n). On average each pivot discards a chunk of the group, so total work is about two passes over the data.
Watch out for
- Seeding the random generator the same way every run and then being surprised that results repeat. (Fine for tests, not for fairness.)
- Assuming randomized means "wrong sometimes". Las Vegas algorithms are always correct, only their speed varies.
- Forgetting the "same as pivot" group, which loops forever when many values are equal.
Quick check
- Why choose the pivot at random?
- So no fixed input can reliably make it slow
- Because it is always faster
- Random numbers are free
- A Las Vegas algorithm is...
- Sometimes wrong, always fast
- Always correct, time varies
- Always slow
- We want the 5th smallest. The pivot has 2 smaller and 1 equal element. Where do we look next?
- Among the smaller, #5
- The pivot is the answer
- Among the bigger, #2