Day 2 of solving LeetCode problems to prepare for FAANG/MAANG interviews.

Detailed view of financial trading graphs on a monitor, illustrating stock market trends.

Meta:


Introduction

The Product of Array Except Self is a common interview problem that tests your ability to reason about products and efficiencies without relying on division. The task is simple to state but requires careful thinking to meet constraints: no division and O(n) time.

This article covers:


Problem Statement

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

Constraints:

Examples

Example 1

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

Example 2

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Brute-force Approach (Intuitive)

Idea

For each index i, multiply all elements except nums[i] by looping through the array and skipping i. This is the most straightforward approach.

Complexity

Python Implementation (Brute-force)

def product_except_self_bruteforce(nums: list[int]) -> list[int]:
    n = len(nums)
    result = [1] * n
    for i in range(n):
        prod = 1
        for j in range(n):
            if i == j:
                continue
            prod *= nums[j]
        result[i] = prod
    return result

# Example
print(product_except_self_bruteforce([1, 2, 3, 4]))  # [24, 12, 8, 6]

When is brute-force acceptable?

However, interviews and production code require better performance, so we move to the optimized approach.


Optimized Approach — Prefix & Suffix Products (O(n))

Key Insight

For every index i, the answer is the product of everything to the left of i times the product of everything to the right of i:

answer[i] = (product of nums[0..i-1]) * (product of nums[i+1..n-1])

We can compute left products in one left-to-right pass and then incorporate right products in a right-to-left pass, using only constant extra space (besides the output array).

Complexity

Python Implementation (Optimized)

def product_except_self(nums: list[int]) -> list[int]:
    n = len(nums)
    # result holds the prefix products initially
    result = [1] * n

    # Left pass: result[i] will be product of elements to the left of i
    left_product = 1
    for i in range(n):
        result[i] = left_product
        left_product *= nums[i]

    # Right pass: multiply with suffix products on the fly
    right_product = 1
    for i in range(n - 1, -1, -1):
        result[i] *= right_product
        right_product *= nums[i]

    return result

# Example tests
print(product_except_self([1, 2, 3, 4]))        # [24, 12, 8, 6]
print(product_except_self([-1, 1, 0, -3, 3]))  # [0, 0, 9, 0, 0]

Why this handles zeros correctly


Alternative (Counting Zeros) — Another O(n) approach

You can also solve this using a single pass by counting zeros and computing the total product of non-zero elements.

Logic

This method can be used when you are allowed to use division or if you only want a constant-time per-index after precomputation and handle zeros carefully.


Edge Cases & Notes

  1. Zeros: Covered above. One zero vs multiple zeros differ.
  2. Negative numbers: Signs are handled naturally by multiplication.
  3. Large arrays: Use the O(n) method. The brute-force approach will time out or be slow.
  4. 32-bit guarantee: The problem guarantees products of prefixes/suffixes will fit in 32-bit signed integer ranges for test inputs. If implementing for arbitrary inputs, consider big integers or checks for overflow.

Tests (Additional)

# random tests
print(product_except_self([5, 0, 2]))     # [0, 10, 0]
print(product_except_self([2, 3]))        # [3, 2]
print(product_except_self([1, -1, 1]))    # [-1, 1, -1]

Final Thoughts

This problem is a great exercise in transforming an obvious but slow solution into a fast, memory-efficient one by reusing the output array as temporary storage and performing two linear passes. The prefix/suffix technique is widely applicable to other problems that combine information from both sides of an index.


Advertisement

300×250 Medium Rectangle

Leave a Reply

Your email address will not be published. Required fields are marked *