Loading…
Product of Array Except Self is a medium coding interview question covering arrays — the kind asked at FAANG (Facebook/Meta, Apple, Amazon, Netflix, Google) and AI-first companies like Anthropic, OpenAI, and Nvidia.
Given an integer array nums, return an array output where output[i] is the product of all elements except nums[i].
Example: [1,2,3,4] -> [24,12,8,6]
You must do this in O(n) without using the division operator.
Try it yourself first
In an interview you'd get about 25 minutes for a medium question. Sketch an approach before peeking — struggling is where the learning happens.
Stuck? Reveal them one at a time — each hint gives away a little more.
Ready to compare notes? The full solution, visualization, and complexity analysis are below.
Two-pass O(n) solution with O(1) extra space. First pass: output[i] = product of all elements to the left of i. Second pass (right to left): multiply by running right product. No division needed — avoids the divide-by-zero edge case.
| 1 | def product_except_self(nums: list[int]) -> list[int]: |
| ▶ | n = len(nums) |
| ▶ | output = [1] * n |
| 4 | |
| 5 | # Left pass: output[i] = product of nums[0..i-1] |
| 6 | for i in range(1, n): |
| 7 | output[i] = output[i-1] * nums[i-1] |
| 8 | |
| 9 | # Right pass: multiply by product of nums[i+1..n-1] |
| 10 | right = 1 |
| 11 | for i in range(n-1, -1, -1): |
| 12 | output[i] *= right |
| 13 | right *= nums[i] |
| 14 | |
| 15 | return output |
Left pass: output[i] = product of all elements to the left. Start with output=[1,1,1,1], prefix=1.
Key Insights
A full interview loop is more than one round. These are the others, each with what is on the site for it.