Product of Array Except Self - Prefix Sum Pattern

Product of Array Except Self in Java using the Prefix Sum pattern: problem statement, approach, template, complexity, and interview tips.

Product of Array Except Self

Problem Statement

Return an array where each element is the product of all other elements of nums, without using division and in O(n) time.

Pattern: Prefix Sum

Precompute running totals so any range sum can be answered in constant time, and so equal-sum questions become hash-map lookups.

Use this pattern when the problem asks about sums of subarrays or ranges, or about counting subarrays with a given sum.

Approach

  1. Build a prefix array (or running sum) in one pass.
  2. Express the answer as a difference of two prefix values.
  3. Use a hash map of prefix value to count or first index when you need to find matching earlier prefixes.

Pattern Template (Java)

int[] prefix = new int[n + 1];
for (int i = 0; i < n; i++) {
    prefix[i + 1] = prefix[i] + nums[i];
}
// sum of nums[l..r] = prefix[r + 1] - prefix[l]

Adapt this template to the exact rules of Product of Array Except Self: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(n) time and O(n) space is typical.

Interview Tips

  • Watch the off-by-one between array indices and prefix indices.
  • Seed the hash map with prefix 0 so subarrays starting at index 0 are counted.
  • Start with a brute-force idea, state its complexity, then explain how the Prefix Sum pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Continuous Subarray Sum

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.