The Blind Multiplier
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L4
Problem
Given a list of integers, return a list of the same length where position i is the product of all input elements except nums[i]. Do not use division. Runtime should be O(n).
Compute the result of everything around you - without seeing yourself.
Example 1
Input:
nums = [1,2,3,4]
Output:
[24,12,8,6]
Example 2
Input:
nums = [-1,1,0,-3,3]
Output:
[0,0,9,0,0]
Worked solution and explanation
Why this problem exists in real interviews
Product of array except self without division tests prefix and suffix product computation. It is a classic array problem that checks whether you can decompose the problem into two passes.
Break down the requirements
Step 1: Compute prefix products
For each index i, prefix[i] is the product of all elements before i.
Step 2: Compute suffix products
For each index i, suffix[i] is the product of all elements after i.
Step 3: Multiply prefix and suffix at each position
The product of everything except nums[i] is prefix[i] * suffix[i].
The solution
def product_except_self(nums):
n = len(nums)
result = [1] * n
prefix = 1
for i in range(n):
result[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(n - 1, -1, -1):
result[i] *= suffix
suffix *= nums[i]
return resultCommon follow-up questions
- What if the array contains zeros? (Tests that the prefix-suffix approach handles zeros naturally, unlike the division approach.)
- Can you solve this with O(1) extra space? (Tests the two-pass approach using the output array as shown in the solution.)
- What if you needed the result modulo a prime? (Tests applying modulo at each multiplication step to prevent overflow (relevant in languages with fixed-width integers).)