KatInterview

Feed Ad Load: Random Slots vs. Fixed Block Quota

Math & Bit ManipulationAuto-graded · 17 test cases
EasyAuto-gradedMath & Bit Manipulationprobabilityexpectationmath

Last updated

Compute expected ad counts for two feed ad policies and the chance of seeing at least one ad in a window, using linearity of expectation and the complement rule.

A feed team is comparing two ways to place ads among organic posts.

  • Random policy: every post is independently an ad with the same fixed probability.
  • Quota policy: the feed is split into consecutive blocks of equal length, and each block gets exactly one ad at a uniformly random position inside it.

Write a function that takes the number of posts, the per-post ad probability, the block length, and a window length, and returns three numbers:

  1. The expected number of ads among total_posts posts under the random policy.
  2. The expected number of ads among total_posts posts under the quota policy, which is the number of blocks, total_posts / block_size, computed as a real-number division with no rounding.
  3. Under the random policy, the probability that a window of window_size consecutive posts contains at least one ad.

Return a dictionary with exactly these keys:

  • "expected_ads_strategy_a": the random-policy expectation.
  • "expected_ads_strategy_b": the quota-policy expectation.
  • "probability_at_least_one_strategy_a": the at-least-one probability for the random policy.

Values are plain floats. Do not round them. The probability must be computed as 1 - (1 - ad_prob) ** window_size.

Constraints

  • total_posts is a positive integer.
  • block_size is a positive integer.
  • 0 <= ad_prob <= 1.
  • window_size is a non-negative integer. An empty window (0) contains no ads, so its probability is 0.
  • Inputs are small enough that ordinary floating-point arithmetic is fine.

Examples

Example 1

Input: ad_feed_stats(100, 0.04, 25, 25)

Output: {'expected_ads_strategy_a': 4, 'expected_ads_strategy_b': 4, 'probability_at_least_one_strategy_a': 0.639603283141982}

Hints

Hint 1

Let each post be a 0/1 indicator of being an ad. Linearity of expectation says the expected total is the sum of the individual expectations, so it is posts times probability.

Hint 2

Under the quota policy the ad count is not random at all: there is one ad per block, so count the blocks.

Hint 3

For 'at least one', compute the probability of the opposite event (no ads in the window). Posts are independent, so that is (1 - p) raised to the window length.