KatInterview

Proportional Stratified Sampling with Largest Remainder Allocation

Arrays & HashingModel answer
MediumModel answerArrays & Hashingsamplinggroupinghash-table

Last updated

Sample records from grouped data while preserving stratum proportions, using the largest remainder method to allocate exact counts and seeded random selection.

Problem

You have an in-memory dataset represented as a list of dictionaries. Each dictionary represents one record and contains at least one categorical field. Your task is to draw a fixed-size sample that preserves the relative proportions of each category as closely as possible.

Write a function that takes:

  • data: a list of dictionaries
  • stratify_col: the name of the categorical field to use for grouping
  • k: the desired sample size
  • seed: an optional integer for reproducible random selection

The function should return exactly k records, drawn without replacement, such that each category's representation in the sample mirrors its share of the full dataset.

Allocation Rule

Because exact proportions rarely yield integers, use the largest remainder method to distribute sample slots:

  1. Calculate the exact floating-point quota for each category: quota = k × (category_size / total_size)
  2. Assign each category the integer floor of its quota
  3. Compute the remainder for each category: remainder = quota - floor(quota)
  4. If the sum of floors is less than k, distribute the remaining slots one at a time to categories in descending order of their remainders
  5. Tie-break identical remainders by sorting category keys in ascending order

Function Signature

def stratified_sample(
    data: list[dict],
    stratify_col: str,
    k: int,
    seed: int | None = None
) -> list[dict]:
    pass

Constraints

  • 0 ≤ k ≤ len(data) ≤ 100,000
  • Every record contains the key specified by stratify_col with a hashable value
  • Category keys are comparable for tie-breaking

Example 1

data = [
    {"id": 1, "region": "North"},
    {"id": 2, "region": "North"},
    {"id": 3, "region": "North"},
    {"id": 4, "region": "North"},
    {"id": 5, "region": "South"},
    {"id": 6, "region": "South"},
    {"id": 7, "region": "East"},
    {"id": 8, "region": "East"},
    {"id": 9, "region": "West"},
    {"id": 10, "region": "West"}
]
k = 5

Total: 10 records. Each region has 2 or 4 records.

  • North: 5 × (4/10) = 2.0 → floor 2, remainder 0.0
  • South: 5 × (2/10) = 1.0 → floor 1, remainder 0.0
  • East: 5 × (2/10) = 1.0 → floor 1, remainder 0.0
  • West: 5 × (2/10) = 1.0 → floor 1, remainder 0.0

Sum of floors = 5, which matches k. Allocation: North gets 2, others get 1 each.

Example 2

data = [
    {"id": 1, "region": "North"},
    {"id": 2, "region": "North"},
    {"id": 3, "region": "South"}
]
k = 2

Total: 3 records.

  • North: 2 × (2/3) ≈ 1.333 → floor 1, remainder ≈ 0.333
  • South: 2 × (1/3) ≈ 0.667 → floor 0, remainder ≈ 0.667

Sum of floors = 1. Need to allocate 1 more slot. South has the larger remainder, so South receives the extra slot. Final allocation: North 1, South 1.

Hints

Hint 1

Group records by the stratify column in a single pass using a hash table, then work with category counts rather than iterating repeatedly over the data.

Hint 2

Avoid floating-point comparison issues when tie-breaking remainders by using exact integer arithmetic: compute remainder numerators with modulo and compare those directly.

Hint 3

Use a private random number generator seeded with the given seed, and process categories in sorted order so the RNG sequence is deterministic across runs.