Tweaked Array

Easy
0/40
Average time to solve is 10m
profile
Contributed by
21 upvotes
Asked in companies
Quantifi AnalyticsNewgen Software

Problem statement

You are given an array ‘ARR’ of size ‘N’ consisting of integers. The array needs to be tweaked a little bit.

Firstly, calculate ‘TotalSum’ = ‘ARR[0]’ + ‘ARR[1]’ + ... + ‘ARR[N - 1]’.

Now, for every ‘i’ (0 <= ‘i’ <= ‘N’ - 1), ‘ARR[i]’ is replaced with ‘ARR[i]’ = ‘TotalSum’ - ‘ARR[i]’.

Output the final array after tweaking it.

Example :
'N' = 3
'ARR' = {2, 4, 1, 1}

TotalSum = 2 + 4 + 1 + 1 = 8

Tweaked Array = {6, 4, 7, 7}.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line contains an integer ‘T’ which denotes the number of test cases to be run. Then the test cases follow.

The first line of each test case contains an integer ‘N’.

The second line contains ‘N’ space-separated integers denoting the elements of array ‘ARR’
Output format :
For each test case, print ‘N’ space-separated integers denoting the elements of the tweaked array.

Print the output of each test case in a new line.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 10^5
-10^5 <= ARR[i] <= 10^5
Sum of ‘N’ over all test cases is <= 10^5.

Time Limit: 1 sec
Sample Input 1 :
2
3
1 4 1
3
5 2 -5
Sample Output 1 :
5 2 5
-3 0 7
Explanation Of Sample Input 1 :
For test 1:
TotalSum = 1 + 4 + 1 = 6
Tweaked array = {6 - 1,  6 - 4,  6 - 1} = {5, 2, 5}

For test 2:
TotalSum = 5 + 2 + (-5) = 2
Tweaked array = {2 - 5,  2 - 2,  2 - (-5)} = {-3, 0, 7}
Sample Input 2 :
2
2
1 2
3
-1 -2 -4
Sample Output 2 :
2 1
-6 -5 - 3
Hint

Simulate the problem statement.

Approaches (1)
Optimal Approach

 

Approach:

 

  • Firstly, find the value of ‘TotalSum’ by calculating the sum of elements from ARR[0] to ARR[N - 1].
  • Then, create a new array with the ith element as ‘TotalSum’ - ARR[i].


 

Algorithm:

 

  • Initialise a variable 'TotalSum' = 0.
  • Loop through the array ‘ARR’ from ‘i’ = 0 to ‘i’ = ‘N’ - 1:
    • ‘TotalSum’ = ‘TotalSum’ + ARR[i]
  • Initialise an array ‘TweakedArr’ = {}
  • Loop through the array ‘ARR’ from ‘i’ = 0 to ‘i’ = ‘N’ - 1:
    • ‘TweakedArr’.append(‘TotalSum’ - ARR[i])
  • return ‘TweakedArr’

 

Time Complexity

O(N), where ‘N’ is the size of the array ‘ARR’.

 

Since we are traversing the array once for calculating the ‘TotalSum’ and once for finding the ‘TweakedArr’. So, the overall Time Complexity is O(N).

Space Complexity

O(1)

 

Constant extra space is required. (We don’t count output array in the space complexity of Algorithm). So, the Space Complexity is O(1).

Code Solution
(100% EXP penalty)
Tweaked Array
Full screen
Console