Open In App

Minimize division by 2 to make Array of alternate odd and even elements

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N positive integers. The task is to find the minimum number of operations required to make the array containing alternating odd and even numbers. In one operation, any array element can be replaced by its half (i.e arr[i]/2).

Examples:

Input: N=6, arr = [4, 10, 6, 6, 2, 7]
Output: 2
Explanation: We can divide elements at index 1 and 3 
by 2 to get array [4, 5, 6, 3, 2, 7], which is off alternate parity.

Input: N=6, arr = [3, 10, 7, 18, 9, 66]
Output:  0
Explanation: No operations are needed as array is already alternative.

Approach: To solve the problem use the following idea:

Try both possibilities of the array start with an odd number as well as even number and print the minimum of the two possibilities as the answer.

Follow the steps to solve the problem:

  • Declare and Initialize two variables result1 and result2 with 0.
  • Iterate the array for all indices from 0 till N – 1.
    • If the element at the even index is odd then
      • Divide the element by 2 and increment the result1 until it becomes even.
    • If the element at the odd index is even then
      • Divide the element by 2 and increment the result1 until it becomes odd.
  • Iterate the array for all indices from 0 till N – 1.
    • If the element at the even index is even then
      • Divide the element by 2 and increment the result2 until it becomes odd.
    • If the element at the odd index is odd then
      • Divide the element by 2 and increment the result2 until it becomes even.
  • print minimum of result1 and result2.

Below is the implementation for the above approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number of operations
int minOperations(int arr[], int n)
{
    // Two variables to count number of operations
    int result1 = 0, result2 = 0;
 
    // For array starting with even element
    for (int i = 0; i < n; i++) {
        int element = arr[i];
 
        // For even indices
        if (i % 2 == 0) {
 
            // If element is already even
            if (element % 2 == 0)
                continue;
 
            // Otherwise keep dividing by 2
            // till element becomes even
            else {
                while (element % 2 == 1) {
                    element /= 2;
                    result1++;
                }
            }
        }
 
        // For odd indices
        else {
 
            // If element is already odd
            if (element % 2 == 1)
                continue;
 
            // Otherwise keep dividing by 2
            // till element becomes odd
            else {
                while (element % 2 == 0) {
                    element /= 2;
                    result1++;
                }
            }
        }
    }
 
    // For array starting from odd element
    for (int i = 0; i < n; i++) {
        int element = arr[i];
 
        // For even indices
        if (i % 2 == 0) {
 
            // If element is already odd
            if (element % 2 == 1)
                continue;
 
            // Otherwise keep dividing by 2
            // till element becomes odd
            else {
                while (element % 2 == 0) {
                    element /= 2;
                    result2++;
                }
            }
        }
 
        // For odd indices
        else {
 
            // If element is already even
            if (element % 2 == 0)
                continue;
 
            // Otherwise keep dividing by 2
            // till element becomes even
            else {
                while (element % 2 == 1) {
                    element /= 2;
                    result2++;
                }
            }
        }
    }
    return min(result1, result2);
}
 
// Driver code
int main()
{
    int N = 6;
    int arr[] = { 4, 10, 6, 6, 2, 3 };
 
    // Function call
    cout << minOperations(arr, N);
    return 0;
}


Java




// Java code to implement the approach
import java.io.*;
 
class GFG
{
 
  // Function to find the minimum number of operations
  public static int minOperations(int arr[], int n)
  {
    // Two variables to count number of operations
    int result1 = 0, result2 = 0;
 
    // For array starting with even element
    for (int i = 0; i < n; i++) {
      int element = arr[i];
 
      // For even indices
      if (i % 2 == 0) {
 
        // If element is already even
        if (element % 2 == 0)
          continue;
 
        // Otherwise keep dividing by 2
        // till element becomes even
        else {
          while (element % 2 == 1) {
            element /= 2;
            result1++;
          }
        }
      }
 
      // For odd indices
      else {
 
        // If element is already odd
        if (element % 2 == 1)
          continue;
 
        // Otherwise keep dividing by 2
        // till element becomes odd
        else {
          while (element % 2 == 0) {
            element /= 2;
            result1++;
          }
        }
      }
    }
 
    // For array starting from odd element
    for (int i = 0; i < n; i++) {
      int element = arr[i];
 
      // For even indices
      if (i % 2 == 0) {
 
        // If element is already odd
        if (element % 2 == 1)
          continue;
 
        // Otherwise keep dividing by 2
        // till element becomes odd
        else {
          while (element % 2 == 0) {
            element /= 2;
            result2++;
          }
        }
      }
 
      // For odd indices
      else {
 
        // If element is already even
        if (element % 2 == 0)
          continue;
 
        // Otherwise keep dividing by 2
        // till element becomes even
        else {
          while (element % 2 == 1) {
            element /= 2;
            result2++;
          }
        }
      }
    }
    return Math.min(result1, result2);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int N = 6;
    int arr[] = { 4, 10, 6, 6, 2, 3 };
 
    // Function call
    System.out.print(minOperations(arr, N));
  }
}
 
// This code is contributed by Rohit Pradhan


Python3




# python3 code to implement the approach
 
# Function to find the minimum number of operations
def minOperations(arr, n):
 
    # Two variables to count number of operations
    result1 = 0
    result2 = 0
 
    # For array starting with even element
    for i in range(0, n):
        element = arr[i]
 
        # For even indices
        if (i % 2 == 0):
 
            # If element is already even
            if (element % 2 == 0):
                continue
 
            # Otherwise keep dividing by 2
            # till element becomes even
            else:
                while (element % 2 == 1):
                    element //= 2
                    result1 += 1
 
        # For odd indices
        else:
 
            # If element is already odd
            if (element % 2 == 1):
                continue
 
            # Otherwise keep dividing by 2
            # till element becomes odd
            else:
                while (element % 2 == 0):
                    element //= 2
                    result1 += 1
 
    # For array starting from odd element
    for i in range(0, n):
        element = arr[i]
 
        # For even indices
        if (i % 2 == 0):
 
            # If element is already odd
            if (element % 2 == 1):
                continue
 
            # Otherwise keep dividing by 2
            # till element becomes odd
            else:
                while (element % 2 == 0):
                    element //= 2
                    result2 += 1
 
        # For odd indices
        else:
 
            # If element is already even
            if (element % 2 == 0):
                continue
 
            # Otherwise keep dividing by 2
            # till element becomes even
            else:
                while (element % 2 == 1):
                    element //= 2
                    result2 += 1
 
    return min(result1, result2)
 
# Driver code
if __name__ == "__main__":
 
    N = 6
    arr = [4, 10, 6, 6, 2, 3]
 
    # Function call
    print(minOperations(arr, N))
 
    # This code is contributed by rakeshsahni


C#




// C# code to implement the approach
using System;
class GFG {
 
  // Function to find the minimum number of operations
  public static int minOperations(int[] arr, int n)
  {
     
    // Two variables to count number of operations
    int result1 = 0, result2 = 0;
 
    // For array starting with even element
    for (int i = 0; i < n; i++) {
      int element = arr[i];
 
      // For even indices
      if (i % 2 == 0) {
 
        // If element is already even
        if (element % 2 == 0)
          continue;
 
        // Otherwise keep dividing by 2
        // till element becomes even
        else {
          while (element % 2 == 1) {
            element /= 2;
            result1++;
          }
        }
      }
 
      // For odd indices
      else {
 
        // If element is already odd
        if (element % 2 == 1)
          continue;
 
        // Otherwise keep dividing by 2
        // till element becomes odd
        else {
          while (element % 2 == 0) {
            element /= 2;
            result1++;
          }
        }
      }
    }
 
    // For array starting from odd element
    for (int i = 0; i < n; i++) {
      int element = arr[i];
 
      // For even indices
      if (i % 2 == 0) {
 
        // If element is already odd
        if (element % 2 == 1)
          continue;
 
        // Otherwise keep dividing by 2
        // till element becomes odd
        else {
          while (element % 2 == 0) {
            element /= 2;
            result2++;
          }
        }
      }
 
      // For odd indices
      else {
 
        // If element is already even
        if (element % 2 == 0)
          continue;
 
        // Otherwise keep dividing by 2
        // till element becomes even
        else {
          while (element % 2 == 1) {
            element /= 2;
            result2++;
          }
        }
      }
    }
    return Math.Min(result1, result2);
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    int N = 6;
    int[] arr = { 4, 10, 6, 6, 2, 3 };
 
    // Function call
    Console.Write(minOperations(arr, N));
  }
}
 
// This code is contributed by code_hunt.


Javascript




<script>
        // JS code to implement the approach
 
 
        // Function to find the minimum number of operations
        function minOperations(arr, n) {
            // Two variables to count number of operations
            let result1 = 0, result2 = 0;
 
            // For array starting with even element
            for (let i = 0; i < n; i++) {
                let element = arr[i];
 
                // For even indices
                if (i % 2 == 0) {
 
                    // If element is already even
                    if (element % 2 == 0)
                        continue;
 
                    // Otherwise keep dividing by 2
                    // till element becomes even
                    else {
                        while (element % 2 == 1) {
                            element = Math.floor(element / 2);
                            result1++;
                        }
                    }
                }
 
                // For odd indices
                else {
 
                    // If element is already odd
                    if (element % 2 == 1)
                        continue;
 
                    // Otherwise keep dividing by 2
                    // till element becomes odd
                    else {
                        while (element % 2 == 0) {
                            element = Math.floor(element / 2);
                            result1++;
                        }
                    }
                }
            }
 
            // For array starting from odd element
            for (let i = 0; i < n; i++) {
                let element = arr[i];
 
                // For even indices
                if (i % 2 == 0) {
 
                    // If element is already odd
                    if (element % 2 == 1)
                        continue;
 
                    // Otherwise keep dividing by 2
                    // till element becomes odd
                    else {
                        while (element % 2 == 0) {
                            element = Math.floor(element / 2);
                            result2++;
                        }
                    }
                }
 
                // For odd indices
                else {
 
                    // If element is already even
                    if (element % 2 == 0)
                        continue;
 
                    // Otherwise keep dividing by 2
                    // till element becomes even
                    else {
                        while (element % 2 == 1) {
                            element = Math.floor(element / 2);
                            result2++;
                        }
                    }
                }
            }
            return Math.min(result1, result2);
        }
 
        // Driver code
 
        let N = 6;
        let arr = [4, 10, 6, 6, 2, 3];
 
        // Function call
        document.write(minOperations(arr, N));
 
    </script>


PHP




<?php
 
// Function to find the minimum number of operations
function minOperations($arr, $n)
{
    // Two variables to count number of operations
    $result1 = 0;
    $result2 = 0;
 
    // For array starting with even element
    for ($i = 0; $i < $n; $i++) {
        $element = $arr[$i];
 
        // For even indices
        if ($i % 2 == 0) {
 
            // If element is already even
            if ($element % 2 == 0)
                continue;
 
            // Otherwise keep dividing by 2
            // till element becomes even
            else {
                while ($element % 2 == 1) {
                    $element /= 2;
                    $result1++;
                }
            }
        }
 
        // For odd indices
        else {
 
            // If element is already odd
            if ($element % 2 == 1)
                continue;
 
            // Otherwise keep dividing by 2
            // till element becomes odd
            else {
                while ($element % 2 == 0) {
                    $element /= 2;
                    $result1++;
                }
            }
        }
    }
 
    // For array starting from odd element
    for ($i = 0; $i < $n; $i++) {
        $element = $arr[$i];
 
        // For even indices
        if ($i % 2 == 0) {
 
            // If element is already odd
            if ($element % 2 == 1)
                continue;
 
            // Otherwise keep dividing by 2
            // till element becomes odd
            else {
                while ($element % 2 == 0) {
                    $element /= 2;
                    $result2++;
                }
            }
        }
 
        // For odd indices
        else {
 
            // If element is already even
            if ($element % 2 == 0)
                continue;
 
            // Otherwise keep dividing by 2
            // till element becomes even
            else {
                while ($element % 2 == 1) {
                    $element /= 2;
                    $result2++;
                }
            }
        }
    }
    return min($result1, $result2);
}
 
// Driver code
$N = 6;
$arr = array(4, 10, 6, 6, 2, 3);
 
// Function call
echo minOperations($arr, $N);
  // This code is contributed by Kanishka Gupta
?>


Output

2






Time Complexity: O(N * log(max(arr[i]))),  where max(arr[i]) is maximum element in array.
Auxiliary Space: O(1)

Using Brute Force In Python:

Approach:

  • We initialize a variable min_ops to inf (infinity) and n to the length of the array.
  • We iterate through all pairs of indices (i, j) in the array and create a copy of the original array arr as temp_arr. We also initialize a variable count to keep track of the number of operations required.
  • We check if the elements at indices i and j are even. If they are, we divide them by 2 and increment the count variable.
  • We check if the resulting temp_arr has alternate parity (i.e., if the parity of the element at index k is the same as k%2 for all k in the range 0 to n-1). If it does, we update the min_ops variable to the minimum of its current value and the count variable.
  • We return the min_ops variable if it has been updated during the iteration, else we return 0 indicating that no operations were required.

C++




#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
 
int alternate_array(vector<int>& arr) {
    int n = arr.size();
    int min_ops = INT_MAX;
 
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            vector<int> temp_arr = arr;
            int count = 0;
 
            if (temp_arr[i] % 2 == 0) {
                temp_arr[i] /= 2;
                count += 1;
            }
            if (temp_arr[j] % 2 == 0) {
                temp_arr[j] /= 2;
                count += 1;
            }
 
            // Check if the modified array meets the alternating condition
            bool is_alternating = true;
            for (int k = 0; k < n; ++k) {
                if (k % 2 == 0 && temp_arr[k] % 2 != 0) {
                    is_alternating = false;
                    break;
                }
                if (k % 2 != 0 && temp_arr[k] % 2 == 0) {
                    is_alternating = false;
                    break;
                }
            }
 
            if (is_alternating) {
                min_ops = min(min_ops, count);
            }
        }
    }
 
    return (min_ops != INT_MAX) ? min_ops : 0;
}
 
int main() {
    vector<int> arr1 = {4, 10, 6, 6, 2, 7};
    cout << alternate_array(arr1) << endl;  // Output: 2
 
    vector<int> arr2 = {3, 10, 7, 18, 9, 66};
    cout << alternate_array(arr2) << endl;  // Output: 0
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class AlternateArray {
    // Function to find the minimum number of operations to make an array alternate
    static int alternateArray(List<Integer> arr) {
        int n = arr.size();
        int minOps = Integer.MAX_VALUE;
 
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                // Create a copy of the original array to perform operations
                List<Integer> tempArr = new ArrayList<>(arr);
                int count = 0;
 
                // If the i-th element is even, divide it by 2 and increment the count
                if (tempArr.get(i) % 2 == 0) {
                    tempArr.set(i, tempArr.get(i) / 2);
                    count += 1;
                }
                // If the j-th element is even, divide it by 2 and increment the count
                if (tempArr.get(j) % 2 == 0) {
                    tempArr.set(j, tempArr.get(j) / 2);
                    count += 1;
                }
 
                // Check if the modified array meets the alternating condition
                boolean isAlternating = true;
                for (int k = 0; k < n; ++k) {
                    if (k % 2 == 0 && tempArr.get(k) % 2 != 0) {
                        // If even-indexed elements are not even, it's not alternating
                        isAlternating = false;
                        break;
                    }
                    if (k % 2 != 0 && tempArr.get(k) % 2 == 0) {
                        // If odd-indexed elements are not odd, it's not alternating
                        isAlternating = false;
                        break;
                    }
                }
 
                // If the modified array is alternating, update minOps
                if (isAlternating) {
                    minOps = Math.min(minOps, count);
                }
            }
        }
 
        // If minOps remains at its initial value, return 0; otherwise, return minOps
        return (minOps != Integer.MAX_VALUE) ? minOps : 0;
    }
 
    public static void main(String[] args) {
        // Test case 1
        List<Integer> arr1 = new ArrayList<>();
        arr1.add(4);
        arr1.add(10);
        arr1.add(6);
        arr1.add(6);
        arr1.add(2);
        arr1.add(7);
        System.out.println(alternateArray(arr1));  // Output: 2
 
        // Test case 2
        List<Integer> arr2 = new ArrayList<>();
        arr2.add(3);
        arr2.add(10);
        arr2.add(7);
        arr2.add(18);
        arr2.add(9);
        arr2.add(66);
        System.out.println(alternateArray(arr2));  // Output: 0
    }
}


Python3




def alternate_array(arr):
    n = len(arr)
    min_ops = float('inf')
    for i in range(n):
        for j in range(i+1, n):
            temp_arr = arr[:]
            count = 0
            if temp_arr[i] % 2 == 0:
                temp_arr[i] //= 2
                count += 1
            if temp_arr[j] % 2 == 0:
                temp_arr[j] //= 2
                count += 1
            if all(temp_arr[k] % 2 == k % 2 for k in range(n)):
                min_ops = min(min_ops, count)
    return min_ops if min_ops != float('inf') else 0
 
# Example usage
arr1 = [4, 10, 6, 6, 2, 7]
n1 = len(arr1)
print(alternate_array(arr1))  # Output: 2
 
arr2 = [3, 10, 7, 18, 9, 66]
n2 = len(arr2)
print(alternate_array(arr2))  # Output: 0


C#




using System;
using System.Collections.Generic;
 
class Program
{
    static int AlternateArray(List<int> arr)
    {
        int n = arr.Count;
        int minOps = int.MaxValue;
 
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                List<int> tempArr = new List<int>(arr);
                int count = 0;
 
                if (tempArr[i] % 2 == 0)
                {
                    tempArr[i] /= 2;
                    count += 1;
                }
                if (tempArr[j] % 2 == 0)
                {
                    tempArr[j] /= 2;
                    count += 1;
                }
 
                // Check if the modified array meets the alternating condition
                bool isAlternating = true;
                for (int k = 0; k < n; k++)
                {
                    if (k % 2 == 0 && tempArr[k] % 2 != 0)
                    {
                        isAlternating = false;
                        break;
                    }
                    if (k % 2 != 0 && tempArr[k] % 2 == 0)
                    {
                        isAlternating = false;
                        break;
                    }
                }
 
                if (isAlternating)
                {
                    minOps = Math.Min(minOps, count);
                }
            }
        }
 
        return (minOps != int.MaxValue) ? minOps : 0;
    }
 
    static void Main()
    {
        List<int> arr1 = new List<int> { 4, 10, 6, 6, 2, 7 };
        Console.WriteLine(AlternateArray(arr1));  // Output: 2
 
        List<int> arr2 = new List<int> { 3, 10, 7, 18, 9, 66 };
        Console.WriteLine(AlternateArray(arr2));  // Output: 0
    }
}


Javascript




function GFG(arr) {
    const n = arr.length;
    // Initialize minOps with positive infinity
    let minOps = Infinity;
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            const tempArr = [...arr];
            // Create a copy of the original array
            let count = 0;
            if (tempArr[i] % 2 === 0) {
                tempArr[i] /= 2;
                count++;
            }
            if (tempArr[j] % 2 === 0) {
                tempArr[j] /= 2;
                count++;
            }
            // Check if all elements in tempArr have the
            // same parity as their index
            if (tempArr.every((value, index) => value % 2 === index % 2)) {
                minOps = Math.min(minOps, count);
            }
        }
    }
    return minOps !== Infinity ? minOps : 0;
}
// Example usage
const arr1 = [4, 10, 6, 6, 2, 7];
console.log(GFG(arr1)); // Output: 2
const arr2 = [3, 10, 7, 18, 9, 66];
console.log(GFG(arr2)); // Output: 0


Output

2
0






 time complexity: O(N^3) 
space complexity: O(N) 



Last Updated : 07 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads