Rearrange Array to minimize difference of sum of squares of odd and even index elements
Last Updated :
27 Mar, 2023
Given an array arr[] of size N (multiple of 8) where the values in the array will be in the range [a, (a+8*N) -1] (a can be any positive integer), the task is to rearrange the array in a way such that the difference between the sum of squares at odd indices and sum of squares of the elements at even indices is the minimum among all possible rearrangements.
Note: If there are multiple rearrangements return any one of those.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
Output: 1 2 4 3 7 8 6 5
Explanation: The difference is 0 as 1 + 42 + 72 + 62 = 102 = 22 + 32 + 82 + 52
Input: arr[] = { 9, 11, 12, 15, 16, 13, 10, 14}
Output: 9 10 12 11 15 16 14 13
Explanation: The difference is 0 as 92 + 122 + 152 + 142 = 102 + 112 + 162 + 132 = 646
Approach: This problem can be solved based on the following mathematical observation:
For any positive integer S, ( S )2 + ( S+3 )2 - 4 = ( S+1 )2 + ( S+2 )2. As N is a multiple of 8 so it can be divided into N/8 groups where the difference of sum of squares of elements at odd and even indices for each group is 0.
For the first four elements keep the sum of squares at odd indices greater and four the next four just the opposite to keep the sum of squares of even indices more. So this group of 8 elements will have difference 0. As the similar is done for all N/8 groups the overall difference will be 0.
The sequence of each group can be like: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
Follow the below steps to solve this problem:
- Divide the array into groups of size 8.
- Arrange elements in each group as derived from the observation.
- Return the rearranged array.
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find
// maximum element of the array
int maximum(int arr[], int size)
{
int ma = INT_MIN;
for (int i = 0; i < size; i++) {
ma = max(ma, arr[i]);
}
return ma;
}
// Function to find
// minimum element of the array
int minimum(int arr[], int size)
{
int mi = INT_MAX;
for (int i = 0; i < size; i++) {
mi = min(mi, arr[i]);
}
return mi;
}
// Function to print the array
void print_min(int arr[], int size)
{
int low = minimum(arr, size);
int high = maximum(arr, size);
// using the fact that
// s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for (int i = 0; i < size; i += 4) {
// Making the difference +4
// for the odd indices
if (i % 8 == 0) {
arr[i] = low;
arr[i + 2] = low + 3;
arr[i + 1] = low + 1;
arr[i + 3] = low + 2;
}
// Making the difference -4 for
// odd indices +4 - 4 = 0 (balanced)
else {
arr[i] = low + 2;
arr[i + 2] = low + 1;
arr[i + 1] = low + 3;
arr[i + 3] = low;
}
low += 4;
}
// Printing the array
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int N = sizeof(arr) / (sizeof(int));
// Function call
print_min(arr, N);
return 0;
}
Java
// JAVA code to implement the approach
import java.util.*;
class GFG
{
// Function to find
// maximum element of the array
public static int maximum(int arr[], int size)
{
int ma = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
ma = Math.max(ma, arr[i]);
}
return ma;
}
// Function to find
// minimum element of the array
public static int minimum(int arr[], int size)
{
int mi = Integer.MAX_VALUE;
for (int i = 0; i < size; i++) {
mi = Math.min(mi, arr[i]);
}
return mi;
}
// Function to print the array
public static void print_min(int arr[], int size)
{
int low = minimum(arr, size);
int high = maximum(arr, size);
// using the fact that
// s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for (int i = 0; i < size; i += 4) {
// Making the difference +4
// for the odd indices
if (i % 8 == 0) {
arr[i] = low;
arr[i + 2] = low + 3;
arr[i + 1] = low + 1;
arr[i + 3] = low + 2;
}
// Making the difference -4 for
// odd indices +4 - 4 = 0 (balanced)
else {
arr[i] = low + 2;
arr[i + 2] = low + 1;
arr[i + 1] = low + 3;
arr[i + 3] = low;
}
low += 4;
}
// Printing the array
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int N = arr.length;
// Function call
print_min(arr, N);
}
}
// This code is contributed by Taranpreet
Python3
# Python code to implement the approach
INT_MIN = -2147483647 - 1
INT_MAX = 2147483647
# Function to find
# maximum element of the array
def maximum(arr, size):
ma = INT_MIN
for i in range(size):
ma = max(ma, arr[i])
return ma
# Function to find
# minimum element of the array
def minimum(arr, size):
mi = INT_MAX
for i in range(size):
mi = min(mi, arr[i])
return mi
# Function to print the array
def print_min(arr, size):
low = minimum(arr, size)
high = maximum(arr, size)
# using the fact that
# s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for i in range(0,size,4):
# Making the difference +4
# for the odd indices
if (i % 8 == 0):
arr[i] = low
arr[i + 2] = low + 3
arr[i + 1] = low + 1
arr[i + 3] = low + 2
# Making the difference -4 for
# odd indices +4 - 4 = 0 (balanced)
else:
arr[i] = low + 2
arr[i + 2] = low + 1
arr[i + 1] = low + 3
arr[i + 3] = low
low += 4
# Printing the array
for i in range(size):
print(arr[i],end=" ")
# Driver code
arr = [1, 2, 3, 4, 5, 6, 7, 8]
N = len(arr)
# Function call
print_min(arr, N)
# This code is contributed by shinjanpatra
C#
// C# code to implement the approach
using System;
class GFG {
// Function to find
// maximum element of the array
static int maximum(int[] arr, int size)
{
int ma = Int32.MinValue;
for (int i = 0; i < size; i++) {
ma = Math.Max(ma, arr[i]);
}
return ma;
}
// Function to find
// minimum element of the array
static int minimum(int[] arr, int size)
{
int mi = Int32.MaxValue;
for (int i = 0; i < size; i++) {
mi = Math.Min(mi, arr[i]);
}
return mi;
}
// Function to print the array
static void print_min(int[] arr, int size)
{
int low = minimum(arr, size);
int high = maximum(arr, size);
// using the fact that
// s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for (int i = 0; i < size; i += 4) {
// Making the difference +4
// for the odd indices
if (i % 8 == 0) {
arr[i] = low;
arr[i + 2] = low + 3;
arr[i + 1] = low + 1;
arr[i + 3] = low + 2;
}
// Making the difference -4 for
// odd indices +4 - 4 = 0 (balanced)
else {
arr[i] = low + 2;
arr[i + 2] = low + 1;
arr[i + 1] = low + 3;
arr[i + 3] = low;
}
low += 4;
}
// Printing the array
for (int i = 0; i < size; i++) {
Console.Write(arr[i] + " ");
}
}
// Driver code
public static void Main()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
int N = arr.Length;
// Function call
print_min(arr, N);
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript code to implement the approach
const INT_MIN = -2147483647 - 1;
const INT_MAX = 2147483647;
// Function to find
// maximum element of the array
const maximum = (arr, size) => {
let ma = INT_MIN;
for (let i = 0; i < size; i++) {
ma = Math.max(ma, arr[i]);
}
return ma;
}
// Function to find
// minimum element of the array
const minimum = (arr, size) => {
let mi = INT_MAX;
for (let i = 0; i < size; i++) {
mi = Math.min(mi, arr[i]);
}
return mi;
}
// Function to print the array
const print_min = (arr, size) => {
let low = minimum(arr, size);
let high = maximum(arr, size);
// using the fact that
// s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for (let i = 0; i < size; i += 4) {
// Making the difference +4
// for the odd indices
if (i % 8 == 0) {
arr[i] = low;
arr[i + 2] = low + 3;
arr[i + 1] = low + 1;
arr[i + 3] = low + 2;
}
// Making the difference -4 for
// odd indices +4 - 4 = 0 (balanced)
else {
arr[i] = low + 2;
arr[i + 2] = low + 1;
arr[i + 1] = low + 3;
arr[i + 3] = low;
}
low += 4;
}
// Printing the array
for (let i = 0; i < size; i++) {
document.write(`${arr[i]} `);
}
}
// Driver code
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
let N = arr.length;
// Function call
print_min(arr, N);
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Another Approach:
- Divide the array into groups of size 8. (a)Since the given array has a length that is a multiple of 8, we can divide it into N/8 groups, where N is the length of the array.
- Arrange elements in each group as derived from the observation. (a)We can use the mathematical observation mentioned in the problem statement:
For any positive integer S, ( S )2 + ( S+3 )2 – 4 = ( S+1 )2 + ( S+2 )2
(b)We can use this formula to derive a sequence of numbers for each group of 8 elements that will keep the difference of sum of squares at odd and even indices zero.
(c)The sequence of each group can be like: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
(d)We can initialize S to be the minimum value in the array and then increment it by 4 for each group to get the above sequence.
- Return the rearranged array. (a)After arranging each group as described in step 2, we can return the rearranged array.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the minimum element in the array
int findMin(int arr[], int size) {
int minElement = INT_MAX;
for (int i = 0; i < size; i++) {
minElement = min(minElement, arr[i]);
}
return minElement;
}
// Function to rearrange the elements in each group
void rearrangeGroup(int arr[], int startValue) {
// Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
arr[0] = startValue;
arr[1] = startValue + 1;
arr[2] = startValue + 3;
arr[3] = startValue + 2;
arr[4] = startValue + 6;
arr[5] = startValue + 7;
arr[6] = startValue + 5;
arr[7] = startValue + 4;
}
// Function to rearrange the array
void rearrangeArray(int arr[], int size) {
int minElement = findMin(arr, size);
for (int i = 0; i < size; i += 8) {
if (i % 16 == 0) {
// For odd-indexed sum of squares > even-indexed sum of squares
rearrangeGroup(&arr[i], minElement);
} else {
// For even-indexed sum of squares > odd-indexed sum of squares
rearrangeGroup(&arr[i], minElement + 2);
}
minElement += 8;
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// Driver code
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int size = sizeof(arr) / sizeof(arr[0]);
// Rearrange the array
rearrangeArray(arr, size);
// Print the rearranged array
printArray(arr, size);
return 0;
}
Java
// Java Code to implement the approach
import java.util.*;
public class GFG {
// Function to find the minimum element in the array
public static int findMin(int[] arr, int size) {
int minElement = Integer.MAX_VALUE;
for (int i = 0; i < size; i++) {
minElement = Math.min(minElement, arr[i]);
}
return minElement;
}
// Function to rearrange the elements in each group
public static void rearrangeGroup(int[] arr, int startValue) {
// Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
arr[0] = startValue;
arr[1] = startValue + 1;
arr[2] = startValue + 3;
arr[3] = startValue + 2;
arr[4] = startValue + 6;
arr[5] = startValue + 7;
arr[6] = startValue + 5;
arr[7] = startValue + 4;
}
// Function to rearrange the array
public static void rearrangeArray(int[] arr, int size) {
int minElement = findMin(arr, size);
for (int i = 0; i < size; i += 8) {
if (i % 16 == 0) {
// For odd-indexed sum of squares > even-indexed sum of squares
rearrangeGroup(arr, minElement);
} else {
// For even-indexed sum of squares > odd-indexed sum of squares
rearrangeGroup(arr, minElement + 2);
}
minElement += 8;
}
}
// Function to print the array
public static void printArray(int[] arr, int size) {
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// Driver code
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
int size = arr.length;
// Rearrange the array
rearrangeArray(arr, size);
// Print the rearranged array
printArray(arr, size);
}
}
Python3
# Python3 Code to implement the approach
import sys
# Function to find the minimum element in the array
def findMin(arr, size):
minElement = sys.maxsize
for i in range(size):
minElement = min(minElement, arr[i])
return minElement
# Function to rearrange the elements in each group
def rearrangeGroup(arr, startValue):
# Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
new_arr = [startValue, startValue + 1, startValue + 3, startValue +
2, startValue + 6, startValue + 7, startValue + 5, startValue + 4]
return new_arr
# Function to rearrange the array
def rearrangeArray(arr, size):
minElement = findMin(arr, size)
for i in range(0, size, 8):
if i % 16 == 0:
# For odd-indexed sum of squares > even-indexed sum of squares
new_arr = rearrangeGroup(arr[i:i+8], minElement)
else:
# For even-indexed sum of squares > odd-indexed sum of squares
new_arr = rearrangeGroup(arr[i:i+8], minElement + 2)
arr[i:i+8] = new_arr
minElement += 8
# Function to print the array
def printArray(arr, size):
for i in range(size):
print(arr[i], end=" ")
print()
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6, 7, 8]
size = len(arr)
# Rearrange the array
rearrangeArray(arr, size)
# Print the rearranged array
printArray(arr, size)
C#
using System;
class GFG
{
// Function to find the minimum element in the array
static int FindMin(int[] arr, int size) {
int minElement = int.MaxValue;
for (int i = 0; i < size; i++) {
minElement = Math.Min(minElement, arr[i]);
}
return minElement;
}
// Function to rearrange the elements in each group
static void RearrangeGroup(int[] arr, int startValue) {
// Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
arr[0] = startValue;
arr[1] = startValue + 1;
arr[2] = startValue + 3;
arr[3] = startValue + 2;
arr[4] = startValue + 6;
arr[5] = startValue + 7;
arr[6] = startValue + 5;
arr[7] = startValue + 4;
}
// Function to rearrange the array
static void RearrangeArray(int[] arr, int size) {
int minElement = FindMin(arr, size);
for (int i = 0; i < size; i += 8) {
if (i % 16 == 0) {
// For odd-indexed sum of squares > even-indexed sum of squares
RearrangeGroup(arr, minElement);
} else {
// For even-indexed sum of squares > odd-indexed sum of squares
RearrangeGroup(arr, minElement + 2);
}
minElement += 8;
}
}
// Function to print the array
static void PrintArray(int[] arr, int size) {
for (int i = 0; i < size; i++) {
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
// Driver code
static void Main(string[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
int size = arr.Length;
// Rearrange the array
RearrangeArray(arr, size);
// Print the rearranged array
PrintArray(arr, size);
}
}
JavaScript
// JavaScript Code to implement the approach
// Function to find the minimum element in the array
function findMin(arr) {
let minElement = Infinity;
for (let i = 0; i < arr.length; i++) {
minElement = Math.min(minElement, arr[i]);
}
return minElement;
}
// Function to rearrange the elements in each group
function rearrangeGroup(arr, startValue) {
// Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
arr[0] = startValue;
arr[1] = startValue + 1;
arr[2] = startValue + 3;
arr[3] = startValue + 2;
arr[4] = startValue + 6;
arr[5] = startValue + 7;
arr[6] = startValue + 5;
arr[7] = startValue + 4;
}
// Function to rearrange the array
function rearrangeArray(arr) {
let minElement = findMin(arr);
for (let i = 0; i < arr.length; i += 8) {
if (i % 16 === 0) {
// For odd-indexed sum of squares > even-indexed sum of squares
rearrangeGroup(arr, minElement);
} else {
// For even-indexed sum of squares > odd-indexed sum of squares
rearrangeGroup(arr, minElement + 2);
}
minElement += 8;
}
}
// Function to print the array
function printArray(arr) {
console.log(arr.join(' '));
}
// Driver code
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
// Rearrange the array
rearrangeArray(arr);
// Print the rearranged array
printArray(arr);
Time Complexity: O(N), where N is the size of the array
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem