Replace every element of the array by sum of all other elements
Last Updated :
19 Jul, 2022
Given an array of size N, the task is to find the encrypted array. The encrypted array is obtained by replacing each element of the original array with the sum of the remaining array elements i.e.
For every i,
arr[i] = sumOfArrayElements – arr[i]
Examples:
Input: arr[] = {5, 1, 3, 2, 4}
Output: 10 14 12 13 11
Original array {5, 1, 3, 2, 4}
Encrypted array is obtained as:
= {1+3+2+4, 5+3+2+4, 5+1+2+4, 5+1+3+4, 5+1+3+2}
= {10, 14, 12, 13, 11}
Each element of original array is replaced by the
sum of the remaining array elements.
Input: arr[] = {6, 8, 32, 12, 14, 10, 25 }
Output: 101 99 75 95 93 97 82
This problem is similar to Find original array from encrypted array (An array of sums of other elements).
Approach:
- Find the sum of all elements of the array.
- Traverse the array and replace arr[i] with the sum-arr[i].
C++
#include <bits/stdc++.h>
using namespace std;
void findEncryptedArray( int arr[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
for ( int i = 0; i < n; i++)
cout << (sum - arr[i]) << " " ;
}
int main()
{
int arr[] = { 5, 1, 3, 2, 4 };
int N = sizeof (arr) / sizeof (arr[0]);
findEncryptedArray(arr, N);
return 0;
}
|
Java
class GFG {
static void findEncryptedArray( int arr[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += arr[i];
for ( int i = 0 ; i < n; i++)
System.out.print(sum - arr[i] + " " );
}
public static void main(String[] args)
{
int arr[] = { 5 , 1 , 3 , 2 , 4 };
int N = arr.length;
findEncryptedArray(arr, N);
}
}
|
Python 3
def findEncryptedArray(arr, n) :
sum = 0
for i in range (n) :
sum + = arr[i]
for i in range (n) :
print ( sum - arr[i], end = " " )
if __name__ = = "__main__" :
arr = [ 5 , 1 , 3 , 2 , 4 ]
N = len (arr)
findEncryptedArray(arr, N)
|
C#
using System;
class GFG
{
static void findEncryptedArray( int []arr,
int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
for ( int i = 0; i < n; i++)
Console.Write(sum - arr[i] + " " );
}
public static void Main()
{
int []arr = { 5, 1, 3, 2, 4 };
int N = arr.Length;
findEncryptedArray(arr, N);
}
}
|
PHP
<?php
function findEncryptedArray(& $arr , $n )
{
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
$sum += $arr [ $i ];
for ( $i = 0; $i < $n ; $i ++)
echo ( $sum - $arr [ $i ]) . " " ;
}
$arr = array (5, 1, 3, 2, 4 );
$N = sizeof( $arr );
findEncryptedArray( $arr , $N );
?>
|
Javascript
<script>
function findEncryptedArray(arr,n)
{
let sum = 0;
for (let i = 0; i < n; i++)
sum += arr[i];
for (let i = 0; i < n; i++)
document.write(sum - arr[i] + " " );
}
let arr=[5, 1, 3, 2, 4 ];
let N = arr.length;
findEncryptedArray(arr, N);
</script>
|
Time complexity: O(n)
Auxiliary Space: O(1) since constant variables are used
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...