Rearrange arrays such that sum of corresponding elements is same for all equal indices
Last Updated :
28 Jan, 2024
Given two arrays A[] and B[] of length N. Then your task is to rearrange the elements of both arrays in such a way that the sum (Ai + Bi) for all i (1 <= i <= N) is same. If no such arrangement is possible output -1 instead.
Examples:
Input: N = 3, A[] = {1, 2, 3}, B[] = {1, 2, 3}
Output: A[] = {3, 1, 2}, B[] = {1, 3, 2}
Explanation: Rearranged A[] and B[] are {3, 1, 2} and {1, 3, 2} respectively. Let us see the sum at each index i (1 <= i <= 3):
- 1st index: A1 + B1 = (3 + 1) = 4
- 2nd index: A2 + B2 = (1 + 3) = 4
- 3rd index: A3 + B3 = (2 + 2) = 4
The sum at each index is same . Thus, arrangements are valid and follows the given constraints.
Input: N = 3, A[] = {5, 6, 7}, B[] = {4, 3, 1}
Output: -1
Explanation: It can be verified that no arrangement of elements is possible such that (Ai + Bi) for all pairs.
Approach: To solve the problem, follow the below idea:
The problem can be solved using the HashMap. There are two things to check:
- Possibility of rearrangement
- Final rearrangement
Let us see both of them one by one:
- Possibility of rearrangement:
- As it is mentioned that the sum of (Ai + Bi) over all i for (1 <= i <= N) must be equal. Distributing of a sum over N number of indices is possible only and only if (Sum % N == 0), where Sum is equal to sum of all elements of A[] and B[]. Hence, in this way the possibility of arrangement can be checked.
- Final rearrangement:
- First of all, we need to know the exact average sum let say Avg, so that for each index (Ai + Bi) = Avg.
- As Sum must be distributed over all indices equally, thus Avg will be equal to (Sum/N). Formally, Avg = (Sum/N).
- Now, we need to do pairing between A[]’s and B[]’s element, So that they should provide sum of pair equal to Avg. Consider that any index i, we know one element let say Ai then it must be paired with an element of B[] such that Bi = (Avg – X). So, that sum of both (Ai + Bi) = ((X) + (Avg – X)) gives Avg, which is required sum at that index i. For knowing the presence of such (Avg – X) element in B[], we need to implement a constant check implementation. Which is only possible by putting all elements of B[] into HashMap. Thus, we can iterate over all indices using loop and Ai can be paired with Bi, If Bi is present in Map, At each iteration the frequency of Bi will be reduced by 1.
Step-by-step algorithm:
- Calculate the sum of all elements of A[] and B[].
- If the sum is not divisible by N, then return -1.
- Else calculate the average Avg = Sum/N.
- Store the frequency of all the elements of B[] in a frequency map.
- Iterate over all the elements for A[] and for every index i, search for (Avg – A[i]) in the frequency map.
- If (Avg – A[i]) is not found, return -1.
- Else make B[i] = (Avg – A[i]) and continue.
- After traversing over all the elements, print the B[] array as the final answer.
Below is the implementation of the algorithm:
C++
#include <iostream>
#include <unordered_map>
using namespace std;
void Rearrange( int N, int A[], int B[]);
int main()
{
int N = 3;
int A[] = {1, 2, 3};
int B[] = {3, 1, 2};
Rearrange(N, A, B);
return 0;
}
void Rearrange( int N, int A[], int B[])
{
unordered_map< int , int > Map;
int Sum = 0;
for ( int i = 0; i < N; i++)
{
Sum += A[i] + B[i];
if (Map.find(B[i]) != Map.end())
{
Map[B[i]]++;
}
else
{
Map[B[i]] = 1;
}
}
bool flag = true ;
if (Sum % N == 0)
{
int Avg = Sum / N;
for ( int i = 0; i < N; i++)
{
int required = Avg - A[i];
if (Map.find(required) != Map.end() && Map[required] > 0)
{
B[i] = required;
Map[required]--;
}
else
{
flag = false ;
}
}
}
else
flag = false ;
if (flag)
{
for ( int i = 0; i < N; i++)
{
cout << A[i] << " " ;
}
cout << endl;
for ( int i = 0; i < N; i++)
{
cout << B[i] << " " ;
}
cout << endl;
}
else
cout << -1 << endl;
}
|
Java
import java.util.*;
class Main {
public static void main(String[] args)
{
int N = 3 ;
int A[] = { 1 , 2 , 3 };
int B[] = { 3 , 1 , 2 };
Rearrange(N, A, B);
}
public static void Rearrange( int N, int [] A, int [] B)
{
HashMap<Integer, Integer> Map = new HashMap<>();
int Sum = 0 ;
for ( int i = 0 ; i < N; i++) {
Sum += A[i] + B[i];
if (Map.containsKey(B[i])) {
Map.put(B[i], Map.get(B[i]) + 1 );
}
else
Map.put(B[i], 1 );
}
boolean flag = true ;
if (Sum % N == 0 ) {
int Avg = Sum / N;
for ( int i = 0 ; i < N; i++) {
int required = Avg - A[i];
if (Map.containsKey(required)) {
B[i] = required;
Map.put(required,
Map.get(required) - 1 );
}
else {
flag = false ;
}
}
}
else
flag = false ;
if (flag) {
for ( int i = 0 ; i < N; i++) {
System.out.print(A[i] + " ");
}
System.out.println();
for ( int i = 0 ; i < N; i++) {
System.out.print(B[i] + " ");
}
System.out.println();
}
else
System.out.println(- 1 );
}
}
|
Python3
def rearrange(N, A, B):
Map = {}
Sum = 0
for i in range (N):
Sum + = A[i] + B[i]
if B[i] in Map :
Map [B[i]] + = 1
else :
Map [B[i]] = 1
flag = True
if Sum % N = = 0 :
Avg = Sum / / N
for i in range (N):
required = Avg - A[i]
if required in Map and Map [required] > 0 :
B[i] = required
Map [required] - = 1
else :
flag = False
else :
flag = False
if flag:
print ( * A)
print ( * B)
else :
print ( - 1 )
if __name__ = = "__main__" :
N = 3
A = [ 1 , 2 , 3 ]
B = [ 3 , 1 , 2 ]
rearrange(N, A, B)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static void Rearrange( int N, int [] A, int [] B)
{
Dictionary< int , int > Map = new Dictionary< int , int >();
int Sum = 0;
for ( int i = 0; i < N; i++)
{
Sum += A[i] + B[i];
if (Map.ContainsKey(B[i]))
{
Map[B[i]] += 1;
}
else
{
Map[B[i]] = 1;
}
}
bool flag = true ;
if (Sum % N == 0)
{
int Avg = Sum / N;
for ( int i = 0; i < N; i++)
{
int required = Avg - A[i];
if (Map.ContainsKey(required) && Map[required] > 0)
{
B[i] = required;
Map[required] -= 1;
}
else
{
flag = false ;
}
}
}
else
{
flag = false ;
}
if (flag)
{
Console.WriteLine( string .Join( " " , A));
Console.WriteLine( string .Join( " " , B));
}
else
{
Console.WriteLine(-1);
}
}
static void Main()
{
int N = 3;
int [] A = { 1, 2, 3 };
int [] B = { 3, 1, 2 };
Rearrange(N, A, B);
}
}
|
Javascript
function rearrange(N, A, B) {
let Map = new Map();
let Sum = 0;
for (let i = 0; i < N; i++) {
Sum += A[i] + B[i];
if (Map.has(B[i])) {
Map.set(B[i], Map.get(B[i]) + 1);
} else {
Map.set(B[i], 1);
}
}
let flag = true ;
if (Sum % N === 0) {
let Avg = Sum / N;
for (let i = 0; i < N; i++) {
let required = Avg - A[i];
if (Map.has(required) && Map.get(required) > 0) {
B[i] = required;
Map.set(required, Map.get(required) - 1);
}
else {
flag = false ;
}
}
}
else {
flag = false ;
}
if (flag) {
console.log(A.join( " " ));
console.log(B.join( " " ));
}
else {
console.log(-1);
}
}
let N = 3;
let A = [1, 2, 3];
let B = [3, 1, 2];
rearrange(N, A, B);
|
Time Complexity: O(N), where N is the size of input array A[] or B[].
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...