Solve weighted pick and product except self
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates algorithm design and data-structure skills, focusing on weighted random selection and array aggregation for product computations within the Coding & Algorithms domain.
Random Pick with Weight (Deterministic Core)
Constraints
- 1 <= len(w) <= 10^4
- 1 <= w[i] <= 10^5
- 1 <= target <= sum(w)
Examples
Input: ([1], 1)
Expected Output: 0
Explanation: Single bucket; any target in [1,1] picks index 0.
Input: ([1, 3], 1)
Expected Output: 0
Explanation: prefix=[1,4]; target 1 <= 1 so index 0.
Hints
- Convert each weight into a cumulative range. Index i 'owns' the integers (P[i-1], P[i]].
- With prefix sums sorted ascending, finding the owning index for a target is a classic lower-bound binary search: find the first prefix value that is >= target.
- Be careful with the binary-search boundary: use a [lo, hi] window that converges to a single index, moving lo = mid+1 only when prefix[mid] < target.
Product of Array Except Self
Constraints
- 2 <= len(nums) <= 10^5
- -30 <= nums[i] <= 30
- The product of any prefix or suffix of nums fits in a 32-bit integer.
Examples
Input: ([1, 2, 3, 4],)
Expected Output: [24, 12, 8, 6]
Explanation: Standard case: 2*3*4=24, 1*3*4=12, 1*2*4=8, 1*2*3=6.
Input: ([-1, 1, 0, -3, 3],)
Expected Output: [0, 0, 9, 0, 0]
Explanation: Single zero: only the zero's own position gets a nonzero product (-1*1*-3*3=9); all others include the zero.
Hints
- answer[i] = (product of everything to the left of i) * (product of everything to the right of i). Compute these two pieces separately.
- First pass left-to-right: store in result[i] the running product of all elements strictly before i.
- Second pass right-to-left: multiply result[i] by a running product of all elements strictly after i. This avoids division and naturally handles zeros.