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:
Sum of Bitwise OR of all pairs in a given array
Next article icon

Sum of product of all pairs of a Binary Array

Last Updated : 01 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary array arr[] of size N, the task is to print the sum of product of all pairs of the given array elements.

Note: The binary array contains only 0 and 1.

Examples:

Input: arr[] = {0, 1, 1, 0, 1}
Output: 3
Explanation: Sum of product of all possible pairs are: {0 × 1 + 0 × 1 + 0 × 0 + 0 × 1 + 1 × 1 + 1 × 0 + 1 × 1 + 1 × 0 + 1 × 1 + 0 × 1}.
Therefore, the required output is 3.

Input: arr[] = {1, 1, 1, 1}
Output: 6

Naive Approach: The simplest approach to solve the problem is to use generate all possible pairs from the array and calculate the sum of their product. 

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, consider only those pairs in which both the elements are 1. Following are the observations:

If there is a pair (arr[i], arr[j]) where arr[i] × arr[j] = 1, then arr[i] and arr[j] must be 1.

Total number of pairs that satisfy (arr[i] × arr[j] = 1) are: 
=> 

\binom{cntOne}{2}      
 


=> cntOne × (cntOne - 1) / 2 
where, cntOne is the count of 1s in the given array


 

Follow the steps below to solve the problem: 

  • Initialize the variable cntOne to store the count of 1s from the given array.
  • Finally, return the value of cntOne * (cntOne - 1) / 2.

Below is the implementation of the above approach:

C++
// C++ program to implement  // the above approach  #include <bits/stdc++.h>  using namespace std;  // Function to print the sum of product // of all pairs of the given array int productSum(int arr[], int N) {          // Stores count of one in     // the given array     int cntOne = 0;       for(int i = 0; i < N; i++)     {                  // If current element is 1         if (arr[i] == 1)               // Increase count             cntOne++;     }       // Return the sum of product     // of all pairs     return cntOne * (cntOne - 1) / 2; }   // Driver Code int main() {     int arr[] = { 0, 1, 1, 0, 1 };          // Stores the size of     // the given array     int n = sizeof(arr) / sizeof(arr[0]);          cout << productSum(arr, n) << endl; }  // This code is contributed by code_hunt 
Java
// Java program to implement // the above approach import java.util.*;  class GFG {      // Function to print the sum of product     // of all pairs of the given array     static int productSum(int[] arr)     {          // Stores count of one in         // the given array         int cntOne = 0;          // Stores the size of         // the given array         int N = arr.length;          for (int i = 0; i < N; i++) {              // If current element is 1             if (arr[i] == 1)                  // Increase count                 cntOne++;         }          // Return the sum of product         // of all pairs         return cntOne * (cntOne - 1) / 2;     }      // Driver Code     public static void main(String[] args)     {          int[] arr = { 0, 1, 1, 0, 1 };          System.out.println(productSum(arr));     } } 
Python3
# Python3 program to implement  # the above approach   # Function to print the sum of product # of all pairs of the given array def productSum(arr):       # Stores count of one in     # the given array     cntOne = 0          # Stores the size of     # the given array     N = len(arr)       for i in range(N):           # If current element is 1         if (arr[i] == 1):               # Increase count             cntOne += 1          # Return the sum of product     # of all pairs     return cntOne * (cntOne - 1) // 2  # Driver Code arr = [ 0, 1, 1, 0, 1 ]  print(productSum(arr))  # This code is contributed by code_hunt 
C#
// C# program to implement  // the above approach  using System;  class GFG{   // Function to print the sum of product // of all pairs of the given array static int productSum(int[] arr) {          // Stores count of one in     // the given array     int cntOne = 0;      // Stores the size of     // the given array     int N = arr.Length;      for(int i = 0; i < N; i++)     {                  // If current element is 1         if (arr[i] == 1)              // Increase count             cntOne++;     }      // Return the sum of product     // of all pairs     return cntOne * (cntOne - 1) / 2; }  // Driver Code public static void Main() {     int[] arr = { 0, 1, 1, 0, 1 };      Console.Write(productSum(arr)); } }  // This code is contributed by code_hunt 
JavaScript
<script>  // Javascript program to implement // the above approach  // Function to print the sum of product // of all pairs of the given array function productSum(arr, N) {          // Stores count of one in     // the given array     let cntOne = 0;      for(let i = 0; i < N; i++)     {                  // If current element is 1         if (arr[i] == 1)              // Increase count             cntOne++;     }      // Return the sum of product     // of all pairs     return cntOne * (cntOne - 1) / 2; }  // Driver Code      let arr = [ 0, 1, 1, 0, 1 ];          // Stores the size of     // the given array     let n = arr.length;          document.write(productSum(arr, n) + "<br>");   // This code is contributed by Mayank Tyagi  </script> 

Output: 
3

 

Time Complexity: O(N) 
Auxiliary Space: O(1)


Next Article
Sum of Bitwise OR of all pairs in a given array
author
offbeat
Improve
Article Tags :
  • Searching
  • Mathematical
  • School Programming
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Mathematical
  • Searching

Similar Reads

  • Sum of product of all pairs of array elements
    Given an array A[] of integers find sum of product of all pairs of array elements i. e., we need to find of product after execution of following pseudo code product = 0 for i = 1:n for j = i+1:n product = product + A[i]*A[j] Examples: Input : A[] = {1, 3, 4} Output : 19 Possible Pairs : (1,3), (1,4)
    12 min read
  • Sum of all ordered pair-products from a given array
    Given an array arr[] of size N, the task is to find the sum of all products of ordered pairs that can be generated from the given array elements.Examples: Input: arr[] ={1, 2, 3}Output: 36Explanation:All possible pairs are {(1, 1), {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}. The
    4 min read
  • Sum of Bitwise OR of all pairs in a given array
    Given an array "arr[0..n-1]" of integers. The task is to calculate the sum of Bitwise OR of all pairs, i.e. calculate the sum of "arr[i] | arr[j]" for all the pairs in the given array where i < j. Here '|' is a bitwise OR operator. The expected time complexity is O(n). Examples: Input: arr[] = {5
    13 min read
  • Sum of XOR of all pairs in an array
    Given an array of n integers, find the sum of xor of all pairs of numbers in the array. Examples : Input : arr[] = {7, 3, 5}Output : 127 ^ 3 = 43 ^ 5 = 67 ^ 5 = 2Sum = 4 + 6 + 2 = 12Input : arr[] = {5, 9, 7, 6}Output : 475 ^ 9 = 129 ^ 7 = 147 ^ 6 = 15 ^ 7 = 25 ^ 6 = 39 ^ 6 = 15Sum = 12 + 14 + 1 + 2
    11 min read
  • Sum of Bitwise And of all pairs in a given array
    Given an array "arr[0..n-1]" of integers, calculate sum of "arr[i] & arr[j]" for all the pairs in the given where i < j. Here & is bitwise AND operator. Expected time complexity is O(n). Examples : Input: arr[] = {5, 10, 15} Output: 15 Required Value = (5 & 10) + (5 & 15) + (10
    13 min read
  • XOR of Sum of every possible pair of an array
    Given an array A of size n. the task is to generate a new sequence B with size N^2 having elements sum of every pair of array A and find the xor value of the sum of all the pairs formed. Note: Here (A[i], A[i]), (A[i], A[j]), (A[j], A[i]) all are considered as different pairs. Examples: Input: arr[]
    5 min read
  • Product of all the pairs from the given array
    Given an array arr[] of N integers, the task is to find the product of all the pairs possible from the given array such as: (arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs. Print the resultant answer modulus 10^9+7. Exam
    11 min read
  • Sum of the Product of digits of all Array elements
    Given an array arr, the task is to find the sum of the product of digits of all array elements Example: Input: arr[]={11, 23, 41}Output: 11Explanation: 1*1 + 2*3 + 4*1 = 1 + 6 + 4 = 1111 Input: arr[]={46, 32, 78, 0}Output: 86 Approach: To solve this problem, find the product of digits of all numbers
    4 min read
  • Mean of array generated by products of all pairs of the given array
    Given an array arr[] consisting of N integers, the task is to find the mean of the array formed by the products of unordered pairs of the given array. Examples: Input: arr[] = {2, 5, 7}Output: 19.67Explanation:Product of unordered pairs of array arr[] are 2 * 5 = 10, 2 * 7 = 14 and 5 * 7 = 35.Theref
    12 min read
  • Count of binary arrays of size N with sum of product of adjacent pairs equal to K
    Given two integers N and K, the task is to find the total number of possible binary array of size N such that the sum of the product of adjacent pairs in that array is exactly equal to K. Examples: Input: N = 5, K = 3Output: 2Explanation: Two combinations of array A of size N, whose sum of product o
    15+ 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