Proportional Stratified Sampling with Largest Remainder Allocation
Arrays & HashingModel answerLast 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 dictionariesstratify_col: the name of the categorical field to use for groupingk: the desired sample sizeseed: 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:
- Calculate the exact floating-point quota for each category:
quota = k × (category_size / total_size) - Assign each category the integer floor of its quota
- Compute the remainder for each category:
remainder = quota - floor(quota) - 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 - 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_colwith 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem breaks into two independent phases: allocation and selection.
Phase 1: Allocation (Deterministic)
Decide how many records each category contributes to the final sample. The largest remainder method ensures the total is exactly k while respecting proportions:
- Compute the ideal quota for each category:
k × (n_category / n_total) - Give each category the floor of its quota
- The sum of floors is typically less than
k; the deficit equals the sum of fractional remainders - Sort categories by descending remainder (tie-break by ascending key) and give the top
deficitcategories one extra slot each
Phase 2: Selection (Random)
Within each category, randomly select the allocated number of records without replacement using a seeded random generator.
Why Use Integer Arithmetic for Remainders
The quota k × n_g / N is a rational number. When computed as a float, two mathematically equal remainders can differ in the least significant bit, breaking tie detection. Instead:
base = (k × n_g) // Nremainder_numerator = (k × n_g) % N
All categories share denominator N, so comparing numerators is equivalent to comparing true remainders, and ties are detected exactly.
Correctness
Total is exactly k: The sum of all quotas equals k × (N / N) = k. The deficit d = k - Σ floors equals the sum of remainders. Since each remainder is in [0, 1), we have d < G (number of groups). Distributing d extra slots to the top d remainder holders sums precisely to k.
No over-allocation: For any category, quota_g ≤ n_g because k ≤ N. A category receives at most ⌈quota_g⌉ ≤ n_g, so sampling never exceeds available records.
Unbiased within strata: random.sample draws uniformly without replacement. Given the allocation, every subset of the required size is equally likely within each category.
Reproducibility: Using a private random.Random(seed) instance and processing categories in sorted order ensures the RNG is consumed identically on every run.
Complexity
- Time: O(N + G log G), where N is the number of records and G is the number of categories. Grouping takes O(N); sorting categories takes O(G log G); sampling is O(k) total.
- Space: O(N) for grouping, plus O(k) for the output.
Edge Cases
- k = 0 or empty data: return an empty list
- k = N: every quota is exactly the category size; all records are returned (shuffled within categories)
- Single category: reduces to simple random sampling
- All remainders equal: tie-breaking by sorted key becomes decisive (though if all remainders are zero and deficit is zero, no extra slots are distributed)
Implementation
import random
from collections import defaultdict
def stratified_sample(
data: list[dict],
stratify_col: str,
k: int,
seed: int | None = None
) -> list[dict]:
n = len(data)
# Handle edge cases
if k == 0 or n == 0:
return []
if k > n:
raise ValueError("Sample size cannot exceed data size")
# Phase 1: Group records by category
groups = defaultdict(list)
for record in data:
groups[record[stratify_col]].append(record)
# Sort category keys for deterministic processing
categories = sorted(groups.keys())
# Phase 2: Compute base allocations and remainders using integer arithmetic
allocations = {}
remainder_numerators = {}
for category in categories:
category_size = len(groups[category])
scaled = k * category_size
allocations[category] = scaled // n
remainder_numerators[category] = scaled % n
# Phase 3: Distribute deficit slots by largest remainder
deficit = k - sum(allocations.values())
if deficit > 0:
# Sort by descending remainder (numerator), then ascending category key for ties
sorted_categories = sorted(
categories,
key=lambda cat: (-remainder_numerators[cat], cat)
)
for category in sorted_categories[:deficit]:
allocations[category] += 1
# Phase 4: Sample from each category
rng = random.Random(seed)
result = []
for category in categories:
quota = allocations[category]
if quota > 0:
result.extend(rng.sample(groups[category], quota))
return result
Example Trace (Example 2)
Data has 3 records: 2 North, 1 South. Target k = 2.
- North:
scaled = 2 × 2 = 4,base = 4 // 3 = 1,remainder_num = 4 % 3 = 1 - South:
scaled = 2 × 1 = 2,base = 2 // 3 = 0,remainder_num = 2 % 3 = 2
Sum of bases = 1, deficit = 1. South has larger remainder numerator (2 > 1), so South receives the extra slot. Final: North 1, South 1.
Common Mistakes
- Using floating-point remainders and encountering tie-break failures
- Forgetting to seed the RNG or using global random state, breaking reproducibility
- Processing categories in arbitrary order, making results non-deterministic even with a seed
- Not validating that
k ≤ len(data)
Follow-Up: Streaming Data
If the dataset doesn't fit in memory:
Two-pass approach:
- First pass: count records per category (memory O(G))
- Compute allocations as above
- Second pass: use reservoir sampling per category with the computed quota (memory O(k))
Distributed systems (Spark/MapReduce):
- Aggregate counts with a group-by operation
- Broadcast allocations to workers
- Assign each record a random priority; keep the
q_gsmallest priorities per category using a min-heap - Priority-based selection merges correctly across partitions