Check if it is possible to redistribute the Array
Last Updated :
07 Dec, 2022
Given an array arr[] of N integers, the task is to check if it is possible to redistribute the array such that for every 1 ? i ? N (1-based indexing) arr[i] = i. Redistributing the array means all the elements of the array can be changed to any other element but the sum of the resultant array must be equal to the original array sum.
Examples:
Input: arr[] = {7, 4, 1, 1, 2}
Output: Yes
7 + 4 + 1 + 1 + 2 = 15
1 + 2 + 3 + 4 + 5 = 15
Input: arr[] = {1, 1, 1, 1}
Output: No
1 + 1 + 1 + 1 = 4
1 + 2 + 3 + 4 = 10
Approach: It is given that the sum of the array must not change after the modification. So, calculate the sum of the given array and in order for the array to be of the form 1, 2, 3, …, N, the sum of the array elements must be (N * (N + 1)) / 2. Else, it is impossible.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool canRedistribute( int * a, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += a[i];
if (sum == (n * (n + 1)) / 2)
return true ;
return false ;
}
int main()
{
int a[] = { 7, 4, 1, 1, 2 };
int n = sizeof (a) / sizeof ( int );
if (canRedistribute(a, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static boolean canRedistribute( int []a, int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += a[i];
if (sum == (n * (n + 1 )) / 2 )
return true ;
return false ;
}
public static void main (String[] args)
{
int a[] = { 7 , 4 , 1 , 1 , 2 };
int n = a.length;
if (canRedistribute(a, n))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def canRedistribute(a, n):
sum = 0 ;
for i in range (n):
sum + = a[i];
if ( sum = = (n * (n + 1 )) / 2 ):
return True ;
return False ;
a = [ 7 , 4 , 1 , 1 , 2 ];
n = len (a);
if (canRedistribute(a, n)):
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG
{
static Boolean canRedistribute( int []a, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += a[i];
if (sum == (n * (n + 1)) / 2)
return true ;
return false ;
}
public static void Main (String[] args)
{
int []a = { 7, 4, 1, 1, 2 };
int n = a.Length;
if (canRedistribute(a, n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function canRedistribute(a, n)
{
var sum = 0;
for ( var i = 0; i < n; i++)
sum += a[i];
if (sum == (n * (n + 1)) / 2)
return true ;
return false ;
}
var a = [ 7, 4, 1, 1, 2 ];
var n = a.length;
if (canRedistribute(a, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n), where n is the length of the given array.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...