AlgoVerse

The hiring problem

Candidates arrive one by one and anyone better than everyone before is hired; how many hires do we make?

We want to hire an assistant. Candidates arrive one at a time, and after each interview we must decide on the spot. Our policy: if the candidate is better than everyone before, hire them (and let the previous one go). Hiring is expensive; how many times do we hire?

Read the full explanation ↓
Input:
n=10PDF export

Ten candidates in a mixed order; only four are hired.

  1. def hire_assistant(ranks):
  2. best = -1
  3. hired = []
  4. for i in range(len(ranks)):
  5. if ranks[i] > best:
  6. best = ranks[i]
  7. hired.append(i)
  8. return hired

Invariant: best is the rank of the best candidate among ranks[0..i−1], and the last hire is that candidate.

Start

502182139435761074869

Local variables

Orange = changed in this step

ranks list

52819371046

Call stack

  1. hire_assistant()line 1
Step 1 of 33
Black = hire · Orange = key stepcompare: 0/10 · hire: 0/4

    How the work grows with input size

    Average of 12 random graphs per n (fixed seeds). Hollow marker = the input on screen.

    • hire
    • current input (n=10)
    0123446810121416n = number of itemshire
    Show as a table
    nhire
    41.7
    62.3
    83.1
    102.9
    123.5
    143.2
    163.4
    Explanation

    The problem

    We want to hire an assistant. Candidates arrive one at a time, and after each interview we must decide on the spot. Our policy: if the candidate is better than everyone before, hire them (and let the previous one go). Hiring is expensive; how many times do we hire?

    Analysis

    • Worst case: the candidates arrive in increasing order, and every one is hired: n hires.
    • If the order is random, candidate i beats all before with probability 1/i. So the expected number of hires is 1 + 1/2 + … + 1/n ≈ ln n: about 5 hires for 100 candidates.

    This is CLRS's classic example of probabilistic analysis, and it shows why we sometimes shuffle the input ourselves (a randomized algorithm).

    What to watch in the trace

    • The i arrow is the current candidate, and the hired list is in the memory panel.
    • Compare the number of hire steps on "increasing" and on the "textbook-style example".