Skip to main content

Multiply Left and Right Array Sum

Problem​

Pitsy needs help with the given task by her teacher. The task is to divide an array into two sub-array (left and right) containing n/2 elements each and do the sum of the subarrays and then multiply both the subarrays.

Note: If the length of the array is odd then the right half will contain one element more than the left half.

Examples:​

Example 1:

Input : arr[ ] = {1, 2, 3, 4}
Output : 21
Explanation:
Sum up an array from index 0 to 1 = 3
Sum up an array from index 2 to 3 = 7
Their multiplication is 21.

Example 2:

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

Your task:​

This is a function problem. The input is already taken care of by the driver code. You only need to complete the function multiply() that takes an array (arr), sizeOfArray (n), and return the sum of the subarrays and then multiply both the subarrays. The driver code takes care of the printing.

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

Constraints:​

  • 1≤T≤1001 ≤ T ≤ 100
  • 1≤N≤10001 ≤ N ≤ 1000
  • 1≤A[i]≤1001 ≤ A[i] ≤ 100

Solution​

Python​

def multiply (arr, n) : 
sum_left, sum_right=0, 0
for i in range(0, n//2):
sum_left = sum_left+arr[i]
for j in range(n//2, n):
sum_right = sum_right+arr[j]
result = sum_left*sum_right
return result

Java​

public static int multiply (int arr[], int n) {
int sum_left=0, sum_right=0;
for(int i=0; i<n/2; i++) {
sum_left = sum_left+arr[i];
}
for(int j = n/2; j<n; j++) {
sum_right = sum_right+arr[j];
}
int result = sum_left*sum_right;
return result;
}

C++​

int multiply(int arr[], int n) {
int sum_left=0, sum_right=0;
for(int i=0; i<n/2; i++) {
sum_left = sum_left+arr[i];
}
for(int j = n/2; j<n; j++) {
sum_right = sum_right+arr[j];
}
int result = sum_left*sum_right;
return result;
}

C​

int multiply(int arr[], int n) {
int sum_left = 0, sum_right = 0;
int i, j;
for (i = 0; i < n / 2; i++) {
sum_left += arr[i];
}
for (j = n / 2; j < n; j++) {
sum_right += arr[j];
}
int result = sum_left * sum_right;
return result;
}
  • Time Complexity: O(N)O(N)
  • Auxiliary Space: O(1)O(1)