Find the sum of all values lesser than the element of the Array
Last Updated :
09 Oct, 2023
Given an array arr[] of n integers. For each index i, you have to find the sum of all integers present in the array with a value less than arr[i].
Examples:
Input: n = 3, arr[ ] = {1, 2, 3}
Output: 0 1 3
Explanation:
- For 1, there are no elements lesser than itself.
- For 2, only 1 is lesser than 2.
- And for 3, 1 and 2 are lesser than 3, so the sum is 3.
Input: n = 2, arr[] = {4, 4}
Output: 0 0
Explanation:
- For 4, there are no elements lesser than itself.
- For 4, there are no elements lesser than itself.
- There are no smaller elements than 4.
Approach 1: Bruteforce Approach
To solve the problem follow the below idea:
Use the first loop for traversing over array element and another loop is for calculating the sum of smaller elements.
- The first loop is for traversing the array elements.
- Store the sum of the smaller element by iterating again in the array using another loop.
- While iterating keep on adding the smaller elements in the sum variable.
- Print the updated array res.
Below are the steps for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void SmallerSum( int n, vector< int >& arr)
{
vector< int > res(n);
for ( int i = 0; i < n; i++) {
int sum = 0;
for ( int j = 0; j < n; j++) {
if (arr[j] < arr[i])
sum += arr[j];
}
res[i] = sum;
}
for ( int i = 0; i < n; i++)
cout << res[i] << " " ;
}
int main()
{
int n = 3;
vector< int > arr = { 1, 2, 3 };
SmallerSum(n, arr);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void SmallerSum( int n, List<Integer> arr)
{
List<Integer> res = new ArrayList<Integer>(n);
for ( int i = 0 ; i < n; i++) {
int sum = 0 ;
for ( int j = 0 ; j < n; j++) {
if (arr.get(j) < arr.get(i))
sum += arr.get(j);
}
res.add(sum);
}
for ( int i = 0 ; i < n; i++)
System.out.print(res.get(i) + " " );
}
public static void main(String[] args)
{
int n = 3 ;
List<Integer> arr = new ArrayList<Integer>(
Arrays.asList( 1 , 2 , 3 ));
SmallerSum(n, arr);
}
}
|
Python3
def SmallerSum(n, arr):
res = []
for i in range (n):
sum = 0
for j in range (n):
if arr[j] < arr[i]:
sum + = arr[j]
res.append( sum )
for i in range (n):
print (res[i], end = " " )
if __name__ = = "__main__" :
n = 3
arr = [ 1 , 2 , 3 ]
SmallerSum(n, arr)
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static void SmallerSum( int n, List< int > arr)
{
List< int > res = new List< int >();
for ( int i = 0; i < n; i++) {
int sum = 0;
for ( int j = 0; j < n; j++) {
if (arr[j] < arr[i])
sum += arr[j];
}
res.Add(sum);
}
for ( int i = 0; i < n; i++)
Console.Write(res[i] + " " );
}
public static void Main()
{
int n = 3;
List< int > arr = new List< int >() {1, 2, 3};
SmallerSum(n, arr);
}
}
|
Javascript
function calculateSmallerSum(n, arr) {
let res = new Array(n);
for (let i = 0; i < n; i++) {
let sum = 0;
for (let j = 0; j < n; j++) {
if (arr[j] < arr[i]) {
sum += arr[j];
}
}
res[i] = sum;
}
for (let i = 0; i < n; i++) {
process.stdout.write(res[i] + " " );
}
console.log();
}
function main() {
let n = 3;
let arr = [1, 2, 3];
calculateSmallerSum(n, arr);
}
main();
|
Time complexity: O(N^2)
Auxiliary Space: O(1)
Approach 2: This can be solved with the following idea:
Using HashMap it can be solved, where for each index find the index of element and check the sum of elements lesser than it.
Below is the implementation of the code:
- Take the input as size “n” and array “arr” and call the SmallerSum() function.
- The function creates an empty unordered_map “mp” that will be used to store the sum of all the elements smaller than a given element in the input vector.
- Creates a copy of the vector “arr” to “vec” and sorts “arr” in ascending order.
- Calculates the cumulative sum of all elements in the sorted vector “arr” and stores the sum in an unordered_map only if the current element is different from the previous element, ensuring that the sum is only calculated once for each unique element in the input vector.
- Loops over the original input vector “vec” and prints out the corresponding sum from the unordered_map for each element.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void SmallerSum( int n, vector< int >& arr)
{
unordered_map< int , long long int > mp;
vector< int > vec;
vec = arr;
sort(arr.begin(), arr.end());
long long int sum = 0;
int pre = 0;
for ( int i = 0; i < n; i++) {
if (pre != arr[i])
mp[arr[i]] = sum;
sum += arr[i];
pre = arr[i];
}
for ( int i = 0; i < n; i++) {
cout << mp[vec[i]] << " " ;
}
cout << endl;
}
int main()
{
int n = 3;
vector< int > arr = { 1, 2, 3 };
SmallerSum(n, arr);
n = 20;
arr = { 0, 7, 7, 9, 0, 0, 5, 1, 0, 6,
6, 5, 8, 9, 9, 9, 1, 2, 4, 3 };
SmallerSum(n, arr);
return 0;
}
|
Java
import java.util.*;
public class SmallerSum {
static void calculateSmallerSum( int n, List<Integer> arr) {
Map<Integer, Long> mp = new HashMap<>();
for ( int element : arr) {
mp.put(element, 0L);
}
List<Integer> vec = new ArrayList<>(arr);
Collections.sort(arr);
long sum = 0 ;
int pre = 0 ;
for ( int i = 0 ; i < n; i++) {
if (pre != arr.get(i)) {
mp.put(arr.get(i), sum);
}
sum += arr.get(i);
pre = arr.get(i);
}
for ( int i = 0 ; i < n; i++) {
System.out.print(mp.get(vec.get(i)) + " " );
}
System.out.println();
}
public static void main(String[] args) {
int n = 3 ;
List<Integer> arr = new ArrayList<>(Arrays.asList( 1 , 2 , 3 ));
calculateSmallerSum(n, arr);
n = 20 ;
arr = new ArrayList<>(Arrays.asList( 0 , 7 , 7 , 9 , 0 , 0 , 5 , 1 , 0 , 6 ,
6 , 5 , 8 , 9 , 9 , 9 , 1 , 2 , 4 , 3 ));
calculateSmallerSum(n, arr);
}
}
|
Python3
def smaller_sum(n, arr):
mp = {}
vec = list (arr)
arr.sort()
sum = 0
pre = None
for i in range (n):
if pre ! = arr[i]:
mp[arr[i]] = sum
sum + = arr[i]
pre = arr[i]
for i in range (n):
print (mp[vec[i]], end = " " )
print ()
if __name__ = = "__main__" :
n = 3
arr = [ 1 , 2 , 3 ]
smaller_sum(n, arr)
n = 20
arr = [ 0 , 7 , 7 , 9 , 0 , 0 , 5 , 1 , 0 , 6 ,
6 , 5 , 8 , 9 , 9 , 9 , 1 , 2 , 4 , 3 ]
smaller_sum(n, arr)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class SmallerSum
{
static void CalculateSmallerSum( int n, List< int > arr)
{
Dictionary< int , long > dict = new Dictionary< int , long >();
foreach ( int element in arr)
{
dict[element] = 0L;
}
List< int > vec = new List< int >(arr);
arr.Sort();
long sum = 0;
int pre = 0;
for ( int i = 0; i < n; i++)
{
if (pre != arr[i])
{
dict[arr[i]] = sum;
}
sum += arr[i];
pre = arr[i];
}
for ( int i = 0; i < n; i++)
{
Console.Write(dict[vec[i]] + " " );
}
Console.WriteLine();
}
public static void Main( string [] args)
{
int n = 3;
List< int > arr = new List< int > { 1, 2, 3 };
CalculateSmallerSum(n, arr);
n = 20;
arr = new List< int >
{
0, 7, 7, 9, 0, 0, 5, 1, 0, 6, 6, 5, 8, 9, 9, 9, 1, 2, 4, 3
};
CalculateSmallerSum(n, arr);
}
}
|
Javascript
function GFG(n, arr) {
const mp = {};
const vec = [...arr];
arr.sort((a, b) => a - b);
let sum = 0;
let pre = 0;
for (let i = 0; i < n; i++) {
if (pre !== arr[i]) {
mp[arr[i]] = sum;
}
sum += arr[i];
pre = arr[i];
}
for (let i = 0; i < n; i++) {
process.stdout.write((mp[vec[i]] || 0) + " " );
}
process.stdout.write( "\n" );
}
function main() {
let n = 3;
let arr = [1, 2, 3];
GFG(n, arr);
n = 20;
arr = [0, 7, 7, 9, 0, 0, 5, 1, 0, 6, 6, 5, 8, 9, 9, 9, 1, 2, 4, 3];
GFG(n, arr);
}
main();
|
Output
0 1 3
0 33 33 55 0 0 11 0 0 21 21 11 47 55 55 55 0 2 7 4
Time Complexity: O(n*logn)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...