Given an array arr[] of n integers, construct a Sum Array sum[] (of same size) such that sum[i] is equal to the sum of all the elements of arr[] except arr[i]. Solve it without subtraction operator and in O(n).
Examples:
Input : arr[] = {3, 6, 4, 8, 9}
Output : sum[] = {27, 24, 26, 22, 21}
Input : arr[] = {4, 5, 7, 3, 10, 1}
Output : sum[] = {26, 25, 23, 27, 20, 29}
Brute Force Approach:
The brute force approach to solve this problem is to iterate through the array for each element, calculate the sum of all other elements, and store it in the sum array. This can be done using two nested loops where the outer loop iterates through all the elements, and the inner loop calculates the sum of all other elements.
- Create an empty sum array of size n to store the sum of all elements except the current element.
- Iterate through the array for each element using a for loop.
- Initialize the sum of the current element as 0.
- For each element, iterate through the array using another for loop.
- If the current index of the inner loop is not equal to the index of the outer loop, add the value of the element at the current index to the sum of the current element.
- Store the sum of all other elements in the sum array at the index of the current element.
- Iterate through the sum array and print its elements.
Below is the implementation of the above approach:
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
void sumArray(int arr[], int n)
{
int sum[n];
for(int i=0; i<n; i++){
sum[i] = 0;
for(int j=0; j<n; j++){
if(j!=i)
sum[i] += arr[j];
}
}
for(int i=0; i<n; i++)
cout<<sum[i]<<" ";
}
/* Driver program to test above functions */
int main()
{
int arr[] = { 3, 6, 4, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
sumArray(arr, n);
return 0;
}
Java
import java.util.Arrays;
public class Main {
// Function to calculate the sum of elements in the array except the current element
static void sumArray(int[] arr, int n) {
int[] sum = new int[n];
// Calculate the sum of elements excluding the current element
for (int i = 0; i < n; i++) {
sum[i] = 0;
for (int j = 0; j < n; j++) {
if (j != i) {
sum[i] += arr[j];
}
}
}
// Print the calculated sums
for (int i = 0; i < n; i++) {
System.out.print(sum[i] + " ");
}
}
public static void main(String[] args) {
int[] arr = {3, 6, 4, 8, 9};
int n = arr.length;
sumArray(arr, n);
}
}
Python3
# Function to calculate the sum of elements in the list except the current element
def sumArray(arr):
n = len(arr)
sum_result = [0] * n
# Calculate the sum of elements excluding the current element
for i in range(n):
sum_result[i] = 0
for j in range(n):
if j != i:
sum_result[i] += arr[j]
# Print the sum of elements for each position
for i in range(n):
print(sum_result[i])
# Driver program to test the sumArray function
arr = [3, 6, 4, 8, 9]
sumArray(arr)
C#
using System;
class Program
{
// Function to calculate the sum of elements except the current element
static void SumArray(int[] arr, int n)
{
int[] sum = new int[n];
for (int i = 0; i < n; i++)
{
sum[i] = 0;
for (int j = 0; j < n; j++)
{
if (j != i)
sum[i] += arr[j];
}
}
for (int i = 0; i < n; i++)
Console.Write(sum[i] + " ");
}
// Main driver program
static void Main()
{
int[] arr = { 3, 6, 4, 8, 9 };
int n = arr.Length;
SumArray(arr, n);
// Output: 27 24 26 22 21
}
}
JavaScript
// Function to calculate the sum of elements in the array except the current element
function sumArray(arr) {
const n = arr.length;
const sum = new Array(n);
// Calculate the sum of elements excluding the current element
for (let i = 0; i < n; i++) {
sum[i] = 0;
for (let j = 0; j < n; j++) {
if (j !== i) {
sum[i] += arr[j];
}
}
}
// Print the sum of elements for each position
for (let i = 0; i < n; i++) {
console.log(sum[i]);
}
}
// Driver program to test the sumArray function
const arr = [3, 6, 4, 8, 9];
sumArray(arr);
Time Complexity: O(n^2), as we are using nested loops to iterate through the array.
Space Complexity: O(n) because we are creating an additional array of the same size as the input array to store the sum of all elements except the current element.
Algorithm:
- Construct a temporary array leftSum[] such that leftSum[i] contains sum of all elements on left of arr[i] excluding arr[i].
- Construct another temporary array rightSum[] such that rightSum[i] contains sum of all elements on right of arr[i] excluding arr[i].
- To get sum[], sum left[] and right[].
Implementation:
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
void sumArray(int arr[], int n)
{
/* Allocate memory for temporary arrays leftSum[],
rightSum[] and Sum[]*/
int leftSum[n], rightSum[n], Sum[n], i, j;
/* Left most element of left array is always 0 */
leftSum[0] = 0;
/* Rightmost most element of right
array is always 0 */
rightSum[n - 1] = 0;
/* Construct the left array*/
for (i = 1; i < n; i++)
leftSum[i] = arr[i - 1] + leftSum[i - 1];
/* Construct the right array*/
for (j = n - 2; j >= 0; j--)
rightSum[j] = arr[j + 1] + rightSum[j + 1];
/* Construct the sum array using
left[] and right[] */
for (i = 0; i < n; i++)
Sum[i] = leftSum[i] + rightSum[i];
/* print the constructed prod array */
for (i = 0; i < n; i++)
cout << Sum[i] << " ";
}
/* Driver program to test above functions */
int main()
{
int arr[] = { 3, 6, 4, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
sumArray(arr, n);
return 0;
}
Java
// Java implementation of above approach
import java.util.*;
import java.lang.*;
import java.io.*;
class Geeks {
public static void sumArray(int arr[], int n)
{
/* Allocate memory for temporary arrays
leftSum[], rightSum[] and Sum[]*/
int leftSum[] = new int[n];
int rightSum[] = new int[n];
int Sum[] = new int[n];
int i = 0, j = 0;
/* Left most element of left array is
always 0 */
leftSum[0] = 0;
/* Right most element of right array
is always 0 */
rightSum[n - 1] = 0;
/* Construct the left array*/
for (i = 1; i < n; i++)
leftSum[i] = arr[i - 1] + leftSum[i - 1];
/* Construct the right array*/
for (j = n - 2; j >= 0; j--)
rightSum[j] = arr[j + 1] + rightSum[j + 1];
/* Construct the sum array using
left[] and right[] */
for (i = 0; i < n; i++)
Sum[i] = leftSum[i] + rightSum[i];
/*print the sum array*/
for (i = 0; i < n; i++)
System.out.print(Sum[i] + " ");
}
/* Driver function to test above function*/
public static void main(String[] args)
{
int arr[] = { 3, 6, 4, 8, 9 };
int n = arr.length;
sumArray(arr, n);
}
}
Python3
# Python3 implementation of above approach
def sumArray(arr, n):
# Allocate memory for temporary arrays
# leftSum[], rightSum[] and Sum[]
leftSum = [0 for i in range(n)]
rightSum = [0 for i in range(n)]
Sum = [0 for i in range(n)]
i, j = 0, 0
# Left most element of left
# array is always 0
leftSum[0] = 0
# Rightmost most element of right
# array is always 0
rightSum[n - 1] = 0
# Construct the left array
for i in range(1, n):
leftSum[i] = arr[i - 1] + leftSum[i - 1]
# Construct the right array
for j in range(n - 2, -1, -1):
rightSum[j] = arr[j + 1] + rightSum[j + 1]
# Construct the sum array using
# left[] and right[]
for i in range(0, n):
Sum[i] = leftSum[i] + rightSum[i]
# print the constructed prod array
for i in range(n):
print(Sum[i], end = " ")
# Driver Code
arr = [3, 6, 4, 8, 9]
n = len(arr)
sumArray(arr, n)
# This code is contributed by
# mohit kumar 29
C#
// C# implementation of above approach
using System ;
class Geeks {
public static void sumArray(int []arr, int n)
{
/* Allocate memory for temporary arrays
leftSum[], rightSum[] and Sum[]*/
int []leftSum = new int[n];
int []rightSum = new int[n];
int []Sum = new int[n];
int i = 0, j = 0;
/* Left most element of left array is
always 0 */
leftSum[0] = 0;
/* Right most element of right array
is always 0 */
rightSum[n - 1] = 0;
/* Construct the left array*/
for (i = 1; i < n; i++)
leftSum[i] = arr[i - 1] + leftSum[i - 1];
/* Construct the right array*/
for (j = n - 2; j >= 0; j--)
rightSum[j] = arr[j + 1] + rightSum[j + 1];
/* Construct the sum array using
left[] and right[] */
for (i = 0; i < n; i++)
Sum[i] = leftSum[i] + rightSum[i];
/*print the sum array*/
for (i = 0; i < n; i++)
Console.Write(Sum[i] + " ");
}
/* Driver function to test above function*/
public static void Main()
{
int []arr = { 3, 6, 4, 8, 9 };
int n = arr.Length;
sumArray(arr, n);
}
// This code is contributed by Ryuga
}
JavaScript
<script>
// JavaScript implementation of above approach
function sumArray(arr, n)
{
/* Allocate memory for temporary arrays
leftSum[], rightSum[] and Sum[]*/
let leftSum = new Array(n);
let rightSum = new Array(n);
let Sum = new Array(n);
let i = 0, j = 0;
/* Left most element of left array is
always 0 */
leftSum[0] = 0;
/* Right most element of right array
is always 0 */
rightSum[n - 1] = 0;
/* Construct the left array*/
for (i = 1; i < n; i++)
leftSum[i] = arr[i - 1] + leftSum[i - 1];
/* Construct the right array*/
for (j = n - 2; j >= 0; j--)
rightSum[j] = arr[j + 1] + rightSum[j + 1];
/* Construct the sum array using
left[] and right[] */
for (i = 0; i < n; i++)
Sum[i] = leftSum[i] + rightSum[i];
/*print the sum array*/
for (i = 0; i < n; i++)
document.write(Sum[i] + " ");
}
let arr = [ 3, 6, 4, 8, 9 ];
let n = arr.length;
sumArray(arr, n);
</script>
PHP
<?php
// PHP implementation of above approach
function sumArray($arr, $n)
{
/* Allocate memory for temporary
arrays leftSum[], rightSum[] and Sum[]*/
$leftSum = array_fill(0, $n, 0);
$rightSum = array_fill(0, $n, 0);
$Sum = array_fill(0, $n, 0);
/* Left most element of left
array is always 0 */
$leftSum[0] = 0;
/* Rightmost most element of right
array is always 0 */
$rightSum[$n - 1] = 0;
/* Construct the left array*/
for ($i = 1; $i < $n; $i++)
$leftSum[$i] = $arr[$i - 1] +
$leftSum[$i - 1];
/* Construct the right array*/
for ($j = $n - 2; $j >= 0; $j--)
$rightSum[$j] = $arr[$j + 1] +
$rightSum[$j + 1];
/* Construct the sum array using
left[] and right[] */
for ($i = 0; $i < $n; $i++)
$Sum[$i] = $leftSum[$i] + $rightSum[$i];
/* print the constructed prod array */
for ($i = 0; $i < $n; $i++)
echo $Sum[$i]." ";
}
// Driver Code
$arr = array( 3, 6, 4, 8, 9 );
$n = count($arr);
sumArray($arr, $n);
// This code is contributed
// by chandan_jnu
?>
Complexity Analysis:
- Time Complexity: O(n)
- Space Complexity: O(n)
The above method can be optimized to work in O(1) auxiliary space.
Implementation:
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
void sumArray(int arr[], int n)
{
int i, temp = 0;
/* Allocate memory for the sum array */
int Sum[n];
/* Initialize the sum array as 0 */
memset(Sum, 0, n);
/* In this loop, temp variable contains
sum of elements on left side excluding
arr[i] */
for (i = 0; i < n; i++) {
Sum[i] = temp;
temp += arr[i];
}
/* Initialize temp to 0 for sum on right
side */
temp = 0;
/* In this loop, temp variable contains
sum of elements on right side excluding
arr[i] */
for (i = n - 1; i >= 0; i--) {
Sum[i] += temp;
temp += arr[i];
}
for (i = 0; i < n; i++)
cout << Sum[i] << " ";
}
/* Driver program to test above function */
int main()
{
int arr[] = { 3, 6, 4, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
sumArray(arr, n);
return 0;
}
Java
// Java implementation of above approach
import java.util.*;
import java.lang.*;
import java.io.*;
class Geeks {
public static void sumArray(int arr[], int n)
{
int i = 0, temp = 0;
int Sum[] = new int[n];
Arrays.fill(Sum, 0);
/* In this loop, temp variable contains
sum of elements on left side excluding
arr[i] */
for (i = 0; i < n; i++) {
Sum[i] = temp;
temp += arr[i];
}
/* Initialize temp to 0 for sum on right side */
temp = 0;
/* In this loop, temp variable contains
sum of elements on right side excluding
arr[i] */
for (i = n - 1; i >= 0; i--) {
Sum[i] += temp;
temp += arr[i];
}
for (i = 0; i < n; i++)
System.out.print(Sum[i] + " ");
}
/* Driver function to test above function*/
public static void main(String[] args)
{
int arr[] = { 3, 6, 4, 8, 9 };
int n = arr.length;
sumArray(arr, n);
}
}
Python3
# Python3 implementation of above approach
def sumArray(arr, n):
i, temp = 0, 0
# Allocate memory for the sum array */
Sum = [0 for i in range(n)]
'''In this loop, temp variable contains
sum of elements on left side excluding
arr[i] '''
for i in range(n):
Sum[i] = temp
temp += arr[i]
# Initialize temp to 0 for sum
# on right side */
temp = 0
''' In this loop, temp variable contains
sum of elements on right side excluding
arr[i] */'''
for i in range(n - 1, -1, -1):
Sum[i] += temp
temp += arr[i]
for i in range(n):
print(Sum[i], end = " ")
# Driver Code
arr = [ 3, 6, 4, 8, 9 ]
n = len(arr)
sumArray(arr, n)
# This code is contributed by
# Mohit Kumar 29
C#
// C# implementation of above approach
using System;
class Geeks {
public static void sumArray(int []arr, int n)
{
int i = 0, temp = 0;
int []Sum = new int[n];
for( i=0;i<n;i++)
Sum[i] = 0;
/* In this loop, temp variable contains
sum of elements on left side excluding
arr[i] */
for (i = 0; i < n; i++) {
Sum[i] = temp;
temp += arr[i];
}
/* Initialize temp to 0 for sum on right side */
temp = 0;
/* In this loop, temp variable contains
sum of elements on right side excluding
arr[i] */
for (i = n - 1; i >= 0; i--) {
Sum[i] += temp;
temp += arr[i];
}
for (i = 0; i < n; i++)
Console.Write(Sum[i] + " ");
}
/* Driver function to test above function*/
public static void Main()
{
int []arr = { 3, 6, 4, 8, 9 };
int n = arr.Length;
sumArray(arr, n);
}
}
// This code is contributed by inder_verma..
JavaScript
<script>
// Javascript implementation of above approach
function sumArray(arr, n)
{
let i = 0, temp = 0;
let Sum = new Array(n);
for( i=0;i<n;i++)
Sum[i] = 0;
/* In this loop, temp variable contains
sum of elements on left side excluding
arr[i] */
for (i = 0; i < n; i++) {
Sum[i] = temp;
temp += arr[i];
}
/* Initialize temp to 0 for sum on right side */
temp = 0;
/* In this loop, temp variable contains
sum of elements on right side excluding
arr[i] */
for (i = n - 1; i >= 0; i--) {
Sum[i] += temp;
temp += arr[i];
}
for (i = 0; i < n; i++)
document.write(Sum[i] + " ");
}
let arr = [ 3, 6, 4, 8, 9 ];
let n = arr.length;
sumArray(arr, n);
// This code is contributed by decode2207.
</script>
PHP
<?php
// PHP implementation of above approach
function sumArray($arr, $n)
{
$temp = 0;
/* Allocate memory for the sum array */
/* Initialize the sum array as 0 */
$Sum = array_fill(0, $n, 0);
/* In this loop, temp variable contains
sum of elements on left side excluding
arr[i] */
for ($i = 0; $i < $n; $i++)
{
$Sum[$i] = $temp;
$temp += $arr[$i];
}
/* Initialize temp to 0 for sum
on right side */
$temp = 0;
/* In this loop, temp variable contains
sum of elements on right side excluding
arr[i] */
for ($i = $n - 1; $i >= 0; $i--)
{
$Sum[$i] += $temp;
$temp += $arr[$i];
}
for ($i = 0; $i < $n; $i++)
echo $Sum[$i] . " ";
}
// Driver Code
$arr = array( 3, 6, 4, 8, 9 );
$n = count($arr);
sumArray($arr, $n);
// This code is contributed by
// chandan_jnu
?>
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read