KatInterview

Expected Number of Running Record Highs

Math & Bit ManipulationAuto-graded · 22 test cases
MediumAuto-gradedMath & Bit Manipulationmathprobabilityarrays

Last updated

Compute the expected number of strict running maximum records for a uniformly random ordering of a collection of numbers.

Given a list of numbers values, consider generating a sequence by shuffling all elements of values into a uniformly random permutation.

We scan the shuffled sequence from left to right, maintaining a running maximum. A position in the permutation establishes a new record if its value is strictly greater than every value observed before it in the sequence. (Note that the very first element scanned always establishes a record).

Return the expected total number of records established in such a random permutation.

Constraints

  • $1 \le \text{len}(values) \le 10^5$
  • Every element in values is an integer between $-10^9$ and $10^9$.
  • Duplicate values are allowed in values.

Examples

Example 1

Input: expected_record_maxima([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100])

Output: 5.187377517639621

Example 2

Input: expected_record_maxima([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 100, 100])

Output: 4.687377517639622

Hints

Hint 1

By linearity of expectation, the expected number of records is the sum of the probabilities that each distinct value establishes a record.

Hint 2

For a particular value $v$, consider only the elements in the multiset that are greater than or equal to $v$.

Hint 3

If $v$ appears $c$ times and there are $h$ elements strictly greater than $v$, what is the probability that a copy of $v$ appears before all $h$ strictly larger elements?