Uniform Random Array Partitioning into K Segments
Arrays & HashingModel answerLast updated
Divide an array into K non-empty contiguous slices such that every valid partition is equally likely to be selected.
Given a list of integers nums of length $N$ and a positive integer k, write a function random_partition(nums, k) that breaks the list into k non-empty contiguous sublists.
Your implementation must satisfy the following constraints:
- Contiguous and Ordered: The sequence of sublists, when concatenated, must equal the original
numslist in its original order. - Non-Empty: Every sublist must contain at least one element.
- Uniform Randomness: The algorithm must sample uniformly at random from the set of all valid $k$-segment contiguous partitions. Every distinct valid partition must have an equal probability of being selected.
- Immutability: The input array
numsmust remain unmodified.
Return the result as a list of lists of integers. If it is impossible to form k non-empty segments from nums (e.g., if $k > N$ or $k \le 0$), your function should raise a ValueError.
Additionally, explain your approach, analyze its time and space complexities, and outline how you would statistically verify that your implementation produces a uniform distribution.
Hints
Hint 1
Think of splitting an array as placing barriers into the spaces between elements rather than choosing segment sizes sequentially.
Hint 2
How many total boundary positions exist between adjacent elements of an array of length N, and how many barriers do you need to place to form k parts?
Hint 3
Generating a uniform random sample of sizes step-by-step is often biased because early choices constrain later options. How does choosing cut locations directly avoid this bias?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying the Mechanics
- Contiguous Segments: Splitting an array of size $N$ into $k$ contiguous sublists means choosing split points along the sequence.
- Combinatorial Count: Between $N$ elements, there are exactly $N - 1$ interior positions (gaps) where a split can occur. Placing a split at a gap divides the elements on either side.
- Uniformity: To form $k$ segments, we must place exactly $k - 1$ distinct split points into these $N - 1$ available gaps. There are $\binom{N-1}{k-1}$ total ways to choose these split points. To achieve uniform distribution over all valid partitions, every combination of $k - 1$ gaps must be chosen with probability $\frac{1}{\binom{N-1}{k-1}}$.
Algorithm & Implementation
Cut-Point Sampling Approach
Instead of picking segment lengths one by one (which leads to sampling bias if not done with carefully adjusted weights), we directly select $k - 1$ distinct cut indices from ${1, 2, \dots, N - 1}$.
- Validate input constraints: require $1 \le k \le N$.
- Uniformly sample $k - 1$ unique values from the range $[1, N - 1]$.
- Sort the chosen cut indices to create ordered boundaries.
- Add $0$ as the start index and $N$ as the end index.
- Slice
numsbetween adjacent pairs in this index sequence.
import random
from typing import List, Optional
def random_partition(
nums: List[int],
k: int,
rng: Optional[random.Random] = None
) -> List[List[int]]:
"""
Splits `nums` into `k` non-empty contiguous segments uniformly at random.
"""
n = len(nums)
if k < 1 or k > n:
raise ValueError(f"Cannot partition array of size {n} into {k} non-empty segments.")
if rng is None:
rng = random.Random()
# Pick k - 1 distinct boundaries out of n - 1 internal positions
cut_indices = sorted(rng.sample(range(1, n), k - 1))
# Define complete boundaries including start (0) and end (n)
boundaries = [0] + cut_indices + [n]
# Generate the k sublists
return [nums[boundaries[i]:boundaries[i + 1]] for i in range(k)]
Complexity Analysis
- Time Complexity:
- Cut Selection: $O(k)$ on average using standard reservoir sampling algorithms like
random.sample. - Sorting Cuts: $O(k \log k)$ to sort the $k - 1$ indices.
- Array Slicing: $O(N)$ to copy all $N$ elements into their respective sublists.
- Total Time Complexity: $\mathcal{O}(N + k \log k)$. Since $k \le N$, this simplifies to $\mathcal{O}(N)$.
- Cut Selection: $O(k)$ on average using standard reservoir sampling algorithms like
- Space Complexity: $\mathcal{O}(N)$ auxiliary space required to construct and return the partitioned sublists.
Common Pitfalls: Sequential Sizing Bias
A common mistake is choosing segment sizes sequentially. For example, selecting segment length $L_1$ uniformly from $[1, N - (k - 1)]$, updating the remaining length, and repeating.
Why this fails: Consider $N = 5, k = 3$. Total valid partitions: $\binom{4}{2} = 6$. Each valid partition should occur with probability $\frac{1}{6}$. Under the sequential sizing approach:
- For the first segment $L_1$, candidate lengths are ${1, 2, 3}$. The algorithm picks each with probability $\frac{1}{3}$.
- If $L_1 = 3$, the remaining elements equal $2$ and $k=2$, forcing $L_2=1$ and $L_3=1$. Thus, partition $(3, 1, 1)$ gets probability $\frac{1}{3}$.
- If $L_1 = 1$, the remaining length is $4$ and $k=2$. $L_2$ can be ${1, 2, 3}$ with probability $\frac{1}{3}$ each. Thus, partition $(1, 1, 3)$ gets probability $\frac{1}{3} \times \frac{1}{3} = \frac{1}{9}$.
Because $\frac{1}{3} \neq \frac{1}{6}$ and $\frac{1}{9} \neq \frac{1}{6}$, sequential uniform picking creates severe distribution bias.
How to Test Randomness
To verify that the partition output is statistically uniform and free of defects:
1. Invariant Checks
- Sublist Count:
len(result) == k. - Non-Emptiness:
all(len(segment) > 0 for segment in result). - Reconstruction:
[elem for sublist in result for elem in sublist] == nums. - Immutability: Confirm original input array
numsremains untouched.
2. Chi-Square ($\chi^2$) Goodness-of-Fit Test
For a small configuration (e.g., $N = 5, k = 3$ with $M = 6$ possible outcomes):
- Run $T = 60{,}000$ iterations with a deterministic seed.
- Record observed frequencies $O_i$ for each partition schema.
- Compute expected frequency $E_i = \frac{T}{M} = 10{,}000$ for all $i$.
- Calculate the test statistic: $$\chi^2 = \sum_{i=1}^{M} \frac{(O_i - E_i)^2}{E_i}$$
- Verify that $\chi^2$ falls below the critical threshold for $M - 1 = 5$ degrees of freedom at a chosen significance level (e.g., $\alpha = 0.01$).
3. Edge-Case Coverage
- $k = 1$: Output should deterministically return
[nums[:]]. - $k = N$: Output should return $N$ single-element sublists.
- Invalid $k$ values ($k = 0$, $k > N$): Verify
ValueErroris raised.