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 values is empty (n == 0), 0 records are set.
  • The very first card turned face up always sets the initial high-water mark (1 record).
  • 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 n index positions is equally probable.

Step-by-step walkthrough

  1. 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 (1 record).
    • 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 values passed into our function never matters — a uniform random shuffle erases the initial ordering, leaving only how many copies each distinct number has.

  2. Why enumerating permutations does not scale

    By definition, n labeled cards have n! equally likely permutations. On a 4-card input (4! = 24) we could loop over all 24 orderings, count strict records in each, and divide by 24.

    For n = 100, however, 100! exceeds 9.3 × 10^157 orderings — astronomically beyond brute force — while n can reach 10^5 and Monte Carlo sampling would only give a noisy estimate. We need an exact closed-form summation.

  3. 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 v using an indicator random variable I_v:

    • I_v = 1 if value v ever sets a new record during the sequence,
    • I_v = 0 if value v never sets a record.

    Why one indicator per distinct value rather than per card? Suppose v = 40 appears twice. The first 40 to appear might set a new record, whereas the second 40 can never set a strict record because the running maximum is already at least 40! Thus any distinct value v contributes either 1 or 0 records — never 2 or more.

    Therefore, the total record count equals the sum of I_v over all distinct values v. 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 add P(I_v = 1) across every distinct value v:

    Expected records = sum over each distinct value v of P(I_v = 1)
    
  4. Find the exact probability for one distinct value

    Fix a distinct value v. Suppose values contains:

    • copies cards equal to v,
    • strictly_larger_count cards strictly greater than v, and
    • any number of cards strictly smaller than v.

    When does v set a record (I_v = 1)?

    1. Smaller cards (< v) have zero effect: Whether they appear before or after v, they can never lift the high-water mark to v or higher, so we can ignore them completely.
    2. Only the copies + strictly_larger_count cards with value >= v compete: Look at the very first card from this >= v group to appear in the shuffled sequence:
      • If that first card is one of the strictly_larger_count bigger numbers, the high-water mark jumps above v before v ever shows up, blocking v (I_v = 0).
      • If that first card is one of the copies of v, every earlier card was < v, so it sets a strict new record (I_v = 1)!
    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_count cards in that filtered group is equally likely to appear first among them:

    P(I_v = 1) = copies / (copies + strictly_larger_count)
    
  5. 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 has copies = 1, facing 0, 1, 2, 3 strictly 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]): Replacing 30 with a second 40:
      • v = 40: copies = 2, strictly_larger_count = 0 -> 2 / (2 + 0) = 1 (the first 40 sets a record; the second 40 ties and adds 0).
      • v = 20: copies = 1, strictly_larger_count = 2 (both 40s block 20!) -> 1 / (1 + 2) = 1/3.
      • v = 10: copies = 1, strictly_larger_count = 3 (20 plus both 40s) -> 1 / (1 + 3) = 1/4.
    Total = 1 + 1/3 + 1/4 = 19/12 ≈ 1.5833333333333335  (drops by 1/2 because 30 is gone!)
    
  6. Cross-check on a 3-card multiset across all 6 permutations

    Let's verify the formula by hand on [2, 2, 1] (labeled 2a, 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! = 6 equally 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!)
    
  7. Complete solution

    In Python, we count copies of each distinct integer in copy_counts, then sweep distinct keys in descending order (reverse=True) while accumulating strictly_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]:

  1. Count copies of each distinct value: copy_counts = {40: 2, 20: 1, 10: 1}.
  2. Process val = 40 (2 copies, 0 strictly larger elements): among those 2 + 0 = 2 cards, one of the 40s is guaranteed to arrive first (2 / 2 = 1.0), while the second 40 ties the high-water mark and adds 0. Update strictly_larger_count = 2.
  3. Process val = 20 (1 copy, 2 larger elements): among {20, 40, 40}, 20 arrives first with probability 1 / (1 + 2) = 1/3; then process val = 10 (1 copy, 3 larger elements) to add 1 / (1 + 3) = 1/4, giving 1 + 1/3 + 1/4 = 19/12 ≈ 1.583333.

Complexity

  • Time: O(n + d log d) where n is len(values) and d is the number of distinct values (d <= n). We scan all n numbers once to populate copy_counts with O(1) average-time dictionary updates, sort the d distinct keys in O(d log d) time, and do one O(d) pass of constant-time arithmetic.
  • Space: O(d). Both copy_counts and the sorted list of distinct keys store one entry per distinct value, using at most O(d) memory (<= O(n)).

Edge cases

  • Empty input ([]): the loop over copy_counts never executes and cleanly returns 0.0 without dividing by zero.
  • Single element ([42]) or all identical elements ([5, 5, 5]): returns 1.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]): all c copies of the maximum together contribute c / c = 1.0 (never c), while adding all c copies into strictly_larger_count for smaller values.
  • Multiple copies of a non-maximum ([1, 1, 2]): having 2 copies of 1 boosts 1's chance of beating 2 from 1/2 to 2 / (2 + 1) = 2/3, giving 1 + 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 30 with a second 40 in [10, 20, 30, 40] removes 30's 1/2 record probability without letting the second 40 score a strict record, dropping the expectation from 25/12 to 19/12.
  • Creating one indicator 1 / (1 + strictly_larger_count) per card instead of per distinct value: that counts ties as new records (2 for the two 40s instead of 1), solving the >= variant rather than strict >.
  • Adding an extra + 1 for index 0: the maximum value in values already contributes copies / (copies + 0) = 1.0 (equivalently, whichever value lands at index 0 is already counted by its own I_v).
  • Worrying that I_u and I_v are 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 n values are distinct, let J_i = 1 if the i-th revealed item (i = 1..n) is the largest among the first i items. By symmetry, the maximum of the first i items is equally likely to sit in any of those i positions, so P(J_i = 1) = 1 / i and E = sum_{i=1}^n 1 / i. Rényi's theorem further shows that J_1, ..., J_n are mutually independent for distinct values, giving variance sum_{i=1}^n (1/i - 1/i^2) immediately. Once duplicates exist, however, P(J_i = 1) depends on which values landed in the first i slots, 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 n distinct elements, the exact expectation is the n-th harmonic number H_n = 1 + 1/2 + ... + 1/n (the sum of reciprocals of the first n positive integers), which grows logarithmically as ln(n) + gamma + 1/(2n) - O(1/n^2), where gamma ≈ 0.5772156649 is the Euler-Mascheroni constant (the limiting offset between H_n and ln(n)). Because ln(n) grows slowly, n = 100 distinct numbers average only ≈ 5.19 records and even n = 1,000,000 distinct numbers average only ln(10^6) + 0.5772 ≈ 14.39 records!
  • 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 value v sets a record whenever that specific card appears ahead of all strictly_larger_count strictly bigger cards, because earlier copies of v only lift the high-water mark to v and v >= v still qualifies. Each copy wins among {itself} union {strictly_larger_count bigger cards} with probability 1 / (1 + strictly_larger_count), so distinct value v contributes copies / (1 + strictly_larger_count); on [10, 20, 40, 40], both 40s now count (2 / 1 = 2), raising the expectation from 19/12 to 2 + 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 index 0. In a uniformly random permutation of n distinct numbers, the global maximum occupies the first slot with probability 1 / n (or c_max / n in the general multiset case when the maximum value has c_max copies).

Follow-up questions

Similar questions

More Worldquant interview questions

All 4 Worldquant questions →