Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Sum of product of all unordered pairs in given range with update queries

  • Last Updated : 13 Sep, 2021

Given an array A[] consisting of N integers and Q queries of the below types, the task is to print the output for all the update queries.

  • (1, L, R): The 1st type of query to find the sum of the product of all unordered pairs from index L to R in the array where 1 <= L <= R <= N.
  • (2, P, X): The 2nd type of query to change the value of the Pth integer of the array to a new value X.

Example:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: A[] = {5 7 2 3 1}, Q = 3, Queries[] = [ [1, 1, 3], [2, 2, 5], [1, 2, 5]] 
 



Output: 
59
41
Explaination: 
Query 1: In the 1st query, the possible pairs in the given range are (5, 7), (5, 2) and (7, 2). So the pairwise product sum will be (5*7) + (5*2) + (7*2) = 35 + 10 + 14 = 59. 
Query 2: In the 2nd query, update the 2nd integer to 5, which makes the array as [5, 5, 2, 3, 1]. 
Query 3: In the 3rd query, the possible pairs in range [2, 5] are (5, 2), (5, 3), (5, 1), (2, 3), (2, 1), and (3, 1). The sum of product of these pairs is 41.

Input: A[] = {7 3 2 1 4 5 8}, Q = 5, Queries[] = [ [1, 1, 6], [2, 2, 4], [1, 2, 5], [2, 3, 8], [1, 4, 7]] 
 

Output: 59 
41 
6

Naive Approach: The simple way to solve this is to for the 1st type of query, generate all unordered pairs in the given range of query and print the sum of product of these pairs. For the 2nd type of queries, update the array element as per the given value.

Below is the implementation of the above approach:

C++




// C++ Program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the Pairwise
// Product Sum in range from L to R
void pairwiseProductSum(int a[], int l, int r)
{
    int sum = 0;
 
    // Loop to iterate over all possible
    // pairs from L to R
    for (int j = l - 1; j <= r - 1; j++) {
        for (int k = j + 1; k <= r - 1; k++) {
            sum += (a[j] * a[k]);
        }
    }
 
    // Print answer
    cout << sum << endl;
}
 
// Function to update the Array
// element at index P to X
void updateArray(int* a, int p, int x)
{
    // Update the value at Pth
    // index in the array
    a[p - 1] = x;
}
 
// Function to solve Q queries
void solveQueries(
    int* a, int n,
    int Q, int query[][3])
{
 
    for (int i = 0; i < Q; i++) {
 
        // If Query is of type 1
        if (query[i][0] == 1)
            pairwiseProductSum(
                a, query[i][1], query[i][2]);
 
        // If Query is of type 2
        else
            updateArray(
                a, query[i][1], query[i][2]);
    }
}
 
// Driver Code
int main()
{
    int A[] = { 5, 7, 2, 3, 1 };
    int N = sizeof(A) / sizeof(int);
    int Q = 3;
    int query[Q][3] = { { 1, 1, 3 },
                        { 2, 2, 5 },
                        { 1, 2, 5 } };
 
    solveQueries(A, N, Q, query);
 
    return 0;
}

Java




// Java Program for the above approach
import java.util.*;
 
class GFG{
 
// Function to calculate the Pairwise
// Product Sum in range from L to R
static void pairwiseProductSum(int a[], int l, int r)
{
    int sum = 0;
 
    // Loop to iterate over all possible
    // pairs from L to R
    for (int j = l - 1; j <= r - 1; j++) {
        for (int k = j + 1; k <= r - 1; k++) {
            sum += (a[j] * a[k]);
        }
    }
 
    // Print answer
    System.out.print(sum +"\n");
}
 
// Function to update the Array
// element at index P to X
static void updateArray(int[] a, int p, int x)
{
    // Update the value at Pth
    // index in the array
    a[p - 1] = x;
}
 
// Function to solve Q queries
static void solveQueries(
    int[] a, int n,
    int Q,
    int query[][])
{
 
    for (int i = 0; i < Q; i++) {
 
        // If Query is of type 1
        if (query[i][0] == 1)
            pairwiseProductSum(
                a, query[i][1], query[i][2]);
 
        // If Query is of type 2
        else
            updateArray(
                a, query[i][1], query[i][2]);
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 5, 7, 2, 3, 1 };
    int N = A.length;
    int Q = 3;
    int query[][] = { { 1, 1, 3 },
                        { 2, 2, 5 },
                        { 1, 2, 5 } };
 
    solveQueries(A, N, Q, query);
 
}
}
 
// This code is contributed by 29AjayKumar

Python3




# Python 3 Program for the above approach
 
# Function to calculate the Pairwise
# Product Sum in range from L to R
def pairwiseProductSum(a, l, r):
    sum = 0
 
    # Loop to iterate over all possible
    # pairs from L to R
    for j in range(l - 1,r,1):
        for k in range(j + 1,r,1):
            sum += (a[j] * a[k]);
 
    # Print answer
    print(sum)
 
# Function to update the Array
# element at index P to X
def updateArray(a, p, x):
    # Update the value at Pth
    # index in the array
    a[p - 1] = x
 
# Function to solve Q queries
def solveQueries(a,n,Q,query):
    for i in range(Q):
        # If Query is of type 1
        if (query[i][0] == 1):
            pairwiseProductSum(a, query[i][1], query[i][2])
 
        # If Query is of type 2
        else:
            updateArray(a, query[i][1], query[i][2])
 
# Driver Code
if __name__ == '__main__':
    A = [5, 7, 2, 3, 1]
    N = len(A)
    Q = 3
    query = [[1, 1, 3],[2, 2, 5],[1, 2, 5]]
 
    solveQueries(A, N, Q, query)
     
    # This code is contributed by ipg2016107

C#




//C# code for the above approach
using System;
 
public class GFG{
// Function to calculate the Pairwise
// Product Sum in range from L to R
static void pairwiseProductSum(int[] a, int l, int r)
{
    int sum = 0;
 
    // Loop to iterate over all possible
    // pairs from L to R
    for (int j = l - 1; j <= r - 1; j++) {
        for (int k = j + 1; k <= r - 1; k++) {
            sum += (a[j] * a[k]);
        }
    }
 
    // Print answer
    Console.Write(sum +"\n");
}
 
// Function to update the Array
// element at index P to X
static void updateArray(int[] a, int p, int x)
{
    // Update the value at Pth
    // index in the array
    a[p - 1] = x;
}
 
// Function to solve Q queries
static void solveQueries(
    int[] a, int n,
    int Q,
    int[][] query)
{
 
    for (int i = 0; i < Q; i++) {
 
        // If Query is of type 1
        if (query[i][0] == 1)
            pairwiseProductSum(
                a, query[i][1], query[i][2]);
 
        // If Query is of type 2
        else
            updateArray(
                a, query[i][1], query[i][2]);
    }
}
 
// Driver Code
    static public void Main (){
 
        // Code
      int[] A = { 5, 7, 2, 3, 1 };
    int N = A.Length;
    int Q = 3;
        int[][] query = {
                            new int[3]{ 1, 1, 3 },
                            new int[3]{ 2, 2, 5 },
                            new int[3] { 1, 2, 5 }
                           };
 
    solveQueries(A, N, Q, query);
    }
}
// This code is contributed by Potta Lokesh

Javascript




<script>
// Javascript Program for the above approach
 
// Function to calculate the Pairwise
// Product Sum in range from L to R
function pairwiseProductSum(a, l, r)
{
  let sum = 0;
 
  // Loop to iterate over all possible
  // pairs from L to R
  for (let j = l - 1; j <= r - 1; j++) {
    for (let k = j + 1; k <= r - 1; k++) {
      sum += a[j] * a[k];
    }
  }
 
  // Print answer
  document.write(sum + "<br>");
}
 
// Function to update the Array
// element at index P to X
function updateArray(a, p, x)
{
 
  // Update the value at Pth
  // index in the array
  a[p - 1] = x;
}
 
// Function to solve Q queries
function solveQueries(a, n, Q, query)
{
  for (let i = 0; i < Q; i++)
  {
   
    // If Query is of type 1
    if (query[i][0] == 1) pairwiseProductSum(a, query[i][1], query[i][2]);
     
    // If Query is of type 2
    else updateArray(a, query[i][1], query[i][2]);
  }
}
 
// Driver Code
let A = [5, 7, 2, 3, 1];
let N = A.length;
let Q = 3;
let query = [
  [1, 1, 3],
  [2, 2, 5],
  [1, 2, 5],
];
 
solveQueries(A, N, Q, query);
 
// This code is contributed by gfgking.
</script>

 
 

Output: 
59
41

 

 



Time Complexity: O(N2) for pairwise product sum query and O(1) for update query.
Space Complexity: O(N)

 

Efficient Approach: The complexity per query can be reduced to O(N) using the prefix sum technique discussed here.

 

Better Approach: A better approach to further reduce the complexity is using Fenwick Tree based on the following observations: 

 

Given that 
(a + b + c)2 = a2 + b2 + c2 + 2*(a*b + b*c + c*a)
Let required Pairwise Product Sum be P
Let E = (a1 + a2 + a3 + a4 … + an)2 
=> E = a12 + a22 + … + an2 + 2*(a1*a2 + a1*a3 + ….) 
=> E = a12 + a22 + … + an2 + 2*(P) 
=> P = ( E – (a12 + a22 + …. + an2) ) / 2
So, P = (E – Q)/2 where Q = (a12 + a22 + …. + an2

 

According to the above observation, we can maintain two Fenwick trees. 

 

  • First Fenwick tree will keep track of the sum of elements in the given range with update queries. This can be used to calculate E for any given range.
  • Similarly, the second Fenwick tree will keep track of the sum of the square of elements in the given range with update queries. This can be used to calculate Q for any given range. Thereafter, P can be easily calculated as P = (E – Q)/2.

 

Below is the implementation of the above approach:

 

C++




// C++ Program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
#define MAXN 100000
 
// Vector to store fenwick tree
// of the 1st type
vector<int> bit1(MAXN, 0);
 
// Vector to store fenwick tree
// of the 2nd type
vector<int> bit2(MAXN, 0);
 
// Function to update the value
// at idx index in fenwick tree
void update(int idx, int val, vector<int>& bit)
{
    while (idx < bit.size()) {
        bit[idx] += val;
        idx += idx & (-idx);
    }
}
 
// Function to return the sum of values
// stored from O to idx index in the
// array using Fenwick Tree
int query(int idx, vector<int>& bit)
{
    int res = 0;
    while (idx > 0) {
        res += bit[idx];
        idx -= idx & (-idx);
    }
    return res;
}
 
// Function to build the Fenwick
// tree from the a[] Array
void buildFenwickTree(int a[], int n)
{
    for (int i = 1; i <= n; i++) {
 
        // Function call to update
        // the ith element in the
        // first Fenwick Tree
        update(i, a[i - 1], bit1);
 
        // Function call to update
        // the ith element in the
        // first Fenwick Tree
        update(i, a[i - 1] * a[i - 1], bit2);
    }
}
 
// Function to find the Pairwise
// Product Sum in the range L to R
void pairwiseProductSum(int a[], int l, int r)
{
    int sum, e, q;
 
    // Function call to calculate E
    // in the given range
    e = query(r, bit1) - query(l - 1, bit1);
    e = e * e;
 
    // Function call to calculate E
    // in the given range
    q = query(r, bit2) - query(l - 1, bit2);
    sum = (e - q) / 2;
 
    // Print Answer
    cout << sum << endl;
}
 
// Function to update the Fenwick
// tree and the array element at
// index P to the new value X
void updateArray(int* a, int p, int x)
{
    // Function call to update the
    // value in 1st Fenwick Tree
    update(p, -a[p - 1], bit1);
    update(p, x, bit1);
 
    // Function call to update the
    // value in 2nd Fenwick Tree
    update(p, -a[p - 1] * a[p - 1], bit2);
    update(p, x * x, bit2);
 
    a[p - 1] = x;
}
 
// Function to solve Q queries
void solveQueries(
    int* a, int n,
    int Q, int query[][3])
{
    // Function Call to build the
    // Fenwick Tree
    buildFenwickTree(a, n);
 
    for (int i = 0; i < Q; i++) {
 
        // If Query is of type 1
        if (query[i][0] == 1)
            pairwiseProductSum(
                a, query[i][1], query[i][2]);
 
        // If Query is of type 2
        else
            updateArray(
                a, query[i][1], query[i][2]);
    }
}
 
// Driver Code
int main()
{
    int A[] = { 5, 7, 2, 3, 1 };
    int N = sizeof(A) / sizeof(int);
    int Q = 3;
    int query[Q][3] = { { 1, 1, 3 },
                        { 2, 2, 5 },
                        { 1, 2, 5 } };
 
    solveQueries(A, N, Q, query);
 
    return 0;
}

Java




// Java Program for the above approach
 
class GFG{
 
static final int MAXN = 100000;
 
// Vector to store fenwick tree
// of the 1st type
static int []bit1 = new int[MAXN];
 
// Vector to store fenwick tree
// of the 2nd type
static int []bit2 = new int[MAXN];
 
// Function to update the value
// at idx index in fenwick tree
static void update(int idx, int val, int []bit)
{
    while (idx < bit.length) {
        bit[idx] += val;
        idx += idx & (-idx);
    }
}
 
// Function to return the sum of values
// stored from O to idx index in the
// array using Fenwick Tree
static int query(int idx, int []bit)
{
    int res = 0;
    while (idx > 0) {
        res += bit[idx];
        idx -= idx & (-idx);
    }
    return res;
}
 
// Function to build the Fenwick
// tree from the a[] Array
static void buildFenwickTree(int a[], int n)
{
    for (int i = 1; i <= n; i++) {
 
        // Function call to update
        // the ith element in the
        // first Fenwick Tree
        update(i, a[i - 1], bit1);
 
        // Function call to update
        // the ith element in the
        // first Fenwick Tree
        update(i, a[i - 1] * a[i - 1], bit2);
    }
}
 
// Function to find the Pairwise
// Product Sum in the range L to R
static void pairwiseProductSum(int a[], int l, int r)
{
    int sum, e, q;
 
    // Function call to calculate E
    // in the given range
    e = query(r, bit1) - query(l - 1, bit1);
    e = e * e;
 
    // Function call to calculate E
    // in the given range
    q = query(r, bit2) - query(l - 1, bit2);
    sum = (e - q) / 2;
 
    // Print Answer
    System.out.print(sum +"\n");
}
 
// Function to update the Fenwick
// tree and the array element at
// index P to the new value X
static void updateArray(int[] a, int p, int x)
{
    // Function call to update the
    // value in 1st Fenwick Tree
    update(p, -a[p - 1], bit1);
    update(p, x, bit1);
 
    // Function call to update the
    // value in 2nd Fenwick Tree
    update(p, -a[p - 1] * a[p - 1], bit2);
    update(p, x * x, bit2);
 
    a[p - 1] = x;
}
 
// Function to solve Q queries
static void solveQueries(
    int[] a, int n,
    int Q, int query[][])
{
    // Function Call to build the
    // Fenwick Tree
    buildFenwickTree(a, n);
 
    for (int i = 0; i < Q; i++) {
 
        // If Query is of type 1
        if (query[i][0] == 1)
            pairwiseProductSum(
                a, query[i][1], query[i][2]);
 
        // If Query is of type 2
        else
            updateArray(
                a, query[i][1], query[i][2]);
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 5, 7, 2, 3, 1 };
    int N = A.length;
    int Q = 3;
    int query[][] = { { 1, 1, 3 },
                        { 2, 2, 5 },
                        { 1, 2, 5 } };
 
    solveQueries(A, N, Q, query);
 
}
}
 
// This code is contributed by Princi Singh

 
 

Output: 
59
41

 

 

Time Complexity: O(N*log N) for the construction of Fenwick tree 
O(log N) for the pairwise product sum query
O(log N) for the update query.
Auxiliary space: O(N)

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :