The Hiring Problem
Most of this course so far has asked "how bad can it get?" The worst case is a guarantee, but it can be pessimistic: an algorithm may be slow only on inputs that hardly ever occur. Probabilistic analysis asks a different question: if the input is random in some precise sense, what is the expected cost? This lesson introduces the idea with a small story, the hiring problem, and shows the difference between analysing a random input and making the algorithm itself random.
The probability you need is expectation and its linearity. If those feel rusty, Expectation and Linearity and Indicator Variables cover them.
The story
A start-up needs one office manager and has hired an agency that sends one candidate a day. The founders have a strict rule: after each interview, if the candidate is better than the person currently in the job, they fire the current manager and hire the new one on the spot. They always want the best person seen so far in the job.
Two costs matter:
- every interview costs (the agency's fee, small),
- every hire costs (paperwork, severance for the previous manager, training, large).
If candidates arrive and of them get hired, the total cost is . The interview part is the same for every order of arrival, so the interesting quantity is , the number of hires.
HIRE-BEST-SO-FAR(c) // c[0..n-1]: candidate scores, all distinct
1 best = -infinity
2 hires = 0
3 for i = 0 to n - 1
4 interview candidate i // cost c_i
5 if c[i] > best
6 best = c[i]
7 hires = hires + 1 // cost c_h
8 return hiresStructurally this is the loop that finds the maximum of an array, where "hire" is the update of the running maximum. So the question "how many hires?" is the same as "how often does the running maximum change?", which matters for real code too (every update of a maximum might be a write to disk or a message on a network).
Here is the procedure with and on three arrival orders of the same eight candidates.
def hire_all(scores, interview_cost=1, hire_cost=20):
best = None
hires = 0
for s in scores:
if best is None or s > best:
best = s
hires += 1
cost = interview_cost * len(scores) + hire_cost * hires
return hires, cost
for name, scores in [("rising", [1, 2, 3, 4, 5, 6, 7, 8]),
("falling", [8, 7, 6, 5, 4, 3, 2, 1]),
("mixed", [3, 1, 6, 2, 8, 5, 7, 4])]:
hires, cost = hire_all(scores)
print(f"{name:8} {scores} hires = {hires}, cost = {cost}")rising [1, 2, 3, 4, 5, 6, 7, 8] hires = 8, cost = 168
falling [8, 7, 6, 5, 4, 3, 2, 1] hires = 1, cost = 28
mixed [3, 1, 6, 2, 8, 5, 7, 4] hires = 3, cost = 68
In C++
The same procedure in C++:
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
using namespace std;
// returns {hires, cost}
pair<int, int> hire_all(const vector<int>& scores, int interview_cost = 1, int hire_cost = 20) {
bool have_best = false;
int best = 0, hires = 0;
for (int s : scores) {
if (!have_best || s > best) {
best = s;
have_best = true;
hires++;
}
}
int cost = interview_cost * (int)scores.size() + hire_cost * hires;
return {hires, cost};
}
string show(const vector<int>& a) {
string s = "[";
for (size_t k = 0; k < a.size(); k++) s += (k ? ", " : "") + to_string(a[k]);
return s + "]";
}
int main() {
struct Order { const char* name; vector<int> scores; };
vector<Order> orders = {{"rising", {1, 2, 3, 4, 5, 6, 7, 8}},
{"falling", {8, 7, 6, 5, 4, 3, 2, 1}},
{"mixed", {3, 1, 6, 2, 8, 5, 7, 4}}};
for (const auto& [name, scores] : orders) {
auto [hires, cost] = hire_all(scores);
printf("%-8s %s hires = %d, cost = %d\n", name, show(scores).c_str(), hires, cost);
}
}rising [1, 2, 3, 4, 5, 6, 7, 8] hires = 8, cost = 168
falling [8, 7, 6, 5, 4, 3, 2, 1] hires = 1, cost = 28
mixed [3, 1, 6, 2, 8, 5, 7, 4] hires = 3, cost = 68
Worst case and best case
The worst case is candidates arriving in increasing order of quality: every one beats the previous, so all are hired and the cost is , which is . The best case is the best candidate arriving first: one hire, cost . Neither tells you what to expect from an agency that sends candidates in no particular order.
Probabilistic analysis: assume a random order
To say anything about the "typical" case you must state what typical means. The standard assumption here: the candidates arrive in a uniformly random order, meaning each of the orderings of their ranks is equally likely. (Only the relative ranks matter to the algorithm, not the actual scores.)
Under that assumption, candidate (0-based) is hired exactly when it is the best of the first candidates. In a random order every one of those candidates is equally likely to be the best of them, so this happens with probability . By linearity of expectation (the next lesson, Indicator Random Variables, does this step carefully):
is the -th harmonic number, and ; more precisely . So the expected hiring cost is , which is for the hiring part, exponentially better than the worst case .
Because the claim is about all orders, it can be checked exactly for small by trying every order and averaging with exact fractions.
from fractions import Fraction
from itertools import permutations
from math import factorial
def hires(order):
best, count = -1, 0
for s in order:
if s > best:
best, count = s, count + 1
return count
for n in range(1, 8):
total = sum(hires(p) for p in permutations(range(n)))
average = Fraction(total, factorial(n))
harmonic = sum(Fraction(1, k) for k in range(1, n + 1))
print(f"n = {n}: {factorial(n):4} orders, average hires {str(average):7} H_n = {str(harmonic):7} equal: {average == harmonic}")n = 1: 1 orders, average hires 1 H_n = 1 equal: True
n = 2: 2 orders, average hires 3/2 H_n = 3/2 equal: True
n = 3: 6 orders, average hires 11/6 H_n = 11/6 equal: True
n = 4: 24 orders, average hires 25/12 H_n = 25/12 equal: True
n = 5: 120 orders, average hires 137/60 H_n = 137/60 equal: True
n = 6: 720 orders, average hires 49/20 H_n = 49/20 equal: True
n = 7: 5040 orders, average hires 363/140 H_n = 363/140 equal: True
From an assumption to a guarantee: randomize first
The analysis above has a weak spot: it is only as good as the assumption. If the agency happens to send candidates from weakest to strongest (perhaps it sorts its list by "years of experience" and that correlates with quality), the expected-case analysis says nothing about the cost you will actually pay.
The fix is to stop assuming and start enforcing. Ask the agency for the whole list in advance, shuffle it uniformly at random yourself, and then interview in the shuffled order. This is a randomized algorithm: the randomness now lives inside the algorithm, not in a hypothesis about the world. For every input order, including the adversarial rising one, the expected number of hires is , where the expectation is over the algorithm's own coin flips.
The two statements sound similar, but they are different:
| Probabilistic analysis | Randomized algorithm | |
|---|---|---|
| Where the randomness is | in the input (an assumption) | in the algorithm (coin flips) |
| What "expected" averages over | all inputs, weighted by the assumed distribution | the algorithm's random choices, for one fixed input |
| Can an adversary make it slow? | yes, by choosing a bad input | no, no single input is bad; only bad luck is |
The quantity analysed is called the expected running time (or expected cost) of the randomized algorithm, and for the shuffled hiring procedure it is on every input. The shuffle must really be uniform; Random Permutations and Fisher-Yates shows how to produce one and why a popular shortcut does not.
import random
def hires(order):
best, count = -1, 0
for s in order:
if s > best:
best, count = s, count + 1
return count
rng = random.Random(7)
n = 1000
sorted_pool = list(range(n)) # the adversary: candidates arrive best-last
print("fixed rising order:", hires(sorted_pool), "hires")
trials = 2000
total = 0
for _ in range(trials):
order = sorted_pool[:]
rng.shuffle(order) # the randomized algorithm shuffles first
total += hires(order)
H = sum(1 / k for k in range(1, n + 1))
print(f"after shuffling: average {total / trials:.2f} hires over {trials} runs")
print(f"H_{n} = {H:.2f}")fixed rising order: 1000 hires
after shuffling: average 7.49 hires over 2000 runs
H_1000 = 7.49
In C++
In C++, std::shuffle with a seeded std::mt19937 does the shuffling. Its random stream is not Python's, so the simulated average comes out slightly different; both are close to :
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <random>
#include <vector>
using namespace std;
int hires(const vector<int>& order) {
int best = -1, count = 0;
for (int s : order) {
if (s > best) {
best = s;
count++;
}
}
return count;
}
int main() {
mt19937 rng(7);
const int n = 1000;
vector<int> sorted_pool(n);
iota(sorted_pool.begin(), sorted_pool.end(), 0); // the adversary: best-last
printf("fixed rising order: %d hires\n", hires(sorted_pool));
const int trials = 2000;
long total = 0;
for (int t = 0; t < trials; t++) {
vector<int> order = sorted_pool;
shuffle(order.begin(), order.end(), rng); // the randomized algorithm shuffles first
total += hires(order);
}
double H = 0;
for (int k = 1; k <= n; k++) H += 1.0 / k;
printf("after shuffling: average %.2f hires over %d runs\n", (double)total / trials, trials);
printf("H_%d = %.2f\n", n, H);
}fixed rising order: 1000 hires
after shuffling: average 7.56 hires over 2000 runs
H_1000 = 7.49
On the worst possible input the plain procedure hires all 1,000 candidates; the shuffled one hires about 7.5 on average. Randomized quicksort, in the next course, uses exactly this trick to turn a bad worst-case input into an unlucky event.
The online variant: hire only once
Change the rules. Now the start-up may hire exactly once, and must decide on each candidate right after the interview: a rejected candidate is gone for good. It wants to maximise the probability of hiring the very best of the candidates. Candidates still arrive in uniformly random order.
A natural strategy: interview the first candidates and reject them all, only to learn how good the field is. Then hire the first later candidate who beats every one of those . (If nobody does, you are stuck with the last candidate, which counts as a failure unless it is the best.)
When does this strategy hire the best candidate? Say the best is at position (0-based), which happens with probability for each . It is hired exactly when nobody between positions and beat the first , that is, when the best of the first candidates sits among the first . That has probability . Summing over , for :
The approximation is maximised at , where it equals . So rejecting about the first 37% of candidates finds the very best one with probability about 37%, however large is. Here is the exact formula checked against every order for small , then optimised for larger .
from fractions import Fraction
from itertools import permutations
from math import e, factorial
def success_formula(n, k):
# reject the first k, then take the first candidate better than all of them
if k == 0:
return Fraction(1, n)
return Fraction(k, n) * sum(Fraction(1, i) for i in range(k, n))
def success_brute(n, k):
wins = 0
for p in permutations(range(n)): # n - 1 is the best candidate
bar = max(p[:k], default=-1)
pick = next((x for x in p[k:] if x > bar), None)
wins += pick == n - 1
return Fraction(wins, factorial(n))
for n in [4, 5, 6]:
exact = [success_brute(n, k) for k in range(n)]
same = all(exact[k] == success_formula(n, k) for k in range(n))
print(f"n = {n}: " + ", ".join(f"k={k}: {p}" for k, p in enumerate(exact)) + f" formula agrees: {same}")
def success_float(n, k):
return 1 / n if k == 0 else k / n * sum(1 / i for i in range(k, n))
for n in [10, 100, 1000]:
best_k = max(range(n), key=lambda k: success_float(n, k))
print(f"n = {n:4}: best k = {best_k:3} (n/e = {n / e:5.1f}), success {success_float(n, best_k):.4f}")
print(f"1/e = {1 / e:.4f}")n = 4: k=0: 1/4, k=1: 11/24, k=2: 5/12, k=3: 1/4 formula agrees: True
n = 5: k=0: 1/5, k=1: 5/12, k=2: 13/30, k=3: 7/20, k=4: 1/5 formula agrees: True
n = 6: k=0: 1/6, k=1: 137/360, k=2: 77/180, k=3: 47/120, k=4: 3/10, k=5: 1/6 formula agrees: True
n = 10: best k = 3 (n/e = 3.7), success 0.3987
n = 100: best k = 37 (n/e = 36.8), success 0.3710
n = 1000: best k = 368 (n/e = 367.9), success 0.3682
1/e = 0.3679
With the strategy hires the first candidate and succeeds with probability ; learning from a sample first is worth a great deal. This "secretary problem" is the simplest example of an online algorithm, one that must decide before seeing the whole input; the Online Algorithms course later in the track is built around such problems.
Test yourself
In the hiring problem with candidates in a uniformly random order, what is the expected number of hires?
- , about
- exactly
- 1
What is the key difference between probabilistic analysis and a randomized algorithm?
- They are the same thing
- Probabilistic analysis assumes a distribution over inputs; a randomized algorithm makes its own random choices, so its expected cost holds for every input
- A randomized algorithm is always faster in the worst case
- Probabilistic analysis only applies to sorting
In the online version, you reject the first candidates and then hire the first one better than all of them. Which approximately maximises the chance of hiring the best?
- , giving success probability about
- , giving success probability
With interview cost and hiring cost , what is the worst-case total cost for candidates?