Permuted-Block Randomization for a Two-Arm Experiment
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: easy
Interview Round: Other
Implement `block_randomize(n, seed, block_size)` to assign `n` units to two arms via permuted-block randomization over `n // block_size` consecutive blocks. Return a `(n,)` array of dtype `int64` (1 = treatment, 0 = control).
The function must follow these rules:
- Raise `ValueError` if `block_size` is odd or `n % block_size != 0`.
- Create the generator once: `rng = np.random.default_rng(seed)`.
- Build the base array `np.array([0] * (block_size // 2) + [1] * (block_size // 2))`.
- For each block in order, call `rng.permutation(base)` exactly once (no reseeding per block).
- Concatenate the blocks in order, so each block has exactly `block_size // 2` treated units and the whole array has `n // 2`.
Example:
```python
block_randomize(n=6, seed=0, block_size=2)
# -> an int64 array of shape (6,) with exactly one 1 in each consecutive
# pair (positions 0-1, 2-3 and 4-5), so three 1s in total.
# Calling it again with seed=0 returns the identical array.
block_randomize(n=6, seed=0, block_size=4) # raises ValueError: 6 % 4 != 0
block_randomize(n=6, seed=0, block_size=3) # raises ValueError: block_size is odd
```
```hint Reproducibility
The same seed must always give the same array. Count how many generators you create and how many draws each block consumes.
```
```hint Output type
NumPy's default integer type has not been int64 on every platform. Check what dtype the base array and the final result end up with.
```
### Constraints & Assumptions
- Two arms with 1:1 allocation.
- Units are assigned in position order, so block `k` covers positions `k * block_size` through `(k + 1) * block_size - 1`.
- The result must be reproducible: the same `seed`, `n` and `block_size` give the same array.
- `numpy` is available.
### What a Strong Answer Covers
- Validation of both failure conditions before any random draw.
- One generator and one permutation per block, in order, so the output depends only on the seed.
- Why every block, and so the whole array, is exactly balanced, and how far the arms can drift inside a block.
- The `(n,)` shape and `int64` dtype, plus time and space complexity.
- Edge cases such as `n = 0` or a block size that is zero or negative.
### Follow-up Questions
- How does block size trade off balance against predictability?
- How would you extend this to stratified randomization across sites?
- Online A/B platforms usually assign users by hashing their IDs. Why would they avoid a precomputed block sequence?
Overview: Implement permuted-block randomization in NumPy, assigning n units to treatment and control in shuffled blocks that are each exactly balanced and reproducible from a seed. It tests input validation, careful use of a random generator, and the trade-off between balance and predictability in experiment design.