NeetCode 150 / Arrays & Hashing

007Product of Array Except Self

MediumArrays & HashingO(n)

Dry run

nums = [1, 2, 3, 4]Step 1 of 10
1
0
2
1
3
2
4
3
answer
1
1
1
1

Start every answer at 1 — it will accumulate the prefix product, then the suffix product.

Pythontime O(n) · space O(1) extra (output array doesn't count)
1def productExceptSelf(nums):
2 n = len(nums)
3 result = [1] * n
4 prefix = 1
5 for i in range(n):
6 result[i] = prefix
7 prefix *= nums[i]
8 suffix = 1
9 for i in range(n - 1, -1, -1):
10 result[i] *= suffix
11 suffix *= nums[i]
12 return result
Variables
i—
prefix—
suffix—

Problem

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all elements of nums except nums[i]. You must solve it without division and in O(n) time.

Examples

Input: nums = [1,2,3,4]Output: [24,12,8,6]
Input: nums = [-1,1,0,-3,3]Output: [0,0,9,0,0]

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • -30 ≤ nums[i] ≤ 30
  • The product of any prefix or suffix fits in a 32-bit integer

Intuition

answer[i] is exactly (product of everything left of i) × (product of everything right of i). Compute the prefix products in one left-to-right pass, storing them directly into the answer array, then multiply in the suffix products with one right-to-left pass — no division needed, and no extra array beyond the output.

Brute force → Optimal

Brute force

For each index, multiply every other element by looping over the whole array again.

Time O(n²)Space O(1) extra
Optimal

One pass fills answer[i] with the prefix product (everything before i). A second pass, right to left, multiplies in the suffix product (everything after i) using a single running variable.

Time O(n)Space O(1) extra (output array doesn't count)

Complexity

Time O(n)Space O(1) extra (output array doesn't count)

Edge cases

  • Exactly one zero in the array: every answer is 0 except at the zero's own index, which gets the product of everything else.
  • Two or more zeros: every answer is 0, since every index excludes at most one zero.

Common mistakes

  • Dividing by nums[i] from the total product — breaks the moment any element is 0, and the problem explicitly disallows division anyway.
  • Allocating a separate prefix array and a separate suffix array instead of reusing the output array and one running variable for the suffix pass.

জটিলতা

O(n)
সময় — অ্যারেটা একবারই ঘুরি, ম্যাপে খোঁজা O(1)।
O(1)
জায়গা — সবচেয়ে খারাপ ক্ষেত্রে সব সংখ্যা ম্যাপে থাকে।
আগের সমস্যা← Encode and Decode Stringsপরের সমস্যাValid Sudoku →