Rearrange an Array such that Sum of same-indexed subsets differ from their Sum in the original Array
Last Updated :
19 May, 2021
Given an array A[] consisting of N distinct integers, the task is to rearrange the given array such that the sum of every same-indexed non-empty subsets of size less than N, is not equal to their sum in the original array.
Examples:
Input: A[] = {1000, 100, 10, 1}
Output: 100 10 1 1000
Explanation:
Original Array A[] = {1000, 100, 10, 1}
Final Array B[] = {100, 10, 1, 1000}
Subsets of size 1:
A[0] = 1000 B[0] = 100
A[1] = 100 B[1] = 10
A[2] = 10 B[2] = 1
A[3] = 1 B[3] = 1000
Subsets of size 2:
{A[0], A[1]} = 1100 {B[0], B[1]} = 110
{A[0], A[2]} = 1010 {B[0], B[2]} = 101
{A[1], A[2]} = 110 {B[1], B[2]} = 11
.....
Similarly, all same-indexed subsets of size 2 have a different sum.
Subsets of size 3:
{A[0], A[1], A[2]} = 1110 {B[0], B[1], B[2]} = 111
{A[0], A[2], A[3]} = 1011 {B[0], B[2], B[3]} = 1101
{A[1], A[2], A[3]} = 111 {B[1], B[2], B[3]} = 1011
Therefore, no same-indexed subsets have equal sum.
Input: A[] = {1, 2, 3, 4, 5}
Output: 5 1 2 3 4
Approach:
The idea is to simply replace every array element except one, by a smaller element. Follow the steps below to solve the problem:
- Store the array elements in pairs of {A[i], i}.
- Sort the pairs in ascending order Of the array elements
- Now, traverse the sorted order, and insert each element at the original index of its next greater element(i.e. at the index v[(i + 1) % n].second). This ensures that every index except one now has a smaller element than the previous value stored in it.
Proof:
Let S = { arr1, arr2, ..., arrk } be a subset.
If u does not belong to S initially, upon insertion of u into S, the sum of the subset changes.
Similarly, if u belongs to S, let S' contains all the elements not present in S. This means that u do not belong to S'. Then, by the same reasoning above, the sum of the subset S' differs from its original sum.
Below is the implementation of the above approach:
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to rearrange the array such
// that no same-indexed subset have sum
// equal to that in the original array
void printNewArray(vector<int> a, int n)
{
// Initialize a vector
vector<pair<int, int> > v;
// Iterate the array
for (int i = 0; i < n; i++) {
v.push_back({ a[i], i });
}
// Sort the vector
sort(v.begin(), v.end());
int ans[n];
// Shift of elements to the
// index of its next cyclic element
for (int i = 0; i < n; i++) {
ans[v[(i + 1) % n].second]
= v[i].first;
}
// Print the answer
for (int i = 0; i < n; i++) {
cout << ans[i] << " ";
}
}
// Driver Code
int main()
{
vector<int> a = { 4, 1, 2, 5, 3 };
int n = a.size();
printNewArray(a, n);
return 0;
}
Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
class GFG{
static class pair
{
int first, second;
pair(int first, int second)
{
this.first = first;
this.second = second;
}
}
// Function to rearrange the array such
// that no same-indexed subset have sum
// equal to that in the original array
static void printNewArray(List<Integer> a, int n)
{
// Initialize a vector
List<pair> v = new ArrayList<>();
// Iterate the array
for(int i = 0; i < n; i++)
{
v.add(new pair(a.get(i), i));
}
// Sort the vector
Collections.sort(v, (pair s1, pair s2) ->
{
return s1.first - s2.first;
});
int ans[] = new int[n];
// Shift of elements to the
// index of its next cyclic element
for(int i = 0; i < n; i++)
{
ans[v.get((i + 1) % n).second] = v.get(i).first;
}
// Print the answer
for(int i = 0; i < n; i++)
{
System.out.print(ans[i] + " ");
}
}
// Driver Code
public static void main(String args[])
{
List<Integer> a = Arrays.asList(4, 1, 2, 5, 3);
int n = a.size();
printNewArray(a, n);
}
}
// This code is contributed by offbeat
Python3
# Python3 Program to implement
# the above approach
# Function to rearrange the array such
# that no same-indexed subset have sum
# equal to that in the original array
def printNewArray(a, n):
# Initialize a vector
v = []
# Iterate the array
for i in range (n):
v.append((a[i], i ))
# Sort the vector
v.sort()
ans = [0] * n
# Shift of elements to the
# index of its next cyclic element
for i in range (n):
ans[v[(i + 1) % n][1]] = v[i][0]
# Print the answer
for i in range (n):
print (ans[i], end = " ")
# Driver Code
if __name__ == "__main__":
a = [4, 1, 2, 5, 3]
n = len(a)
printNewArray(a, n)
# This code is contributed by Chitranayal
C#
// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to rearrange the array such
// that no same-indexed subset have sum
// equal to that in the original array
static void printNewArray(List<int> a, int n)
{
// Initialize a vector
List<Tuple<int, int>> v = new List<Tuple<int, int>>();
// Iterate the array
for (int i = 0; i < n; i++)
{
v.Add(new Tuple<int, int>(a[i],i));
}
// Sort the vector
v.Sort();
int[] ans = new int[n];
// Shift of elements to the
// index of its next cyclic element
for (int i = 0; i < n; i++)
{
ans[v[(i + 1) % n].Item2]
= v[i].Item1;
}
// Print the answer
for (int i = 0; i < n; i++)
{
Console.Write(ans[i] + " ");
}
}
// Driver code
static void Main()
{
List<int> a = new List<int>(new int[]{4, 1, 2, 5, 3});
int n = a.Count;
printNewArray(a, n);
}
}
// This code is contributed by divyesh072019
JavaScript
<script>
// Javascript Program to implement
// the above approach
// Function to rearrange the array such
// that no same-indexed subset have sum
// equal to that in the original array
function printNewArray(a, n)
{
// Initialize a vector
var v = [];
// Iterate the array
for (var i = 0; i < n; i++) {
v.push([ a[i], i]);
}
// Sort the vector
v.sort();
var ans = Array(n);
// Shift of elements to the
// index of its next cyclic element
for (var i = 0; i < n; i++) {
ans[v[(i + 1) % n][1]]
= v[i][0];
}
// Print the answer
for (var i = 0; i < n; i++) {
document.write( ans[i] + " ");
}
}
// Driver Code
var a = [4, 1, 2, 5, 3];
var n = a.length;
printNewArray(a, n);
</script>
Time Complexity: O(N log N)
Auxiliary Space: O(N)
Similar Reads
Partition a set into two subsets such that the difference of subset sums is minimum Given an array arr[] of size n, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must have n-m elements and the value of abs(sum(Subset1) - sum(Subs
15+ min read
Find pair i, j such that |A[i]âA[j]| is same as sum of difference of them with any Array element Given an array A[] having N non-negative integers, find a pair of indices i and j such that the absolute difference between them is same as the sum of differences of those with any other array element i.e., | A[i] â A[k] | + | A[k]â A[j] | = | A[i] â A[j] |, where k can be any index. Examples: Input
7 min read
Find sub-arrays from given two arrays such that they have equal sum Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] =
15+ min read
Rearrange array to make sum of all subarrays starting from first index non-zero Given an array arr[] consisting of N integers, the task is to rearrange the array such that sum of all subarrays starting from the first index of the array is non-zero. If it is not possible to generate such arrangement, then print "-1". Examples: Input: arr[] = {-1, 1, -2, 3}Output: {-1, -2, 1, 3}E
12 min read
Find an element in array such that sum of left array is equal to sum of right array Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sums. Examples: Input: 1 4 2 5 0Output: 2Explanation: If 2 is the partition, subarrays are : [1, 4] and [5] Input: 2 3 4 1 4 5Output: 1Explanation: If 1 is the partition, Subarrays are : [2, 3, 4] and [4
15+ min read