Open In App

Minimum length Subarray starting from each index with maximum OR

Last Updated : 25 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of size N. Consider all the subarrays starting at each index from [0, N – 1]. Determine the length of the smallest subarray starting from each index whose bitwise OR  is maximum.

Examples:

Input: N = 5, A = {1, 2, 3, 4, 5}
Output: {4, 3, 2, 2, 1}
Explanation: 

  • For i = 1, and size of subarray = 1, score of this subarray is 1. 
    For size = 2, the value is 1 | 2 = 3. 
    For size = 3, the value is 1 | 2 | 3 = 3.
    For size = 4, the value is 1 | 2 | 3 | 4 = 7 and 
    for size = 5, the value of this subarray is 1 | 2 | 3 | 4 | 5 = 7. 
    You can see that the maximum value is 7, and the smallest size 
    of the subarray starting at 1 with this value is of size 4. 
    So the maximum answer starting from 1st index is equal to 4.
  • For i = 2 and size = 1, the value is 2. 
    For size = 2, the value is 2 | 3 = 3. 
    For size = 3, the value is 2 | 3 | 4 = 7. 
    For size = 4, the value is 2 | 3 | 4 | 5 = 7. 
    You can see that the maximum score is 7, and the smallest size 
    of the subarray starting at 2, with this value is of size 3. 
    So the maximum answer starting from 2nd index is equal to 3.
  • For i = 3 and size = 1, the value is 3. 
    For size = 2, the value is 3 | 4 = 7. 
    For size = 3, the value is 3 | 4 | 5 = 7. 
    So for i = 3 the size is 2
  • For i = 4 and size = 1, the score is 4 and for size = 2, the score is 4 | 1 = 5. 
    So the size is equal to 2.
  • For i = 5 only one subarray is there of size 1.

Input: N = 7, A = {2, 4, 3, 1, 5, 4, 6}
Output: {3, 2, 3, 4, 3, 2, 1}

Naive Approach: To solve the problem follow the below idea:

For each index find all the subarrays starting from that index and find the smallest one with maximum bitwise OR.

Follow the given steps to solve the problem using the above approach:

  • Traverse the array using two nested for loops, to find every possible subarray
  • Calculate the OR value of every subarray and update the maximum answer found so far for the current starting index.
  • Push the minimum length subarray size, with maximum value into the answer array.
  • Return the answer array.

Below is the implementation for the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// This function is for finding the minimum
// length maximum OR subarray, for each index
vector<int> solve(int arr[], int N)
{
    vector<int> len;
 
    for (int i = 0; i < N; i++) {
        int mxor = 0, mnlen = 0, OR = 0;
        for (int j = i; j < N; j++) {
            OR = OR | arr[j];
 
            // Updating maximum value found
            // so far
            if (mxor < OR) {
                mxor = OR;
                mnlen = j - i + 1;
            }
        }
        len.push_back(mnlen);
    }
 
    return len;
}
 
// Driver's code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    vector<int> mnlen = solve(arr, N);
 
    for (int i = 0; i < N; i++)
        cout << mnlen[i] << " ";
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
 
  // This function is for finding the minimum length
  // maximum OR subarray, for each index
  static List<Integer> solve(int[] arr, int N)
  {
    List<Integer> len = new ArrayList<>();
 
    for (int i = 0; i < N; i++) {
      int mxor = 0, mnlen = 0, OR = 0;
      for (int j = i; j < N; j++) {
        OR = OR | arr[j];
 
        // Updating maximum value found so far
        if (mxor < OR) {
          mxor = OR;
          mnlen = j - i + 1;
        }
      }
      len.add(mnlen);
    }
    return len;
  }
 
  public static void main(String[] args)
  {
    int[] arr = { 1, 2, 3, 4, 5 };
    int N = arr.length;
 
    // Function call
    List<Integer> mnlen = solve(arr, N);
 
    for (int i = 0; i < N; i++) {
      System.out.print(mnlen.get(i) + " ");
    }
  }
}
 
// This code is contributed by lokesh (lokeshmvs21).


Python




# Python program for the above approach
 
# This function is for finding the minimum
# length maximum OR subarray, for each index
def solve(arr, N):
    len =  list()
 
    for i in range(0 ,N):
        mxor = 0
        mnlen = 0
        OR = 0
        for j in range(i, N):
            OR = OR | arr[j];
 
            # Updating maximum value found
            # so far
            if (mxor < OR):
                mxor = OR
                mnlen = j - i + 1
        len.append(mnlen)
 
    return len
 
# Driver's code
if __name__ == "__main__":
   
    arr = [ 1, 2, 3, 4, 5 ]
    N = len(arr)
 
    # Function call
    mnlen = solve(arr, N)
 
    for i in range(0 ,N):
        print mnlen[i],
   
  # This code is contributed by hrithikgarg03188.


C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG {
 
  // This function is for finding the minimum length
  // maximum OR subarray, for each index
  static List<int> solve(int[] arr, int N)
  {
    List<int> len = new List<int>();
 
    for (int i = 0; i < N; i++) {
      int mxor = 0, mnlen = 0, OR = 0;
      for (int j = i; j < N; j++) {
        OR = OR | arr[j];
 
        // Updating maximum value found so far
        if (mxor < OR) {
          mxor = OR;
          mnlen = j - i + 1;
        }
      }
      len.Add(mnlen);
    }
    return len;
  }
 
  public static void Main()
  {
    int[] arr = { 1, 2, 3, 4, 5 };
    int N = arr.Length;
 
    // Function call
    List<int> mnlen = solve(arr, N);
 
    for (int i = 0; i < N; i++) {
      Console.Write(mnlen[i] + " ");
    }
  }
}
 
// This code is contributed by Taranpreet


Javascript




<script>
 
// JavaScript code to implement the above approach
 
  // This function is for finding the minimum length
  // maximum OR subarray, for each index
  function solve(arr, N)
  {
    let len = new Array();
 
    for (let i = 0; i < N; i++) {
      let mxor = 0, mnlen = 0, OR = 0;
      for (let j = i; j < N; j++) {
        OR = OR | arr[j];
 
        // Updating maximum value found so far
        if (mxor < OR) {
          mxor = OR;
          mnlen = j - i + 1;
        }
      }
      len.push(mnlen);
    }
    return len;
  }
 
// Driver Code
 
    let arr = [ 1, 2, 3, 4, 5 ];
    let N = arr.length;
 
    // Function call
    let mnlen = solve(arr, N);
 
    for (let i = 0; i < N; i++) {
      document.write(mnlen[i] + " ");
    }
 
// This code is contributed by sanjoy_62.
</script>


Output

4 3 2 2 1 

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

Efficient approach: To solve the problem follow the below idea:

By observing the functionality of OR, bits can only be turned on using 1. So, start from the end and keep track of the minimum index that will keep the particular bit as a set and then we take a max of all the indexes that contain the set bits.

Follow the given steps to solve the problem using the above approach:

  • Traverse the given array from end and update the minimum index of every set bit in the current element
  • Take the maximum index of all the set bits so far, as the answer for the current index.
  • Return the answer array

Below is the implementation for the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// This function is for finding the
// minimum length maximum OR subarray
vector<int> solve(int arr[], int N)
{
    vector<int> ans;
    vector<int> nearest(32, -1);
    for (int i = N - 1; i >= 0; i--) {
        for (int j = 0; j < 32; j++) {
 
            // Nearest index where jth
            // bit is set
            if (arr[i] & (1 << j))
                nearest[j] = i;
        }
 
        int last_set_bit_index = i;
 
        // Finding Maximum index of all set bits
        for (int j = 0; j < 32; j++)
            last_set_bit_index
                = max(last_set_bit_index, nearest[j]);
 
        ans.push_back(last_set_bit_index - i + 1);
    }
 
    // Reversing the answer vector
    reverse(ans.begin(), ans.end());
    return ans;
}
 
// Driver code
int main()
{
 
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    vector<int> mnlen = solve(arr, N);
    for (int i = 0; i < N; i++)
        cout << mnlen[i] << " ";
    return 0;
}


Java




import java.io.*;
import java.util.*;
 
class GFG {
 
    // This function is for finding the minimum length
    // maximum OR subarray, for each index
    static List<Integer> solve(int[] arr, int N)
    {
        List<Integer> ans = new ArrayList<>();
        int[] nearest = new int[32];
        for (int i = N - 1; i >= 0; i--) {
            for (int j = 0; j < 32; j++) {
 
                // Nearest index where jth
                // bit is set
                int x = (int)Math.pow(2, j) & arr[i];
                if (x != 0)
                    nearest[j] = i;
            }
 
            int last_set_bit_index = i;
 
            // Finding Maximum index of all set bits
            for (int j = 0; j < 32; j++)
                last_set_bit_index = Math.max(
                    last_set_bit_index, nearest[j]);
 
            ans.add(last_set_bit_index - i + 1);
        }
        Collections.reverse(ans);
        return ans;
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        int N = arr.length;
 
        // Function call
        List<Integer> mnlen = solve(arr, N);
 
        for (int i = 0; i < N; i++) {
            System.out.print(mnlen.get(i) + " ");
        }
    }
}
 
//  This code is contributed by garg28harsh.


Python3




# Python program for the above approach
 
# This function is for finding the
# minimum length maximum OR subarray
def solve (arr, N):
    ans = [];
    nearest = [-1] * 32
    for i in range(N - 1, -1, -1):
        for j in range(32):
 
            # Nearest index where jth
            # bit is set
            if (arr[i] & (1 << j)):
                nearest[j] = i;
         
 
        last_set_bit_index = i;
 
        # Finding Maximum index of all set bits
        for j in range(32):
            last_set_bit_index = max(last_set_bit_index, nearest[j]);
 
        ans.append(last_set_bit_index - i + 1);
     
    # Reversing the answer vector
    ans.reverse();
    return ans;
 
# Driver code
arr = [1, 2, 3, 4, 5];
N = len(arr)
 
# Function call
mnlen = solve(arr, N);
for i in range(N):
    print(mnlen[i], end=" ");
 
# This code is contributed by Saurabh Jaiswal


C#




// C# implementation of above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  // This function is for finding the
// minimum length maximum OR subarray
static List<int> solve(int[] arr, int N)
{
     List<int> ans = new List<int>();
    int[] nearest = new int[32];
    for(int i =0; i<32; i++)
    {
        nearest[i] = -1;
    }
     
    for (int i = N - 1; i >= 0; i--) {
        for (int j = 0; j < 32; j++) {
  
            // Nearest index where jth
            // bit is set
            if ((arr[i]  & (1 << j)) != 0)
                nearest[j] = i;
        }
  
        int last_set_bit_index = i;
  
        // Finding Maximum index of all set bits
        for (int j = 0; j < 32; j++)
            last_set_bit_index
                = Math.Max(last_set_bit_index, nearest[j]);
  
        ans.Add(last_set_bit_index - i + 1);
    }
  
    // Reversing the answer vector
    ans.Reverse();
    return ans;
}
  // Driver Code
  public static void Main()
  {
     int[] arr = { 1, 2, 3, 4, 5 };
    int N = arr.Length;
  
    // Function call
    List<int> mnlen = solve(arr, N);
    for (int i = 0; i < N; i++)
        Console.Write(mnlen[i] + " ");
  }
}
 
// This code is contributed by code_hunt.


Javascript




<script>
    // JavaScript program for the above approach
 
    // This function is for finding the
    // minimum length maximum OR subarray
    const solve = (arr, N) => {
        let ans = [];
        let nearest = new Array(32).fill(-1);
        for (let i = N - 1; i >= 0; i--) {
            for (let j = 0; j < 32; j++) {
 
                // Nearest index where jth
                // bit is set
                if (arr[i] & (1 << j))
                    nearest[j] = i;
            }
 
            let last_set_bit_index = i;
 
            // Finding Maximum index of all set bits
            for (let j = 0; j < 32; j++)
                last_set_bit_index
                    = Math.max(last_set_bit_index, nearest[j]);
 
            ans.push(last_set_bit_index - i + 1);
        }
 
        // Reversing the answer vector
        ans.reverse();
        return ans;
    }
 
    // Driver code
    let arr = [1, 2, 3, 4, 5];
    let N = arr.length;
 
    // Function call
    let mnlen = solve(arr, N);
    for (let i = 0; i < N; i++)
        document.write(`${mnlen[i]} `);
 
    // This code is contributed by rakeshsahni
 
</script>


Output

4 3 2 2 1 

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads