InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Product of Array Except Self

medium Original ↗ 00:00

Problem

Given an integer array nums, return an array answer where answer[i] is the product of every element of nums except nums[i].

Two constraints:

  • You may not use division.
  • The algorithm must run in O(n) time.

Follow-up: compute it with O(1) extra space, not counting the output array.

All prefix/suffix products are guaranteed to fit in a 32-bit integer.

Examples

Example 1: nums = [1, 2, 3, 4][24, 12, 8, 6] For index 0: 2·3·4 = 24; for index 1: 1·3·4 = 12; and so on.

Example 2: nums = [-1, 1, 0, -3, 3][0, 0, 9, 0, 0] Every position except the zero’s own picks up the 0 factor; at the zero’s index the remaining product is (-1)·1·(-3)·3 = 9.

Constraints

  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30

n up to 10^5 rules out the O(n²) pairwise product; the no-division rule rules out the “total product / nums[i]” shortcut (which zeros break anyway).

Think about it first

Hint 1 The product of everything except index i splits into two independent pieces. Which two?
Hint 2 Can you compute, in one left-to-right pass, the product of everything *before* each index? And in one right-to-left pass, everything *after* it?
Hint 3 `answer[i] = prefix[i] * suffix[i]`. For O(1) extra space: write the prefix products directly into the output array on the first pass, then sweep right-to-left carrying a running suffix product in a single variable and multiply it in.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug