Expected Count of Strict Running Maxima
Medium · Statistics & Math · Data Scientist · Technical Screen
Problem Statement
You are given an integer list values, which may be empty or contain duplicate numbers. Suppose its n = len(values) entries are written on n individually labeled cards, shuffled uniformly at random across all n! card orderings, and turned face up one by one from left to right.
Track the running high-water mark as cards appear:
- If
valuesis empty (n == 0),0records are set. - The very first card turned face up always sets the initial high-water mark (
1record). - Each subsequent card sets a new record if and only if its value is strictly greater (
>) than every previously turned card. A card whose value equals (==) the current high-water mark does not count as a new record.
Implement expected_record_maxima(values: List[int]) -> float to return the exact expected number of records set across a uniformly random shuffle. Answers within 10^-6 relative or absolute tolerance are accepted.
Examples
Example 1
Input: values = [10, 20, 30, 40]
Output: 2.0833333333333335
All four entries are distinct: 40 always sets a record (1), 30 sets a record whenever it appears ahead of 40 (1/2), 20 sets a record whenever it appears ahead of both 30 and 40 (1/3), and 10 sets a record only when drawn first (1/4). Summing gives 1 + 1/2 + 1/3 + 1/4 = 25/12 ≈ 2.083333.
Example 2
Input: values = [10, 20, 40, 40]
Output: 1.5833333333333335
Value 40 appears twice: whichever 40 is drawn first sets a record (2 / 2 = 1), whereas the second 40 ties the high-water mark and adds nothing. Meanwhile, 20 must precede both 40s (1 / 3) and 10 must precede 20 and both 40s (1 / 4), giving 1 + 1/3 + 1/4 = 19/12 ≈ 1.583333.
Constraints
0 <= len(values) <= 10^5-10^9 <= values[i] <= 10^9- Every permutation of the
nindex positions is equally probable.
Step-by-step walkthrough
Understand what counts as a strict running maximum
We are given a list of integers
values, shuffled into a uniformly random order (treating duplicate copies as individually labeled cards when shuffling) and turned face up one by one:- The first turned card always establishes the initial high-water mark (
1record). - Each later card sets a new record only if it is strictly greater (
>) than every card turned before it. A tie (==) with the current high-water mark does not count.
We want to return the expected value (exact average across all
n!equally likely card orderings) of the number of records set, handling both distinct inputs like[10, 20, 30, 40]and inputs with duplicates like[10, 20, 40, 40].Turn order: [ 20, 10, 40, 40 ] High-water mark: 20 20 40 40 New record? YES no YES no -> 2 records ^ second 40 ties max (not > 40)Notice that the starting order of
valuespassed into our function never matters — a uniform random shuffle erases the initial ordering, leaving only how many copies each distinct number has.- The first turned card always establishes the initial high-water mark (
Why enumerating permutations does not scale
By definition,
nlabeled cards haven!equally likely permutations. On a 4-card input (4! = 24) we could loop over all24orderings, count strict records in each, and divide by24.For
n = 100, however,100!exceeds9.3 × 10^157orderings — astronomically beyond brute force — whilencan reach10^5and Monte Carlo sampling would only give a noisy estimate. We need an exact closed-form summation.Break the count into one 0/1 indicator per distinct value
Instead of asking "How many total records were set across the whole sequence?", flip the question to each distinct number
vusing an indicator random variableI_v:I_v = 1if valuevever sets a new record during the sequence,I_v = 0if valuevnever sets a record.
Why one indicator per distinct value rather than per card? Suppose
v = 40appears twice. The first40to appear might set a new record, whereas the second40can never set a strict record because the running maximum is already at least40! Thus any distinct valuevcontributes either1or0records — never2or more.Therefore, the total record count equals the sum of
I_vover all distinct valuesv. By linearity of expectation — the rule that the average of a sum always equals the sum of the individual averages, even when the events depend on one another — we simply addP(I_v = 1)across every distinct valuev:Expected records = sum over each distinct value v of P(I_v = 1)Find the exact probability for one distinct value
Fix a distinct value
v. Supposevaluescontains:copiescards equal tov,strictly_larger_countcards strictly greater thanv, and- any number of cards strictly smaller than
v.
When does
vset a record (I_v = 1)?- Smaller cards (
< v) have zero effect: Whether they appear before or afterv, they can never lift the high-water mark tovor higher, so we can ignore them completely. - Only the
copies + strictly_larger_countcards with value>= vcompete: Look at the very first card from this>= vgroup to appear in the shuffled sequence:- If that first card is one of the
strictly_larger_countbigger numbers, the high-water mark jumps abovevbeforevever shows up, blockingv(I_v = 0). - If that first card is one of the
copiesofv, every earlier card was< v, so it sets a strict new record (I_v = 1)!
- If that first card is one of the
Full random shuffle (v = 20, copies = 2, strictly_larger_count = 3): [ 5, 10, 20a, 15, 50, 20b, 70, 5, 60 ] ^^^ ^^ ^^^ ^^ ^^ Filter to only cards >= 20: [ 20a, 50, 20b, 70, 60 ] (2 + 3 = 5 equally likely leaders) ^^^ First card >= 20 is a 20 -> v = 20 sets a record!Because the shuffle is uniformly random, each of the
copies + strictly_larger_countcards in that filtered group is equally likely to appear first among them:P(I_v = 1) = copies / (copies + strictly_larger_count)Trace Example 1 and Example 2
Applying
copies / (copies + strictly_larger_count)from largest value down to smallest:- Example 1 (
[10, 20, 30, 40]): Every value hascopies = 1, facing0, 1, 2, 3strictly larger cards in turn:
v = 40: 1 / (1 + 0) = 1 v = 30: 1 / (1 + 1) = 1/2 v = 20: 1 / (1 + 2) = 1/3 v = 10: 1 / (1 + 3) = 1/4 Total = 1 + 1/2 + 1/3 + 1/4 = 25/12 ≈ 2.0833333333333335- Example 2 (
[10, 20, 40, 40]): Replacing30with a second40:v = 40:copies = 2,strictly_larger_count = 0->2 / (2 + 0) = 1(the first40sets a record; the second40ties and adds0).v = 20:copies = 1,strictly_larger_count = 2(both40s block20!) ->1 / (1 + 2) = 1/3.v = 10:copies = 1,strictly_larger_count = 3(20plus both40s) ->1 / (1 + 3) = 1/4.
Total = 1 + 1/3 + 1/4 = 19/12 ≈ 1.5833333333333335 (drops by 1/2 because 30 is gone!)- Example 1 (
Cross-check on a 3-card multiset across all 6 permutations
Let's verify the formula by hand on
[2, 2, 1](labeled2a,2b,1):- Formula:
v = 2(copies = 2, larger = 0) ->2 / 2 = 1;v = 1(copies = 1, larger = 2) ->1 / 3. Sum =4/3. - Exhaustive check across all
3! = 6equally likely card orderings:
Ordering Records triggered Count ------------ ------------------------ ----- [2a, 2b, 1] 2a 1 [2b, 2a, 1] 2b 1 [2a, 1, 2b] 2a 1 [2b, 1, 2a] 2b 1 [1, 2a, 2b] 1, then 2a 2 [1, 2b, 2a] 1, then 2b 2 Average = 8 / 6 = 4/3 (exact match!)- Formula:
Complete solution
In Python, we count copies of each distinct integer in
copy_counts, then sweep distinct keys in descending order (reverse=True) while accumulatingstrictly_larger_count:from typing import Any, Dict, List, Optional, Set, Tuple def expected_record_maxima(values: List[int]) -> float: # Phase 1: Count how many copies of each distinct number appear in `values`. # copy_counts: {distinct_value: count_of_copies}, e.g. {40: 2, 20: 1, 10: 1} copy_counts: Dict[int, int] = {} for val in values: copy_counts[val] = copy_counts.get(val, 0) + 1 # Phase 2: Sweep distinct values from largest down to smallest so we always # know how many elements in `values` are strictly larger than `val`. expected_replacements = 0.0 strictly_larger_count = 0 for val in sorted(copy_counts.keys(), reverse=True): copies = copy_counts[val] # Distinct value `val` triggers a record replacement (at most once!) if and # only if one of its `copies` appears before all `strictly_larger_count` # bigger elements. Smaller elements never block `val`, and later copies of # `val` tie the running maximum and do not count as strict replacements. candidates = copies + strictly_larger_count prob_val_sets_record = copies / candidates expected_replacements += prob_val_sets_record # Include all copies of `val` as strictly larger blockers for smaller values. strictly_larger_count += copies return expected_replacements✅ Submit now — all tests should pass.
Intuition & how it works
Imagine athletes walking through a doorway one at a time in completely random order, while a scoreboard displays the tallest height seen so far and updates only when someone strictly taller than everyone already inside walks in. Instead of tracking the scoreboard step by step across every possible arrival sequence, focus on one specific height v and ask: "Does height v ever appear on the scoreboard?" Shorter athletes never affect whether v sets a record — height v claims the scoreboard (at most once!) if and only if someone of height v walks in before every athlete who is strictly taller than v.
A naive approach would iterate through every permutation (an ordering of all n items) and average the record counts, which explodes to n! orderings (100! ≈ 9.33 × 10^157). Instead, we define an indicator random variable I_v for each distinct value v (a random variable equal to 1 if v sets a record and 0 otherwise) and apply linearity of expectation — the rule that the expected value (probability-weighted average) of a sum of random variables always equals the sum of their individual expected values, even when those variables depend on one another.
Walk through Example 2, the multiset (a collection allowing duplicate values) [10, 20, 40, 40]:
- Count copies of each distinct value:
copy_counts = {40: 2, 20: 1, 10: 1}. - Process
val = 40(2copies,0strictly larger elements): among those2 + 0 = 2cards, one of the40s is guaranteed to arrive first (2 / 2 = 1.0), while the second40ties the high-water mark and adds0. Updatestrictly_larger_count = 2. - Process
val = 20(1copy,2larger elements): among{20, 40, 40},20arrives first with probability1 / (1 + 2) = 1/3; then processval = 10(1copy,3larger elements) to add1 / (1 + 3) = 1/4, giving1 + 1/3 + 1/4 = 19/12 ≈ 1.583333.
Complexity
- Time:
O(n + d log d)wherenislen(values)anddis the number of distinct values (d <= n). We scan allnnumbers once to populatecopy_countswithO(1)average-time dictionary updates, sort theddistinct keys inO(d log d)time, and do oneO(d)pass of constant-time arithmetic. - Space:
O(d). Bothcopy_countsand the sorted list of distinct keys store one entry per distinct value, using at mostO(d)memory (<= O(n)).
Edge cases
- Empty input (
[]): the loop overcopy_countsnever executes and cleanly returns0.0without dividing by zero. - Single element (
[42]) or all identical elements ([5, 5, 5]): returns1.0, since the first element sets the record (c / (c + 0) = 1.0) and any duplicate ties are ignored. - Multiple copies of the maximum (
[10, 20, 40, 40]): allccopies of the maximum together contributec / c = 1.0(neverc), while adding allccopies intostrictly_larger_countfor smaller values. - Multiple copies of a non-maximum (
[1, 1, 2]): having2copies of1boosts1's chance of beating2from1/2to2 / (2 + 1) = 2/3, giving1 + 2/3 = 5/3. - Labeled permutations vs distinct multiset arrangements: because every distinct multiset sequence corresponds to the exact same number of labeled card permutations (the product of
copies!across all distinct values), shuffling labeled cards and choosing uniformly among distinct multiset arrangements yield identical probabilities. - Unsorted inputs and negative numbers: only relative order (
>) and copy counts matter, so negative integers and arbitrary input order work identically.
Common mistakes
- Assuming duplicates of the maximum leave the expectation unchanged: replacing
30with a second40in[10, 20, 30, 40]removes30's1/2record probability without letting the second40score a strict record, dropping the expectation from25/12to19/12. - Creating one indicator
1 / (1 + strictly_larger_count)per card instead of per distinct value: that counts ties as new records (2for the two40s instead of1), solving the>=variant rather than strict>. - Adding an extra
+ 1for index0: the maximum value invaluesalready contributescopies / (copies + 0) = 1.0(equivalently, whichever value lands at index0is already counted by its ownI_v). - Worrying that
I_uandI_vare correlated: indicator events can depend on one another across subsets, yet linearity of expectation (E[X + Y] = E[X] + E[Y]) holds unconditionally without independence.
Alternative approaches
- Position-based indicators (for distinct values only): When all
nvalues are distinct, letJ_i = 1if thei-th revealed item (i = 1..n) is the largest among the firstiitems. By symmetry, the maximum of the firstiitems is equally likely to sit in any of thoseipositions, soP(J_i = 1) = 1 / iandE = sum_{i=1}^n 1 / i. Rényi's theorem further shows thatJ_1, ..., J_nare mutually independent for distinct values, giving variancesum_{i=1}^n (1/i - 1/i^2)immediately. Once duplicates exist, however,P(J_i = 1)depends on which values landed in the firstislots, making value-based indicators much cleaner.
Follow-up questions
- How fast does the expected count grow asymptotically as the number of distinct elements n approaches infinity? For
ndistinct elements, the exact expectation is then-th harmonic numberH_n = 1 + 1/2 + ... + 1/n(the sum of reciprocals of the firstnpositive integers), which grows logarithmically asln(n) + gamma + 1/(2n) - O(1/n^2), wheregamma ≈ 0.5772156649is the Euler-Mascheroni constant (the limiting offset betweenH_nandln(n)). Becauseln(n)grows slowly,n = 100distinct numbers average only≈ 5.19records and evenn = 1,000,000distinct numbers average onlyln(10^6) + 0.5772 ≈ 14.39records! - If ties also counted as new records (>= instead of strict >), how would the formula and answer change when duplicates are present? Under
>=, every individual copy of valuevsets a record whenever that specific card appears ahead of allstrictly_larger_countstrictly bigger cards, because earlier copies ofvonly lift the high-water mark tovandv >= vstill qualifies. Each copy wins among{itself} union {strictly_larger_count bigger cards}with probability1 / (1 + strictly_larger_count), so distinct valuevcontributescopies / (1 + strictly_larger_count); on[10, 20, 40, 40], both40s now count (2 / 1 = 2), raising the expectation from19/12to2 + 1/3 + 1/4 = 31/12. - When all n numbers are distinct, what is the exact probability that only a single record is set across the entire sequence? Since the very first revealed card always sets record
#1, avoiding any second record requires every later card to be smaller than the first — which happens if and only if the unique global maximum lands at index0. In a uniformly random permutation ofndistinct numbers, the global maximum occupies the first slot with probability1 / n(orc_max / nin the general multiset case when the maximum value hasc_maxcopies).
Follow-up questions
- How fast does the expected count grow asymptotically as the number of distinct elements n approaches infinity?
- If ties also counted as new records (>= instead of strict >), how would the formula and answer change when duplicates are present?
- When all n numbers are distinct, what is the exact probability that only a single record is set across the entire sequence?
Similar questions
- Break-Even Fee for Four-Chest Prize Search
- OOP vs. Functional Python Enrichment Pipelines
- Distinct Coin Combinations for a Target Sum
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips