Rearrange an array such that product of every two consecutive elements is a multiple of 4

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: