Arrays January 13 ,2026

Product of Array Except Self

Problem Statement

You are given an array of integers arr of size n.
Your task is to return an array output such that:

output[i] = product of all elements of arr except arr[i]

Constraints

  • Do not use division (in the optimal approach)
  • Solve in O(n) time

Example 1

Input

arr = [1, 2, 3, 4]

Output

[24, 12, 8, 6]

Example 2

Input

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

Output

[0, 0, 9, 0, 0]

Why This Problem Is Important

  • Very frequently asked interview problem
  • Tests array traversal and prefix logic
  • Tests space optimization
  • Appears in FAANG interviews
  • Builds foundation for prefix & suffix techniques

Approaches Overview

ApproachTechniqueTimeSpace
Approach 1Brute ForceO(n²)O(1)
Approach 2Using DivisionO(n)O(1)
Approach 3Prefix & Suffix Product (Optimal)O(n)O(1)

Approach 1: Brute Force

Idea

For each index, calculate the product of all elements except the current one using nested loops.

Algorithm

  1. Initialize an output array
  2. For each index i
    • Set product = 1
    • Loop through array
    • Multiply all elements except i
  3. Store product in output array

Time & Space Complexity

  • Time: O(n²)
  • Space: O(1) (excluding output array)

Implementations

C

#include 

int main() {
    int arr[] = {1,2,3,4};
    int n = 4;
    int output[4];

    for(int i = 0; i < n; i++) {
        int prod = 1;
        for(int j = 0; j < n; j++) {
            if(i != j)
                prod *= arr[j];
        }
        output[i] = prod;
    }

    for(int i = 0; i < n; i++)
        printf("%d ", output[i]);

    return 0;
}

C++

#include 
using namespace std;

int main() {
    int arr[] = {1,2,3,4};
    int n = 4;
    int output[4];

    for(int i = 0; i < n; i++) {
        int prod = 1;
        for(int j = 0; j < n; j++) {
            if(i != j)
                prod *= arr[j];
        }
        output[i] = prod;
    }

    for(int i = 0; i < n; i++)
        cout << output[i] << " ";

    return 0;
}

Java

public class ProductExceptSelf {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4};
        int n = arr.length;
        int[] output = new int[n];

        for(int i = 0; i < n; i++) {
            int prod = 1;
            for(int j = 0; j < n; j++) {
                if(i != j)
                    prod *= arr[j];
            }
            output[i] = prod;
        }

        for(int val : output)
            System.out.print(val + " ");
    }
}

Python

arr = [1,2,3,4]
n = len(arr)
output = []

for i in range(n):
    prod = 1
    for j in range(n):
        if i != j:
            prod *= arr[j]
    output.append(prod)

print(output)

JavaScript

let arr = [1,2,3,4];
let output = [];

for (let i = 0; i < arr.length; i++) {
    let prod = 1;
    for (let j = 0; j < arr.length; j++) {
        if (i !== j)
            prod *= arr[j];
    }
    output.push(prod);
}

console.log(output);

Approach 2: Using Division

Idea

Compute total product of all elements.
For each index, divide total product by arr[i].

⚠️ Fails when array contains zero(s)

Algorithm

  1. Compute total product
  2. For each index i, output = totalProduct / arr[i]

Time & Space Complexity

  • Time: O(n)
  • Space: O(1)

Implementations

C

#include 

int main() {
    int arr[] = {1,2,3,4};
    int n = 4;
    int product = 1;

    for(int i = 0; i < n; i++)
        product *= arr[i];

    for(int i = 0; i < n; i++)
        printf("%d ", product / arr[i]);

    return 0;
}

C++

#include 
using namespace std;

int main() {
    int arr[] = {1,2,3,4};
    int n = 4;
    int product = 1;

    for(int i = 0; i < n; i++)
        product *= arr[i];

    for(int i = 0; i < n; i++)
        cout << product / arr[i] << " ";

    return 0;
}

Java

public class ProductExceptSelf {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4};
        int product = 1;

        for(int num : arr)
            product *= num;

        for(int num : arr)
            System.out.print(product / num + " ");
    }
}

Python

arr = [1,2,3,4]
product = 1

for num in arr:
    product *= num

print([product // num for num in arr])

JavaScript

let arr = [1,2,3,4];
let product = 1;

for (let num of arr)
    product *= num;

console.log(arr.map(num => product / num));
Building a Product Array without the Element Itself | avni.sh

Approach 3: Prefix & Suffix Product (Optimal)

Idea

Instead of division, compute:

  • Prefix product (left side)
  • Suffix product (right side)

Multiply both for each index.

Algorithm

  1. Create output array initialized with 1
  2. Traverse left → right
    • output[i] = product of elements before i
  3. Traverse right → left
    • output[i] *= product of elements after i

Time & Space Complexity

  • Time: O(n)
  • Space: O(1) (excluding output array)

Implementations

C

#include 

int main() {
    int arr[] = {1,2,3,4};
    int n = 4;
    int output[4];

    int prefix = 1;
    for(int i = 0; i < n; i++) {
        output[i] = prefix;
        prefix *= arr[i];
    }

    int suffix = 1;
    for(int i = n - 1; i >= 0; i--) {
        output[i] *= suffix;
        suffix *= arr[i];
    }

    for(int i = 0; i < n; i++)
        printf("%d ", output[i]);

    return 0;
}

C++

#include 
using namespace std;

int main() {
    int arr[] = {1,2,3,4};
    int n = 4;
    int output[4];

    int prefix = 1;
    for(int i = 0; i < n; i++) {
        output[i] = prefix;
        prefix *= arr[i];
    }

    int suffix = 1;
    for(int i = n - 1; i >= 0; i--) {
        output[i] *= suffix;
        suffix *= arr[i];
    }

    for(int i = 0; i < n; i++)
        cout << output[i] << " ";

    return 0;
}

Java

public class ProductExceptSelf {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4};
        int n = arr.length;
        int[] output = new int[n];

        int prefix = 1;
        for(int i = 0; i < n; i++) {
            output[i] = prefix;
            prefix *= arr[i];
        }

        int suffix = 1;
        for(int i = n - 1; i >= 0; i--) {
            output[i] *= suffix;
            suffix *= arr[i];
        }

        for(int val : output)
            System.out.print(val + " ");
    }
}

Python

arr = [1,2,3,4]
n = len(arr)
output = [1] * n

prefix = 1
for i in range(n):
    output[i] = prefix
    prefix *= arr[i]

suffix = 1
for i in range(n-1, -1, -1):
    output[i] *= suffix
    suffix *= arr[i]

print(output)

JavaScript

let arr = [1,2,3,4];
let n = arr.length;
let output = Array(n).fill(1);

let prefix = 1;
for (let i = 0; i < n; i++) {
    output[i] = prefix;
    prefix *= arr[i];
}

let suffix = 1;
for (let i = n - 1; i >= 0; i--) {
    output[i] *= suffix;
    suffix *= arr[i];
}

console.log(output);

Dry Run (Prefix & Suffix)

Input

[1, 2, 3, 4]
  • Prefix pass → [1, 1, 2, 6]
  • Suffix pass → [24, 12, 8, 6]

Final Output

[24, 12, 8, 6]

Summary

  • Brute force is inefficient
  • Division method is simple but unsafe
  • Prefix & Suffix approach is optimal and interview-preferred
  • Solves in linear time without division

Next Problem in the Series

Maximum Product Subarray
 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com