Neural Mastery
← Practice
Product of Array Except Selfmedium

Product of Array Except Self

medium Coding Interview Patterns 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Implement Product of Array Except Self via two passes (prefix products, then suffix products) -- the classic answer to "compute this without division," which also correctly handles zeros in the input.

Related Skills

Task

Implement product_except_self(nums): first pass left-to-right builds each position's product of everything BEFORE it; second pass right-to-left multiplies in the product of everything AFTER it.

Function Signature

product_except_self(nums: list[int]) -> list[int]

Examples

Example 1: No Zeros
Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]
Example 2: Exactly One Zero
Input: nums = [-1, 1, 0, -3, 3]
Output: [0, 0, 9, 0, 0]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Division is not allowed (a zero in the input would break a divide-by-total approach anyway).
  • Must run in O(n) time.
Python3Saved ✓
def product_except_self(nums: list[int]) -> list[int]:
"""Return a list where result[i] is the product of every element in
nums EXCEPT nums[i]. Must not use division, and must run in O(n)
time (extra O(n) output space is fine; the classic follow-up asks
for O(1) *extra* space beyond the output, but that isn't required
here)."""
# Your implementation here
pass

Case 1: No Zeros
Input: nums = [1, 2, 3, 4]
Expected: [24, 12, 8, 6]
Case 2: Exactly One Zero
Input: nums = [-1, 1, 0, -3, 3]
Expected: [0, 0, 9, 0, 0]