Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 all non repeating Subarrays of an Array
Next article icon

Product of all Subarrays of an Array | Set 2

Last Updated : 05 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of integers of size N, the task is to find the products of all subarrays of the array.
Examples: 
 

Input: arr[] = {2, 4} 
Output: 64 
Explanation: 
Here, subarrays are {2}, {2, 4}, and {4}. 
Products of each subarray are 2, 8, 4. 
Product of all Subarrays = 64
Input: arr[] = {1, 2, 3} 
Output: 432 
Explanation: 
Here, subarrays are {1}, {1, 2}, {1, 2, 3}, {2}, {2, 3}, {3}. 
Products of each subarray are 1, 2, 6, 2, 6, 3. 
Product of all Subarrays = 432 
 

 

Naive and Iterative approach: Please refer this post for these approaches.
Approach: The idea is to count the number of each element occurs in all the subarrays. To count we have below observations: 
 

  • In every subarray beginning with arr[i], there are (N – i) such subsets starting with the element arr[i]. 
    For Example: 
     

For array arr[] = {1, 2, 3} 
N = 3 and for element 2 i.e., index = 1 
There are (N – index) = 3 – 1 = 2 subsets 
{2} and {2, 3} 
 

  •  
  • For any element arr[i], there are (N – i)*i subarrays where arr[i] is not the first element. 
     

For array arr[] = {1, 2, 3} 
N = 3 and for element 2 i.e., index = 1 
There are (N – index)*index = (3 – 1)*1 = 2 subsets where 2 is not the first element. 
{1, 2} and {1, 2, 3} 
 

  •  

Therefore, from the above observations, the total number of each element arr[i] occurs in all the subarrays at every index i is given by: 
 

total_elements = (N - i) + (N - i)*i total_elements = (N - i)*(i + 1) 

The idea is to multiply each element (N – i)*(i + 1) number of times to get the product of elements in all subarrays.
Below is the implementation of the above approach: 
 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the product of
// elements of all subarray
long int SubArrayProdct(int arr[],
                        int n)
{
    // Initialize the result
    long int result = 1;
 
    // Computing the product of
    // subarray using formula
    for (int i = 0; i < n; i++)
        result *= pow(arr[i],
                      (i + 1) * (n - i));
 
    // Return the product of all
    // elements of each subarray
    return result;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 2, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << SubArrayProdct(arr, N)
         << endl;
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the product of
// elements of all subarray
static int SubArrayProdct(int arr[], int n)
{
     
    // Initialize the result
    int result = 1;
 
    // Computing the product of
    // subarray using formula
    for(int i = 0; i < n; i++)
       result *= Math.pow(arr[i], (i + 1) *
                                  (n - i));
 
    // Return the product of all
    // elements of each subarray
    return result;
}
 
// Driver code
public static void main(String[] args)
{
 
    // Given array arr[]
    int arr[] = new int[]{2, 4};
 
    int N = arr.length;
 
    // Function Call
    System.out.println(SubArrayProdct(arr, N));
}
}
 
// This code is contributed by Pratima Pandey
 
 

Python3




# Python3 program for the above approach
 
# Function to find the product of
# elements of all subarray
def SubArrayProdct(arr, n):
 
    # Initialize the result
    result = 1;
 
    # Computing the product of
    # subarray using formula
    for i in range(0, n):
        result *= pow(arr[i],
                     (i + 1) * (n - i));
 
    # Return the product of all
    # elements of each subarray
    return result;
 
# Driver Code
 
# Given array arr[]
arr = [ 2, 4 ];
N = len(arr);
 
# Function Call
print(SubArrayProdct(arr, N))
 
# This code is contributed by Code_Mech
 
 

C#




// C# program for the above approach
using System;
class GFG{
 
// Function to find the product of
// elements of all subarray
static int SubArrayProdct(int []arr, int n)
{
     
    // Initialize the result
    int result = 1;
 
    // Computing the product of
    // subarray using formula
    for(int i = 0; i < n; i++)
       result *= (int)(Math.Pow(arr[i], (i + 1) *
                                        (n - i)));
 
    // Return the product of all
    // elements of each subarray
    return result;
}
 
// Driver code
public static void Main()
{
 
    // Given array arr[]
    int []arr = new int[]{2, 4};
 
    int N = arr.Length;
 
    // Function Call
    Console.Write(SubArrayProdct(arr, N));
}
}
 
// This code is contributed by Code_Mech
 
 

Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Function to find the product of
// elements of all subarray
function SubArrayProdct(arr, n)
{
       
    // Initialize the result
    let result = 1;
   
    // Computing the product of
    // subarray using formula
    for(let i = 0; i < n; i++)
       result *= Math.pow(arr[i], (i + 1) *
                                  (n - i));
   
    // Return the product of all
    // elements of each subarray
    return result;
}
 
// Driver code
 
     // Given array arr[]
    let arr = [2, 4];
   
    let N = arr.length;
   
    // Function Call
    document.write(SubArrayProdct(arr, N));
  
 // This code is contributed by sanjoy_62.
</script>
 
 
Output: 
64

 

Time Complexity: O(N), where N is the number of elements. 
Auxiliary Space: O(1)
 



Next Article
Product of all non repeating Subarrays of an Array
author
spp____
Improve
Article Tags :
  • Arrays
  • Competitive Programming
  • DSA
  • Mathematical
  • subarray
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Product of all Subarrays of an Array
    Given an array of integers arr of size N, the task is to print products of all subarrays of the array. Examples: Input: arr[] = {2, 4} Output: 64 Here, subarrays are [2], [2, 4], [4] Products are 2, 8, 4 Product of all Subarrays = 64 Input : arr[] = {10, 3, 7} Output : 27783000 Here, subarrays are [
    7 min read
  • Product of all non repeating Subarrays of an Array
    Given an array containing distinct integers arr[] of size N, the task is to print the product of all non-repeating subarrays of the array. Examples: Input: arr[] = {2, 4} Output: 64 Explanation: The possible subarrays for the given array are {2}, {2, 4}, {4} The products are 2, 8, 4 respectively. Th
    5 min read
  • Largest product of a subarray of size k
    Given an array consisting of n positive integers, and an integer k. Find the largest product subarray of size k, i.e., find the maximum produce of k contiguous elements in the array where k <= n.Examples : Input: arr[] = {1, 5, 9, 8, 2, 4, 1, 8, 1, 2} k = 6Output: 4608 The subarray is {9, 8, 2, 4
    13 min read
  • Sum of products of all possible Subarrays
    Given an array arr[] of N positive integers, the task is to find the sum of the product of elements of all the possible subarrays. Examples: Input: arr[] = {1, 2, 3}Output: 20Explanation: Possible Subarrays are: {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}.Products of all the above subarrays are 1, 2, 3
    6 min read
  • Print all subsets of a given Set or Array
    Given an array arr of size n, your task is to print all the subsets of the array in lexicographical order. A subset is any selection of elements from an array, where the order does not matter, and no element appears more than once. It can include any number of elements, from none (the empty subset)
    12 min read
  • 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
  • A product array puzzle | Set 2 (O(1) Space)
    Given an array arr[] of size n, 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]. Note: Solve it without division operator and in O(n). Examples: Input: arr[] = [10, 3, 5, 6, 2]Output: [180, 600, 360, 300, 900]Expl
    13 min read
  • Bitwise OR of Bitwise AND of all subarrays of an array
    Given an array arr[] consisting of N positive integers, the task is to find the Bitwise OR of Bitwise AND of all subarrays of the given arrays. Examples: Input: arr[] = {1, 2, 3}Output: 3Explanation:The following are Bitwise AND of all possible subarrays are: {1}, Bitwise AND is 1.{1, 2}, Bitwise AN
    7 min read
  • Number of subarrays having even product
    Given an array arr[] consisting of N integers, the task is to count the total number of subarrays having even product. Examples : Input: arr[] = { 7, 5, 4, 9 }Output: 6Explanation: There are total 6 subarrays { 4 }{ 5, 4 }{ 7, 5, 4 }{ 7, 5, 4, 9 }{ 5, 4, 9 }{ 4, 9 } Input: arr[] = { 1, 3, 5 }Output:
    9 min read
  • Length of maximum product subarray
    Given an integer array arr[] of size N, the task is to find the maximum length subarray whose products of element is non zero. . Examples: Input: arr[] = [1, 1, 0, 2, 1, 0, 1, 6, 1] Output: 3 Explanation Possible subarray whose product are non zero are [1, 1], [2, 1] and [1, 6, 1] So maximum possibl
    8 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