Typorithm · medium

Product Except Self

product-except-selfprefix-sumsprefix-productsuffix-productno-division
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Product Except Self

0%

Prefix Sums

Two passes: fill result with left products, then multiply each by the running right product — no division needed.

Each output is the product of all elements except the one at that index.

A forward pass stores the product of everything to the left of each index.

A backward pass multiplies in the product of everything to the right, avoiding division entirely.

01

Left products in a forward pass.

02

Right products in a backward pass.

03

No division — handles zeros safely.

function productExceptSelf(nums) {
  const n = nums.length;
  const result = new Array(n).fill(1);

  let prefix = 1;
  for (let i = 0; i < n; i += 1) {
    result[i] = prefix;
    prefix *= nums[i];
  }

  let suffix = 1;
  for (let i = n - 1; i >= 0; i -= 1) {
    result[i] *= suffix;
    suffix *= nums[i];
  }

  return result;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Left product

Store the product of everything to the left of i.

result[i] = prefix

2. Extend prefix

Fold nums[i] into the running left product.

prefix *= nums[i]

3. Times right product

Multiply by the product of everything to the right.

result[i] *= suffix

4. Extend suffix

Fold nums[i] into the running right product.

suffix *= nums[i]

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Product Except Self: Lesson & Practice · Typorithm | ApplyDjinn