KatInterview

Weighted Random Index Sampling and Exclusion Product Array

Arrays & HashingModel answer
MediumModel answerArrays & Hashingarraysbinary-searchprefix-sum

Last updated

Implement weighted index sampling with binary search and an exclusion product array without division in O(1) auxiliary space.

This assessment consists of two fundamental algorithmic tasks centered on array precomputation strategies.


Task 1: Weighted Random Selection

Given an array of positive integers weights representing the relative weight of each index, write a class with two methods:

  1. __init__(weights: List[int]): Initializes the object with the given weights.
  2. pickIndex() -> int: Randomly chooses and returns an index $i \in [0, \text{len}(weights) - 1]$. The probability of selecting index $i$ must be proportional to weights[i], specifically: $$\mathbb{P}(\text{index } i) = \frac{\text{weights}[i]}{\sum_{j} \text{weights}[j]}$$

Constraints & Notes

  • $1 \le \text{weights.length} \le 10^4$
  • $1 \le \text{weights}[i] \le 10^5$
  • pickIndex will be called up to $10^4$ times.
  • Optimizing pickIndex time complexity is essential.

Task 2: Element Exclusion Product Array

Given an array of integers nums, return an array output such that output[i] is equal to the product of all elements of nums except nums[i].

Constraints & Rules

  • $2 \le \text{nums.length} \le 10^5$
  • $-30 \le \text{nums}[i] \le 30$
  • The product of any prefix or suffix of nums is guaranteed to fit in a standard 32-bit integer.
  • You must write an algorithm that runs in $O(n)$ time and does NOT use the division operator.
  • Follow-up: Can you solve it using $O(1)$ extra space complexity? (The output array does not count as extra space for memory complexity analysis.)

Hints

Hint 1

For Task 1: Map each index to an interval on a continuous range using accumulated prefix sums. A uniform random draw in that range can then be mapped to an index using binary search.

Hint 2

For Task 2: Notice that for any index i, the product except nums[i] is equivalent to (product of elements before i) * (product of elements after i).

Hint 3

To achieve O(1) extra space in Task 2, perform the left prefix product pass directly into the output array, then accumulate the right suffix product using a single scalar variable during a backward sweep.