← Back to Codes

2026-06-09 16:36:42

Product of Array Except Self in Python and Java | LeetCode #238

Learn how to solve Product of Array Except Self in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Product of Array Except Self in Python and Java

In this tutorial, we will learn LeetCode #238: Product of Array Except Self in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Product of Array Except Self Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use prefix and suffix products because it gives a clean and optimized solution.

Example input:
nums = [2, 3, 5, 4]

Expected result:
Output: [60, 40, 24, 30]

Explanation:
Each index stores product of all other numbers.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
nums = [2, 3, 5, 4]

Approach:
prefix and suffix products

We update variables step by step until we reach:
Output: [60, 40, 24, 30]

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why prefix and suffix products is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this input.

nums = [2, 3, 5, 4]
answer = [1, 1, 1, 1]

Step 2
Build prefix products from the left.

Before index 0, prefix = 1
answer[0] = 1

Then prefix = 1 * 2 = 2

Step 3
At index 1, prefix is 2.

answer[1] = 2

prefix = 2 * 3 = 6

Step 4
After the left pass, answer stores left products.

answer = [1, 2, 6, 30]

Step 5
Now multiply suffix products from the right.

suffix = 1
answer[3] = 30 * 1 = 30

suffix = 1 * 4 = 4

Step 6
At index 2, suffix is 4.

answer[2] = 6 * 4 = 24

Final answer = [60, 40, 24, 30]

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: [60, 40, 24, 30]

Example 1

Input:
nums = [2, 3, 5, 4]

Output:
Output: [60, 40, 24, 30]

Explanation:
Each index stores product of all other numbers.

Example 2

Input:
nums = [1, 2, 4, 8]

Output:
[64, 32, 16, 8]

Explanation:
Each position contains the product of all numbers except itself.

Python Code

Here is the complete Python solution for LeetCode #238.

class ProductExceptSelfBuilder:
    def product_except_self(self, nums):
        answer = [1] * len(nums)

        prefix = 1
        for i in range(len(nums)):
            answer[i] = prefix
            prefix *= nums[i]

        suffix = 1
        for i in range(len(nums) - 1, -1, -1):
            answer[i] *= suffix
            suffix *= nums[i]

        return answer


builder = ProductExceptSelfBuilder()
print(builder.product_except_self([2, 3, 5, 4]))  # Output: [60, 40, 24, 30]
print(builder.product_except_self([1, 2, 3]))     # Output: [6, 3, 2]

Java Code

Here is the complete Java solution for LeetCode #238.

import java.util.Arrays;

class ProductExceptSelfBuilder {
    public int[] productExceptSelf(int[] nums) {
        int[] answer = new int[nums.length];

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

        int suffix = 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            answer[i] *= suffix;
            suffix *= nums[i];
        }

        return answer;
    }

    public static void main(String[] args) {
        ProductExceptSelfBuilder builder = new ProductExceptSelfBuilder();
        System.out.println(Arrays.toString(builder.productExceptSelf(new int[] {2, 3, 5, 4}))); // [60, 40, 24, 30]
        System.out.println(Arrays.toString(builder.productExceptSelf(new int[] {1, 2, 3})));    // [6, 3, 2]
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(1)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #238: Product of Array Except Self becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.