Product of Array Except Self [Medium]

29 Aug 2026 2 min read
2
The Product of Array Except Self problem requires calculating the product of all elements except the element at the current index.

Problem

You are given an integer array nums.

Return an array answer such that answer[i] is equal to the product of every element in nums except nums[i].

The solution should run in O(n) time and should not use division.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

nums = [1,2,3,4]

Output

[24,12,8,6]

Solution

For every position, the required product can be divided into two parts: the product of all elements to its left and the product of all elements to its right.

We can first store the product of all elements to the left of each position in the result array. We then traverse the array from right to left and multiply each result by the product of all elements to its right.

This allows us to calculate the result using only the output array and one variable, without creating separate prefix and suffix arrays.
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] answer = new int[n];

        // Store prefix products.
        int prefix = 1;
        for (int i = 0; i < n; i++) {
            answer[i] = prefix;
            prefix *= nums[i];
        }

        // Multiply by suffix products.
        int suffix = 1;
        for (int i = n - 1; i >= 0; i--) {
            answer[i] *= suffix;
            suffix *= nums[i];
        }
        return answer;
    }
}

Complexity

The array is traversed twice, resulting in O(n) time complexity. The output array is used to store the prefix products, and only constant extra space is used apart from the output array, resulting in O(1) extra space.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion