Weighted Random Index Sampling and Exclusion Product Array
Arrays & HashingModel answerLast 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:
__init__(weights: List[int]): Initializes the object with the given weights.pickIndex() -> int: Randomly chooses and returns an index $i \in [0, \text{len}(weights) - 1]$. The probability of selecting index $i$ must be proportional toweights[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$
pickIndexwill be called up to $10^4$ times.- Optimizing
pickIndextime 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
numsis 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Overview
Both tasks depend on prefix aggregates—computing cumulative values across the array once to perform efficient downstream queries or avoid redundant work.
Part 1: Weighted Random Selection
Mathematical Concept
If we lay out intervals on a line where index $i$ owns a segment of length $\text{weights}[i]$, the total length is $S = \sum \text{weights}[i]$.
For example, given weights = [1, 3, 2]:
- Cumulative prefix sum array:
[1, 4, 6]. - Index 0 corresponds to range $[1, 1]$ (length 1).
- Index 1 corresponds to range $[2, 4]$ (length 3).
- Index 2 corresponds to range $[5, 6]$ (length 2).
Generating a uniform random integer $r \in [1, S]$ and finding the first prefix sum greater than or equal to $r$ selects index $i$ with probability $\frac{\text{weights}[i]}{S}$.
Algorithm
- In
__init__, build a cumulative prefix sum arrayprefix_sums. - In
pickIndex:- Sample integer $r \sim \text{Uniform}(1, S)$, where $S$ is the final entry in
prefix_sums. - Use binary search (
bisect_left) to find the smallest indexidxwhereprefix_sums[idx] >= r.
- Sample integer $r \sim \text{Uniform}(1, S)$, where $S$ is the final entry in
Complexity
- Constructor: $O(n)$ time to build the prefix sums, $O(n)$ space.
pickIndex: $O(\log n)$ time per call using binary search, $O(1)$ extra space.
Part 2: Element Exclusion Product Array
Mathematical Concept
For index $i$, the target product is: $$\text{output}[i] = \left( \prod_{j=0}^{i-1} \text{nums}[j] \right) \times \left( \prod_{k=i+1}^{n-1} \text{nums}[k] \right)$$
Without division, we can compute left prefix products and right suffix products independently:
- Left Pass: Populating
output[i]with the running product of elements strictly to the left of index $i$. - Right Pass: Sweeping right-to-left while maintaining a running scalar variable
right_productrepresenting the product of elements strictly to the right of index $i$. Multiplyoutput[i]byright_productat each step.
Why Division Fails on Zeroes
If division were allowed, input arrays with zeros would cause edge cases:
- One zero: Output is non-zero only at the zero index.
- Two or more zeros: All outputs become zero. The prefix/suffix approach handles all zero variations naturally without special handling.
Complexity
- Time Complexity: $O(n)$ total (two linear passes).
- Space Complexity: $O(1)$ auxiliary memory (excluding the returned result array).
Source Code
import random
import bisect
from typing import List
class WeightedSampler:
"""
Part 1: Weighted Random Selection
"""
def __init__(self, weights: List[int]):
self.prefix_sums = []
running_total = 0
for w in weights:
running_total += w
self.prefix_sums.append(running_total)
self.total_sum = running_total
def pickIndex(self) -> int:
# Generate target in range [1, total_sum] inclusive
target = random.randint(1, self.total_sum)
# Perform lower bound binary search
return bisect.bisect_left(self.prefix_sums, target)
class Solution:
"""
Part 2: Product of Array Except Self
"""
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
output = [1] * n
# Pass 1: Compute left products directly in output array
left_product = 1
for i in range(n):
output[i] = left_product
left_product *= nums[i]
# Pass 2: Compute right products on-the-fly and combine
right_product = 1
for i in range(n - 1, -1, -1):
output[i] *= right_product
right_product *= nums[i]
return output
Key Takeaways & Interview Follow-ups
- Random Pick Updates (Dynamic Weights): If weight values mutate frequently, maintaining a static prefix array requires $O(n)$ updates. A Binary Indexed Tree (Fenwick Tree) or Segment Tree reduces both update and sampling operations to $O(\log n)$.
- $O(1)$ Time Random Sampling: If the weight array is static and $O(1)$ query performance is required, Alias Method (Vose's algorithm) allows $O(n)$ initialization and $O(1)$ sampling per pick.
- Off-by-one errors in sampling: Ensure uniform random integer ranges match the binary search boundary. Using a 0-indexed integer draw with a strictly greater condition versus 1-indexed with
>=must be implemented consistently to avoid probability distribution skew.