Skip to content
Related Articles

Related Articles

Improve Article

Length of longest subarray with product equal to a power of 2

  • Last Updated : 14 Jun, 2021

Given an array arr[] consisting of N positive integers, the task is to find the length of the longest subarray having a product of elements of that subarray equal to a perfect power of 2.

Examples:

Input: arr[] = {2, 5, 4, 4, 6}
Output: 2
Explanation:
The subarray having maximum length whose product is perfect power of 2 is {4, 4}.
Product = 4 * 4 = 16, which is a perfect power of 2.

Input: arr[] = {2, 5, 4, 6, 8, 8, 2}
Output: 3
Explanation:
The subarray having maximum length whose product is perfect power of 2 is {8, 8, 2}.
Product = 8 * 8 * 2 = 128, which is a perfect power of 2.

 

Naive Approach: The simplest approach is to generate all possible subarrays of the given array and check if the product of the elements of any subarray is a perfect power of 2 or not. If found to be true, then update the maximum length to the length of this subarray. Finally, print the maximum length of the subarray obtained after checking all possible subarray. 



Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is based upon the fact that for any number to be a power of 2 it can be also be expressed as the product of numbers having perfect power of 2. Therefore, the idea is to use the Kadane’s Algorithm to find the maximum length of the subarray having all elements having perfect power of 2. Below are the steps:

  • Initialize maxLength and ans as 0 that will store the maximum length of subarrays and a resultant maximum length of subarray respectively.
  • Traverse the given array and do the following:
  • Print the value of ans as the maximum length after the above steps.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether a number
// is power of 2 or not
bool isPower(int x)
{
    return (x && (!(x & (x - 1))));
}
 
// Function to find maximum length
// subarray having product of element
// as a perfect power of 2
int maximumlength(int arr[], int N)
{
    // Stores current subarray length
    int max_length = 0;
 
    // Stores maximum subarray length
    int max_len_subarray = 0;
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
 
        // If arr[i] is power of 2
        if (isPower(arr[i]) == 1) {
 
            // Increment max_length
            max_length++;
 
            // Update max_len_subarray
            max_len_subarray
                = max(max_length,
                      max_len_subarray);
        }
 
        // Otherwise
        else {
            max_length = 0;
        }
    }
 
    // Print the maximum length
    cout << max_len_subarray;
}
 
// Driver Code
int main()
{
    // Given arr[]
    int arr[] = { 2, 5, 4, 6, 8, 8, 2 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maximumlength(arr, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to check whether a number
// is power of 2 or not
public static boolean isPower(int x)
{
    if (x != 0 && (x & (x - 1)) == 0)
        return true;
         
    return false;
}
 
// Function to find maximum length
// subarray having product of element
// as a perfect power of 2
public static void maximumlength(int arr[],
                                 int N)
{
     
    // Stores current subarray length
    int max_length = 0;
 
    // Stores maximum subarray length
    int max_len_subarray = 0;
 
    // Traverse the given array
    for(int i = 0; i < N; i++)
    {
         
        // If arr[i] is power of 2
        if (isPower(arr[i]))
        {
             
            // Increment max_length
            max_length++;
 
            // Update max_len_subarray
            max_len_subarray = Math.max(max_length,
                                        max_len_subarray);
        }
 
        // Otherwise
        else
        {
            max_length = 0;
        }
    }
 
    // Print the maximum length
    System.out.println(max_len_subarray);
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given arr[]
    int arr[] = { 2, 5, 4, 6, 8, 8, 2 };
 
    int N = arr.length;
 
    // Function Call
    maximumlength(arr, N);
}
}
 
// This code is contributed by hemanthswarna1506

Python3




# Python3 program for the
# above approach
 
# Function to check whether
# a number is power of 2
# or not
def isPower(x):
   
    if (x != 0 and
       (x & (x - 1)) == 0):
        return True;
 
    return False;
 
# Function to find maximum
# length subarray having
# product of element
# as a perfect power of 2
def maximumlength(arr, N):
   
    # Stores current
    # subarray length
    max_length = 0;
 
    # Stores maximum
    # subarray length
    max_len_subarray = 0;
 
    # Traverse the given array
    for i in range(N):
 
        # If arr[i] is power of 2
        if (isPower(arr[i])):
 
            # Increment max_length
            max_length += 1;
 
            # Update max_len_subarray
            max_len_subarray = max(max_length,
                                   max_len_subarray);
 
        # Otherwise
        else:
            max_length = 0;
 
    # Prthe maximum length
    print(max_len_subarray);
 
# Driver Code
if __name__ == '__main__':
   
    # Given arr
    arr = [2, 5, 4,
           6, 8, 8, 2];
 
    N = len(arr);
 
    # Function Call
    maximumlength(arr, N);
 
# This code is contributed by gauravrajput1

C#




// C# program for the above approach
using System;
  
class GFG{
      
// Function to check whether a number
// is power of 2 or not
public static bool isPower(int x)
{
    if (x != 0 && (x & (x - 1)) == 0)
        return true;
          
    return false;
}
  
// Function to find maximum length
// subarray having product of element
// as a perfect power of 2
public static void maximumlength(int[] arr,
                                 int N)
{
     
    // Stores current subarray length
    int max_length = 0;
  
    // Stores maximum subarray length
    int max_len_subarray = 0;
  
    // Traverse the given array
    for(int i = 0; i < N; i++)
    {
         
        // If arr[i] is power of 2
        if (isPower(arr[i]))
        {
             
            // Increment max_length
            max_length++;
  
            // Update max_len_subarray
            max_len_subarray = Math.Max(max_length,
                                        max_len_subarray);
        }
  
        // Otherwise
        else
        {
            max_length = 0;
        }
    }
  
    // Print the maximum length
    Console.WriteLine(max_len_subarray);
}
  
// Driver Code
public static void Main()
{
     
    // Given arr[]
    int[] arr = { 2, 5, 4, 6, 8, 8, 2 };
  
    int N = arr.Length;
  
    // Function Call
    maximumlength(arr, N);
}
}
 
// This code is contributed by sanjoy_62

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to check whether a number
// is power of 2 or not
function isPower(x)
{
    return (x && (!(x & (x - 1))));
}
 
// Function to find maximum length
// subarray having product of element
// as a perfect power of 2
function maximumlength(arr, N)
{
    // Stores current subarray length
    var max_length = 0;
 
    // Stores maximum subarray length
    var max_len_subarray = 0;
 
    // Traverse the given array
    for (var i = 0; i < N; i++) {
 
        // If arr[i] is power of 2
        if (isPower(arr[i]) == 1) {
 
            // Increment max_length
            max_length++;
 
            // Update max_len_subarray
            max_len_subarray
                = Math.max(max_length,
                      max_len_subarray);
        }
 
        // Otherwise
        else {
            max_length = 0;
        }
    }
 
    // Print the maximum length
    document.write( max_len_subarray);
}
 
// Driver Code
 
// Given arr[]
var arr = [2, 5, 4, 6, 8, 8, 2];
var N = arr.length;
 
// Function Call
maximumlength(arr, N);
 
</script>
Output
3

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :