Rearrange an array such that product of every two consecutive elements is a multiple of 4
Last Updated :
08 Jul, 2021
Given an array arr[] of size N, the task is to rearrange the array elements such that for every index i(1 <= i <= N - 1), the product of arr[i] and arr[i - 1] is a multiple of 4.
Example:
Input: arr[] = {1, 10, 100}
Output: 1, 100, 10
Explanation:
1 * 100 is divisible by 4
100 * 10 is divisible by 4
Input: arr[] = {2, 7, 1, 8, 2, 8}
Output: 7, 8, 1, 8, 2, 2
Naive Approach:
The simplest approach to solve the problem is to generate all possible permutations of the array and for every permutation, check if the product of every two consecutive elements is a multiple of 4 or not.
Time complexity: O(N^2 * N!)
Auxiliary Space: O(N!)
Efficient Approach:
Follow the steps below to optimize the above approach:
- Initialize following three variables:
- odd = Number of odd elements.
- four = Number of elements divisible by 4.
- non_four = Number of even elements not divisible by 4.
- Consider the following two cases:
- Case 1: non_four = 0
In this case, no even elements are present which are not divisible by 4.- The optimal way is to first place the “odd” elements first in the array in alternate positions.
- Fill the vacancies with the even elements.
Illustration
arr[] = {1, 1, 1, 4, 4}
Step 0: four = 2, odd = 3
Step 1: {1 _ 1 _ 1}
Step 2: {1 4 1 4 1}
- Hence, for the approach to be mathematically possible, the difference between the count of even and odd elements should not exceed 1.
- Case 2: non_four > 0
In this case, even elements that are not divisible by 4 exist in the array.
- Follow the exact same strategy as depicted above by placing the elements divisible by 4 in alternate positions followed by odd elements in the vacancies.
- Then, place all the remaining even elements at the end of the array. This is because the product of two even numbers is always divisible by 4. Hence, placing the even elements towards the end of the array guarantees that the product of consecutive elements among them is divisible by 4.
Illustration:
arr[] = {2, 7, 1, 8, 2, 8}
Step 1: four = 2, non_four = 2, odd = 2
Step 2: {_ 8 _ 8}
Step 3: {1 8 7 8}
Step 4: {1 8 7 8 2 2}
- For this to be possible mathematically, four >= odd.
Below is the implementation of the above approach:
C++
// C++ Program to rearray array
// elements such that the product
// of every two consecutive
// elements is a multiple of 4
#include <bits/stdc++.h>
using namespace std;
// Function to rearrange array
// elements such that the every
// two consecutive elements is
// a multiple of 4
void Permute(vector<int>& arr,
int n)
{
int odd = 0, four = 0;
int non_four = 0;
vector<int> ODD, FOUR,
NON_FOUR;
for (auto x : arr) {
// If element is odd
if (x & 1) {
odd++;
// Odd
ODD.push_back(x);
}
// If element is divisible
// by 4
else if (x % 4 == 0) {
four++;
// Divisible by 4
FOUR.push_back(x);
}
// If element is not
// divisible by 4
else {
non_four++;
// Even but not divisible
// by 4
NON_FOUR.push_back(x);
}
}
// Condition for rearrangement
// to be possible
if (non_four == 0
&& four >= odd - 1) {
int x = ODD.size();
int y = FOUR.size();
int i;
// Print ODD[i] and FOUR[i]
// consecutively
for (i = 0; i < x; i++) {
cout << ODD[i] << " ";
if (i < y)
cout << FOUR[i] << " ";
}
// Print the remaining
// FOUR[i], if any
while (i < y)
cout << FOUR[i] << " ";
cout << endl;
}
// Condition for rearrangement
// to be possible
else if (non_four > 0
and four >= odd) {
int x = ODD.size();
int y = FOUR.size();
int i;
// Print ODD[i] and FOUR[i]
// consecutively
for (i = 0; i < x; i++) {
cout << ODD[i] << " ";
if (i < y)
cout << FOUR[i] << " ";
}
// Print the remaining
// FOUR[i], if any
while (i < y)
cout << FOUR[i] << " ";
// Print the NON_FOUR[i]
// elements at the end
for (int j = 0;
j < (int)NON_FOUR.size();
j++)
cout << NON_FOUR[j] << " ";
cout << endl;
}
else
// No possible configuration
cout << "Not Possible" << endl;
}
// Driver Code
signed main()
{
vector<int> arr = { 2, 7, 1,
8, 2, 8 };
int N = sizeof(arr) / sizeof(arr);
Permute(arr, N);
return 0;
}
Java
// Java program to rearray array
// elements such that the product
// of every two consecutive
// elements is a multiple of
import java.io.*;
import java.util.*;
class GFG{
// Function to rearrange array
// elements such that the every
// two consecutive elements is
// a multiple of 4
public static void Permute(Vector<Integer> arr, int n)
{
int odd = 0, four = 0;
int non_four = 0;
Vector<Integer> ODD = new Vector<Integer>();
Vector<Integer> FOUR = new Vector<Integer>(n);
Vector<Integer> NON_FOUR = new Vector<Integer>(n);
for(int x : arr)
{
// If element is odd
if (x % 2 != 0)
{
odd++;
// Odd
ODD.add(x);
}
// If element is divisible
// by 4
else if (x % 4 == 0)
{
four++;
// Divisible by 4
FOUR.add(x);
}
// If element is not
// divisible by 4
else
{
non_four++;
// Even but not divisible
// by 4
NON_FOUR.add(x);
}
}
// Condition for rearrangement
// to be possible
if (non_four == 0 && four >= odd - 1)
{
int x = ODD.size();
int y = FOUR.size();
int i;
// Print ODD.get(i) and FOUR.get(i)
// consecutively
for(i = 0; i < x; i++)
{
System.out.print(ODD.get(i) + " ");
if (i < y)
System.out.print(FOUR.get(i) + " ");
}
// Print the remaining
// FOUR.get(i), if any
while (i < y)
System.out.print(FOUR.get(i) + " ");
System.out.println();
}
// Condition for rearrangement
// to be possible
else if (non_four > 0 && four >= odd)
{
int x = ODD.size();
int y = FOUR.size();
int i;
// Print ODD.get(i) and FOUR.get(i)
// consecutively
for(i = 0; i < x; i++)
{
System.out.print(ODD.get(i) + " ");
if (i < y)
System.out.print(FOUR.get(i) + " ");
}
// Print the remaining
// FOUR.get(i), if any
while (i < y)
System.out.print(FOUR.get(i) + " ");
// Print the NON_FOUR.get(i)
// elements at the end
for(int j = 0; j < (int)NON_FOUR.size(); j++)
System.out.print(NON_FOUR.get(j) + " ");
System.out.println();
}
else
// No possible configuration
System.out.println("Not Possible");
}
// Driver Code
public static void main(String[] args)
{
Vector<Integer> arr = new Vector<Integer>();
arr.add(2);
arr.add(7);
arr.add(1);
arr.add(8);
arr.add(2);
arr.add(8);
Permute(arr, arr.size());
}
}
// This code is contributed by grand_master
Python3
# Python3 program to rearray array
# elements such that the product
# of every two consecutive
# elements is a multiple of 4
# Function to rearrange array
# elements such that the every
# two consecutive elements is
# a multiple of 4
def Permute(arr, n):
odd = 0
four = 0
non_four = 0
ODD, FOUR, NON_FOUR = [], [], []
for x in arr:
# If element is odd
if (x & 1):
odd += 1
# Odd
ODD.append(x)
# If element is divisible
# by 4
elif (x % 4 == 0):
four += 1
# Divisible by 4
FOUR.append(x)
# If element is not
# divisible by 4
else:
non_four += 1
# Even but not divisible
# by 4
NON_FOUR.append(x)
# Condition for rearrangement
# to be possible
if (non_four == 0 and four >= odd - 1):
x = len(ODD)
y = len(FOUR)
i = 0
# Print ODD[i] and FOUR[i]
# consecutively
while i < x:
print(ODD[i], end = " ")
if (i < y):
print(FOUR[i], end = " ")
# Print the remaining
# FOUR[i], if any
while (i < y):
print(FOUR[i], end = " ")
i += 1
print()
# Condition for rearrangement
# to be possible
elif (non_four > 0 and four >= odd):
x = len(ODD)
y = len(FOUR)
i = 0
# Print ODD[i] and FOUR[i]
# consecutively
while i < x:
print(ODD[i], end = " ")
if (i < y):
print(FOUR[i], end = " ")
i += 1
# Print the remaining
# FOUR[i], if any
while (i < y):
print(FOUR[i], end = " ")
i += 1
# Print the NON_FOUR[i]
# elements at the end
for j in NON_FOUR:
print(j, end = " ")
else:
# No possible configuration
print("Not Possible")
# Driver Code
if __name__ == '__main__':
arr = [ 2, 7, 1, 8, 2, 8 ]
N = len(arr)
Permute(arr, N)
# This code is contributed by mohit kumar 29
C#
// C# program to rearray array
// elements such that the product
// of every two consecutive
// elements is a multiple of
using System;
using System.Collections.Generic;
class GFG{
// Function to rearrange array
// elements such that the every
// two consecutive elements is
// a multiple of 4
public static void Permute(List<int> arr,
int n)
{
int odd = 0, four = 0;
int non_four = 0;
List<int> ODD =
new List<int>();
List<int> FOUR =
new List<int>(n);
List<int> NON_FOUR =
new List<int>(n);
foreach(int x in arr)
{
// If element is odd
if (x % 2 != 0)
{
odd++;
// Odd
ODD.Add(x);
}
// If element is divisible
// by 4
else if (x % 4 == 0)
{
four++;
// Divisible by 4
FOUR.Add(x);
}
// If element is not
// divisible by 4
else
{
non_four++;
// Even but not divisible
// by 4
NON_FOUR.Add(x);
}
}
// Condition for rearrangement
// to be possible
if (non_four == 0 &&
four >= odd - 1)
{
int x = ODD.Count;
int y = FOUR.Count;
int i;
// Print ODD[i] and FOUR[i]
// consecutively
for(i = 0; i < x; i++)
{
Console.Write(ODD[i] + " ");
if (i < y)
Console.Write(FOUR[i] + " ");
}
// Print the remaining
// FOUR[i], if any
while (i < y)
Console.Write(FOUR[i] + " ");
Console.WriteLine();
}
// Condition for rearrangement
// to be possible
else if (non_four > 0 &&
four >= odd)
{
int x = ODD.Count;
int y = FOUR.Count;
int i;
// Print ODD[i] and FOUR[i]
// consecutively
for(i = 0; i < x; i++)
{
Console.Write(ODD[i] + " ");
if (i < y)
Console.Write(FOUR[i] + " ");
}
// Print the remaining
// FOUR[i], if any
while (i < y)
Console.Write(FOUR[i] + " ");
// Print the NON_FOUR[i]
// elements at the end
for(int j = 0;
j < (int)NON_FOUR.Count; j++)
Console.Write(NON_FOUR[j] + " ");
Console.WriteLine();
}
else
// No possible configuration
Console.WriteLine("Not Possible");
}
// Driver Code
public static void Main(String[] args)
{
List<int> arr = new List<int>();
arr.Add(2);
arr.Add(7);
arr.Add(1);
arr.Add(8);
arr.Add(2);
arr.Add(8);
Permute(arr, arr.Count);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to rearray array
// elements such that the product
// of every two consecutive
// elements is a multiple of
// Function to rearrange array
// elements such that the every
// two consecutive elements is
// a multiple of 4
function Permute(arr,n)
{
let odd = 0, four = 0;
let non_four = 0;
let ODD = [];
let FOUR = [];
let NON_FOUR = [];
for(let x = 0; x < arr.length; x++)
{
// If element is odd
if (arr[x] % 2 != 0)
{
odd++;
// Odd
ODD.push(arr[x]);
}
// If element is divisible
// by 4
else if (arr[x] % 4 == 0)
{
four++;
// Divisible by 4
FOUR.push(arr[x]);
}
// If element is not
// divisible by 4
else
{
non_four++;
// Even but not divisible
// by 4
NON_FOUR.push(arr[x]);
}
}
// Condition for rearrangement
// to be possible
if (non_four == 0 && four >= odd - 1)
{
let x = ODD.length;
let y = FOUR.length;
let i;
// Print ODD.get(i) and FOUR.get(i)
// consecutively
for(i = 0; i < x; i++)
{
document.write(ODD[i] + " ");
if (i < y)
document.write(FOUR[i] + " ");
}
// Print the remaining
// FOUR.get(i), if any
while (i < y)
document.write(FOUR[i] + " ");
document.write("<br>");
}
// Condition for rearrangement
// to be possible
else if (non_four > 0 && four >= odd)
{
let x = ODD.length;
let y = FOUR.length;
let i;
// Print ODD.get(i) and FOUR.get(i)
// consecutively
for(i = 0; i < x; i++)
{
document.write(ODD[i] + " ");
if (i < y)
document.write(FOUR[i] + " ");
}
// Print the remaining
// FOUR.get(i), if any
while (i < y)
document.write(FOUR[i] + " ");
// Print the NON_FOUR.get(i)
// elements at the end
for(let j = 0; j < NON_FOUR.length; j++)
document.write(NON_FOUR[j] + " ");
document.write("<br>");
}
else
// No possible configuration
document.write("Not Possible<br>");
}
// Driver Code
let arr=[2,7,1,8,2,8]
Permute(arr, arr.length);
// This code is contributed by patel2127
</script>
Output:
7 8 1 8 2 2
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Construct array with sum of product of same indexed elements in the given array equal to zero
Given an array, arr[] of size N (always even), the task is to construct a new array consisting of N non-zero integers such that the sum of the product of the same indexed elements of arr[] and the new array is equal to 0. If multiple solutions exist, print any one of them. Examples: Input: arr[] = {
6 min read
Count arrays of length K whose product of elements is same as that of given array
Given an integer array arr[] of length N and an integer K, the task is to count the number of possible arrays of length K such that the product of all elements of that array is equal to the product of all elements of the given array arr[]. Since the answer can be very large, return the answer modulo
15+ min read
Minimum flips in a Binary array such that XOR of consecutive subarrays of size K have different parity
Given a binary array arr[] of length N, the task is to find the minimum flips required in the array such that XOR of a consecutive sub-arrays of size K have different parity.Examples: Input: arr[] = {0, 1, 0, 1, 1}, K = 2 Output: 2 Explanation: For the above given array XOR of consecutive sub-array
9 min read
Rearrange Array to minimize difference of sum of squares of odd and even index elements
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
15+ min read
Minimum sum subsequence such that at least one of every four consecutive elements is picked
Given an array arr[] of positive integers. The task is to find minimum sum subsequence from the array such that at least one value among all groups of four consecutive elements is picked. Examples : Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8}Output: 66 is sum of output subsequence {1, 5}Note that we hav
15+ min read
Count of elements to be multiplied with integers to make each pair of Array a perfect square
Given an array arr[] containing positive integers, the task is to find the minimum number of operations to be done on the array to make every number of the array a superpower. In each operation, we can multiply any element of the array with an integer. A superpower is defined as a number in the arra
15+ min read
Product of all pairwise consecutive elements in an Array
Given an array of integers of N elements. The task is to print the product of all of the pairwise consecutive elements.Pairwise consecutive pairs of an array of size N are (a[i], a[i+1]) for all i ranging from 0 to N-2 Examples: Input : arr[] = {8, 5, 4, 3, 15, 20} Output : 40, 20, 12, 45, 300 Input
4 min read
Count of permutation such that GCD of all elements multiplied with position is not 1
Given an integer array having N elements ranging from 1 to N and each element appearing exactly once. The task is to find the number of possible permutations such that the GCD of all elements multiplied with their position is greater than 1. Note: As the answer can be very large, return the answer m
5 min read
Count array elements that can be represented as sum of at least two consecutive array elements
Given an array A[] consisting of N integers from a range [1, N], the task is to calculate the count of array elements (non-distinct) that can be represented as the sum of two or more consecutive array elements. Examples: Input: a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}Output: 5Explanation:The array elements
11 min read
Modulus of all pairwise consecutive elements in an Array
Given an array of N elements. The task is to print the modulus of all of the pairwise consecutive elements. That is for all pair of consecutive elements say ((a[i], a[i+1])), print (a[i] % a[i+1]). Note: Consecutive pairs of an array of size N are (a[i], a[i+1]) for all i ranging from 0 to N-2. Exam
4 min read