Skip to main content
Back to problems
Leetcode
Medium
Arrays
Google
Meta
Product Of Array Except Self

Return an array where each position contains the product of all elements except the one at that position.

Acceptance 77%
Problem Statement

Given an integer array nums, build a new array answer such that answer[i] is the product of every value in nums except nums[i].

Do this without using division, and aim for linear time.

The array may contain zeroes, so your approach should handle them correctly.

Input Format

  • A single integer array nums.
  • nums.length = n.
  • Each element is an integer.

Output Format

  • Return an integer array answer of length n.
  • answer[i] should equal the product of all elements in nums except nums[i].

Constraints

  • Use an approach that runs in O(n)O(n) time.
  • Extra space beyond the output array should be kept minimal.
  • Division is not allowed.
  • Handle arrays containing zero values.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,2,3,4]

Output

[24,12,8,6]

Explanation

For each position, multiply all numbers except the one at that index: 2×3×4 = 24, 1×3×4 = 12, 1×2×4 = 8, and 1×2×3 = 6.

Example 2

Input

nums = [-1,1,0,-3,3]

Output

[0,0,9,0,0]

Explanation

Every position except index 2 includes the zero, so the product is 0. At index 2, the product of the remaining values is (-1)×1×(-3)×3 = 9.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.