KatInterview

Uniform Random Array Partitioning into K Segments

Arrays & HashingModel answer
MediumModel answerArrays & Hashingarraysmath-bitsheaps-sorting

Last 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:

  1. Contiguous and Ordered: The sequence of sublists, when concatenated, must equal the original nums list in its original order.
  2. Non-Empty: Every sublist must contain at least one element.
  3. 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.
  4. Immutability: The input array nums must 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?