Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Product of Array Except Self
Next article icon

Product of Array Except Self

Last Updated : 13 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[] of n integers, construct a product array res[] (of the same size) such that res[i] is equal to the product of all the elements of arr[] except arr[i]. 

Example: 

Input: arr[] = [10, 3, 5, 6, 2]
Output: [180, 600, 360, 300, 900]
Explanation:

  • For i=0, res[i] = 3 * 5 * 6 * 2 is 180.
  • For i = 1, res[i] = 10 * 5 * 6 * 2 is 600.
  • For i = 2, res[i] = 10 * 3 * 6 * 2 is 360.
  • For i = 3, res[i] = 10 * 3 * 5 * 2 is 300.
  • For i = 4, res[i] = 10 * 3 * 5 * 6 is 900.

Input: arr[] = [12, 0]
Output: [0, 12]
Explanation:

  • For i = 0, res[i] = 0.
  • For i = 1, res[i] = 12.

Table of Content

  • [Naive Approach] Using Nested Loops - O(n^2) Time and O(1) Space
  • [Better approach] Using Prefix and Suffix Array - O(n) Time and O(n) Space
  • [Efficient Approach] Using Product Array - O(n) Time and O(1) Space

[Naive Approach] Using Nested Loops - O(n^2) Time and O(1) Space

The idea is simple, for every element arr[i], we compute product of all elements except itself. To compute the product, we run an inner loop.

C++
#include <iostream> #include <vector> using namespace std;  // Function to calculate the product of all  // elements except the current element vector<int> productExceptSelf(vector<int>& arr) {     int n = arr.size();        // Fill result array with 1     vector<int> res(n, 1);      for (int i = 0; i < n; i++) {                // Compute product of all elements except arr[i]         for (int j = 0; j < n; j++) {             if (i != j)                  res[i] *= arr[j];         }     }      return res; }  int main() {     vector<int> arr = {10, 3, 5, 6, 2};     vector<int> res = productExceptSelf(arr);     for (int val : res)          cout << val << " ";     return 0; } 
C
#include <stdio.h>  // Function to calculate the product of all  // elements except the current element void productExceptSelf(int arr[], int n, int res[]) {        // Initialize result array as 1     for (int i = 0; i < n; i++) {         res[i] = 1;     }      for (int i = 0; i < n; i++) {              	// Compute product of all elements except arr[i]         for (int j = 0; j < n; j++) {             if (i != j) {                 res[i] *= arr[j];             }         }     } }  int main() {     int arr[] = {10, 3, 5, 6, 2};     int n = sizeof(arr) / sizeof(arr[0]);     int res[n];          productExceptSelf(arr, n, res);          for (int i = 0; i < n; i++) {         printf("%d ", res[i]);     }          return 0; } 
Java
import java.util.Arrays; class GfG {        	// Function to calculate the product of all  	// elements except the current element     static int[] productExceptSelf(int[] arr) {         int n = arr.length;          // Initialize the result array as 1         int[] res = new int[n];         Arrays.fill(res, 1);         for (int i = 0; i < n; i++) {              // Compute the product of all except arr[i]             for (int j = 0; j < n; j++) {                 if (i != j) {                     res[i] *= arr[j];                 }             }         }          return res;     }      public static void main(String[] args) {         int[] arr = {10, 3, 5, 6, 2};         int[] res = productExceptSelf(arr);         for (int val : res) {             System.out.print(val + " ");         }     } } 
Python
# Function to calculate the product of all  # elements except the current element def productExceptSelf(arr):     n = len(arr)      # Initialize the result list as 1     res = [1] * n      for i in range(n):                  # Compute the product of all except arr[i]         for j in range(n):             if i != j:                 res[i] *= arr[j]      return res  if __name__ == "__main__":     arr = [10, 3, 5, 6, 2]     res = productExceptSelf(arr)     print(" ".join(map(str, res))) 
C#
using System;  class GfG {          // Function to calculate the product of all    	// elements except the current element     static int[] productExceptSelf(int[] arr) {         int n = arr.Length;         int[] res = new int[n];         Array.Fill(res, 1);          // Compute product of all elements except arr[i]         for (int i = 0; i < n; i++) {             for (int j = 0; j < n; j++) {                 if (i != j) {                     res[i] *= arr[j];                 }             }         }          return res;     }      static void Main(string[] args) {         int[] arr = {10, 3, 5, 6, 2};         int[] res = productExceptSelf(arr);                  foreach (int val in res) {             Console.Write(val + " ");         }     } } 
JavaScript
// Function to calculate the product of all  // elements except the current element function productExceptSelf(arr) {     let n = arr.length;     let res = new Array(n).fill(1);      // Compute product of all elements except arr[i]     for (let i = 0; i < n; i++) {         for (let j = 0; j < n; j++) {             if (i !== j) {                 res[i] *= arr[j];             }         }     }      return res; }  // Driver code let arr = [10, 3, 5, 6, 2]; let res = productExceptSelf(arr); console.log(res.join(" ")); 

Output
180 600 360 300 900 

[Better approach] Using Prefix and Suffix Array - O(n) Time and O(n) Space

The above approach can be optimized by avoiding the repetitive calculation of products of elements. The idea is to precompute the prefix and suffix products and store them in two arrays. Now we can find the product of array except i-th element, by using these precomputed arrays in constant time.

product of array except i-th element = prefProduct[i] * suffProduct[i]

prefProduct[i] stores product of all elements before i-th index in the array.
suffProduct[i] stores product of all elements after i-th index in the array.

C++
#include <iostream> #include <vector> using namespace std;  // Function to calculate the product of all // elements except the current element vector<int> productExceptSelf(vector<int> &arr) {     int n = arr.size();     vector<int> prefProduct(n), suffProduct(n), res(n);      // Construct the prefProduct array     prefProduct[0] = 1;     for (int i = 1; i < n; i++)         prefProduct[i] = arr[i - 1] * prefProduct[i - 1];      // Construct the suffProduct array     suffProduct[n - 1] = 1;     for (int j = n - 2; j >= 0; j--)         suffProduct[j] = arr[j + 1] * suffProduct[j + 1];      // Construct the result array using     // prefProduct[] and suffProduct[]     for (int i = 0; i < n; i++)         res[i] = prefProduct[i] * suffProduct[i]; 	     return res;  }  int main() {     vector<int> arr = {10, 3, 5, 6, 2};     vector<int> res = productExceptSelf(arr);      for (int val : res)         cout << val << " "; } 
Java
import java.util.Arrays;  class GfG {        // Function to calculate the product of all     // elements except the current element     static int[] productExceptSelf(int[] arr) {         int n = arr.length;         int[] prefProduct = new int[n];         int[] suffProduct = new int[n];         int[] res = new int[n];          // Construct the prefProduct array         prefProduct[0] = 1;         for (int i = 1; i < n; i++)             prefProduct[i] = arr[i - 1] * prefProduct[i - 1];          // Construct the suffProduct array         suffProduct[n - 1] = 1;         for (int j = n - 2; j >= 0; j--)             suffProduct[j] = arr[j + 1] * suffProduct[j + 1];          // Construct the result array using         // prefProduct[] and suffProduct[]         for (int i = 0; i < n; i++)             res[i] = prefProduct[i] * suffProduct[i];          return res;     }      public static void main(String[] args) {         int[] arr = {10, 3, 5, 6, 2};         int[] res = productExceptSelf(arr);          System.out.println(Arrays.toString(res));     } } 
Python
# Function to calculate the product of all # elements except the current element def productExceptSelf(arr):     n = len(arr)     prefProduct = [1] * n     suffProduct = [1] * n     res = [0] * n      # Construct the prefProduct array     for i in range(1, n):         prefProduct[i] = arr[i - 1] * prefProduct[i - 1]      # Construct the suffProduct array     for j in range(n - 2, -1, -1):         suffProduct[j] = arr[j + 1] * suffProduct[j + 1]      # Construct the result array using     # prefProduct[] and suffProduct[]     for i in range(n):         res[i] = prefProduct[i] * suffProduct[i]      return res  if __name__ == '__main__':     arr = [10, 3, 5, 6, 2]     res = productExceptSelf(arr)     print(res) 
C#
using System;  class GFG {     // Function to calculate the product of all     // elements except the current element     static int[] productExceptSelf(int[] arr) {         int n = arr.Length;         int[] prefProduct = new int[n];         int[] suffProduct = new int[n];         int[] res = new int[n];          // Construct the prefProduct array         prefProduct[0] = 1;         for (int i = 1; i < n; i++)             prefProduct[i] = arr[i - 1] * prefProduct[i - 1];          // Construct the suffProduct array         suffProduct[n - 1] = 1;         for (int j = n - 2; j >= 0; j--)             suffProduct[j] = arr[j + 1] * suffProduct[j + 1];          // Construct the result array using         // prefProduct[] and suffProduct[]         for (int i = 0; i < n; i++)             res[i] = prefProduct[i] * suffProduct[i];          return res;     }      static void Main() {         int[] arr = {10, 3, 5, 6, 2};         int[] res = productExceptSelf(arr);          Console.WriteLine(string.Join(" ", res));     } } 
JavaScript
// Function to calculate the product of all // elements except the current element function productExceptSelf(arr) {     const n = arr.length;     const prefProduct = new Array(n).fill(1);     const suffProduct = new Array(n).fill(1);     const res = new Array(n);      // Construct the prefProduct array     for (let i = 1; i < n; i++) {         prefProduct[i] = arr[i - 1] * prefProduct[i - 1];     }      // Construct the suffProduct array     for (let j = n - 2; j >= 0; j--) {         suffProduct[j] = arr[j + 1] * suffProduct[j + 1];     }      // Construct the result array using     // prefProduct[] and suffProduct[]     for (let i = 0; i < n; i++) {         res[i] = prefProduct[i] * suffProduct[i];     }      return res; }  // Driver Code const arr = [10, 3, 5, 6, 2]; const res = productExceptSelf(arr); console.log(res.join(" ")); 

Output
180 600 360 300 900  

[Efficient Approach] Using Product Array - O(n) Time and O(1) Space

The idea is to handle two special cases of the input array: when it contains zero(s) and when it doesn't.

If the array has no zeros, product of array at any index (excluding itself) can be calculated by dividing the total product of all elements by the current element.

However, division by zero is undefined, so if there are zeros in the array, the logic changes. If there is exactly one zero, the product for that index will be the product of all other non-zero elements, while the elements in rest of the indices will be zero.
If there are more than one zero, the product for all indices will be zero, since multiplying by zero results in zero.

C++
#include <iostream> #include <vector> using namespace std;  // Function to calculate the product of all elements  // except the current element vector<int> productExceptSelf(vector<int> &arr) {     int zeros = 0, idx = -1;     int prod = 1;      // Count zeros and track the index of the zero     for (int i = 0; i < arr.size(); ++i) {         if (arr[i] == 0) {             zeros++;             idx = i;         } else {             prod *= arr[i];         }     }      vector<int> res(arr.size(), 0);      // If no zeros, calculate the product for all elements     if (zeros == 0) {         for (int i = 0; i < arr.size(); i++)             res[i] = prod / arr[i];     }     // If one zero, set product only at the zero's index     else if (zeros == 1)         res[idx] = prod;      return res; }  int main() {     vector<int> arr = {10, 3, 5, 6, 2};     vector<int> res = productExceptSelf(arr);      for (int val : res)         cout << val << " "; } 
Java
import java.util.Arrays;  class GfG {        // Function to calculate the product of all elements      // except the current element     static int[] productExceptSelf(int[] arr) {         int zeros = 0, idx = -1, prod = 1;         int n = arr.length;          // Count zeros and track the index of the zero         for (int i = 0; i < n; i++) {             if (arr[i] == 0) {                 zeros++;                 idx = i;             } else {                 prod *= arr[i];             }         }          int[] res = new int[n];         Arrays.fill(res, 0);          // If no zeros, calculate the product for all elements         if (zeros == 0) {             for (int i = 0; i < n; i++)                  res[i] = prod / arr[i];         }         // If one zero, set product only at the zero's index         else if (zeros == 1)             res[idx] = prod;          return res;     }      public static void main(String[] args) {         int[] arr = {10, 3, 5, 6, 2};         int[] res = productExceptSelf(arr);          for (int val : res)             System.out.print(val + " ");     } } 
Python
# Function to calculate the product of all elements  # except the current element  def productExceptSelf(arr):     zeros = 0     idx = -1     prod = 1      # Count zeros and track the index of the zero     for i in range(len(arr)):         if arr[i] == 0:             zeros += 1             idx = i         else:             prod *= arr[i]      res = [0] * len(arr)      # If no zeros, calculate the product for all elements     if zeros == 0:         for i in range(len(arr)):             res[i] = prod // arr[i]     # If one zero, set product only at the zero's index     elif zeros == 1:         res[idx] = prod      return res   if __name__ == "__main__":     arr = [10, 3, 5, 6, 2]     res = productExceptSelf(arr)     print(" ".join(map(str, res))) 
C#
using System;  class GfG {     // Function to calculate the product of all elements  	// except the current element     static int[] productExceptSelf(int[] arr) {         int zeros = 0, idx = -1, prod = 1;         int n = arr.Length;          // Count zeros and track the index of the zero         for (int i = 0; i < n; i++) {             if (arr[i] == 0) {                 zeros++;                 idx = i;             } else {                 prod *= arr[i];             }         }          int[] res = new int[n];         Array.Fill(res, 0);          // If no zeros, calculate the product for all elements         if (zeros == 0) {             for (int i = 0; i < n; i++)                  res[i] = prod / arr[i];         }         // If one zero, set product only at the zero's index         else if (zeros == 1)             res[idx] = prod;          return res;     }      static void Main(string[] args) {         int[] arr = {10, 3, 5, 6, 2};         int[] res = productExceptSelf(arr);          Console.WriteLine(string.Join(" ", res));     } } 
JavaScript
// Function to calculate the product of all elements  // except the current element function productExceptSelf(arr) {     let zeros = 0, idx = -1, prod = 1; 	     // Count zeros and track the index of the zero     for (let i = 0; i < arr.length; i++) {         if (arr[i] === 0) {             zeros++;             idx = i;         } else {             prod *= arr[i];         }     }      let res = new Array(arr.length).fill(0);      // If no zeros, calculate the product for all elements     if (zeros === 0) {         for (let i = 0; i < arr.length; i++)              res[i] = Math.floor(prod / arr[i]);     }     // If one zero, set product only at the zero's index     else if (zeros === 1)         res[idx] = prod;      return res; }  // Driver Code let arr = [10, 3, 5, 6, 2]; let res = productExceptSelf(arr); console.log(res.join(" ")); 

Output
180 600 360 300 900  

Other Mathematical Approaches:

Please refer A product array puzzle for more approaches that use log and pow to compute the required result without division operator.

Related Problem: 
Construct an Array from XOR of all elements of array except element at same index


Next Article
Product of Array Except Self

K

kartik
Improve
Article Tags :
  • Mathematical
  • DSA
  • Arrays
  • Amazon
  • Morgan Stanley
  • D-E-Shaw
  • Accolite
  • Opera
  • prefix-sum
Practice Tags :
  • Accolite
  • Amazon
  • D-E-Shaw
  • Morgan Stanley
  • Opera
  • Arrays
  • Mathematical
  • prefix-sum

Similar Reads

    Maximum product subset of an array
    Given an array a, we have to find the maximum product possible with the subset of elements present in the array. The maximum product can be a single element also.Examples: Input: a[] = { -1, -1, -2, 4, 3 }Output: 24Explanation : Maximum product will be ( -2 * -1 * 4 * 3 ) = 24 Input: a[] = { -1, 0 }
    10 min read
    Suffix Product Array
    Given an array nums[] of N integers the task is to generate a suffix product array from the given array. A Suffix Product Array is an array where each element at index i contains the product of all elements to the right of i (including the element at index i). Examples: Input: nums[] = {1, 2, 3, 4,
    4 min read
    Prefix Product Array
    Given an array arr[] of N integers the task is to generate a prefix product array from the given array. In a prefix product array, ith term pref[i] = arr[i] * arr[i - 1] * ...... * arr[0] Examples: Input: {1, 2, 3, 4, 5} Output: {1, 2, 6, 24, 120} Explanation: The Prefix Product Array will be {1, 2*
    4 min read
    Count of sub-arrays with odd product
    Given an integer array arr[] of size N, the task is to count the number of sub-arrays that have an odd product.Examples: Input : arr[] = {5, 1, 2, 3, 4} Output : 4 Explanation: The sub-arrays with odd product are- {5}, {1}, {3}, {5, 1}. Hence the count is 4.Input : arr[] = {12, 15, 7, 3, 25, 6, 2, 1
    7 min read
    Smallest Fibonacci Product from Array elements
    Given an array of integers, find the smallest Fibonacci number that can be formed by selecting any two distinct numbers from the array and multiplying them. If no such number exists, return -1. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: 2Explanation: The possible pairs of distinct numbers from
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences