Minimum length Subarray starting from each index with maximum OR
Last Updated :
25 Oct, 2022
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>
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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Find smallest Subarray with Maximum Xor starting from each index
Given an array A[] consisting of N elements, the task is to find the minimum length of the subarray starting from each index and the bitwise OR value is the maximum among all possible subarrays starting from that index. Examples: Input: A[] = [4, 5, 2, 9, 11]Output: [4, 3, 2, 2, 1]Explanation: For i
10 min read
Find subarray of Length K with Maximum Peak
Given an array arr[] of length n and a positive integer K, we have to find a subarray of length K which has maximum peak inside in it. Peaks of the segment [l, r] are those indexes such that l < i < r, a[i-1] < a[i] and a[i+1] < a[i]. Note: The boundary indexes l and r for the segment ar
8 min read
Find Subarray whose end points don't have maximum or minimum
Given an array nums[] of length N which contains integers, the task is to find a subarray such that the first and the last element of that subarray is neither the maximum nor minimum element present in that subarray and print the starting and ending index if there is such a subarray otherwise print
11 min read
Minimum size Subarray with maximum sum in non-increasing order
Given an array arr, the task is to find a subarray of the array elements whose sum is strictly greater than the rest of the elements. The size of the subarray should be minimum and the sum should be maximum and it must be in non-increasing order.Examples: Input: arr = [7, 6, 13, 12, 11] Output: 13 1
6 min read
Maximum MEX from all subarrays of length K
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum MEX from all subarrays of length K. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {3, 2, 1, 4}, K = 2Output: 3Explanation:All subarrays havin
8 min read
Number of subarrays whose minimum and maximum are same
Given an array of n integers, find the no of subarrays whose minimal and maximum elements are the same. A subarray is defined as a non-empty sequence of consecutive elements. Examples: Input: 2 3 1 1 Output: 5Explanation: The subarrays are (2), (3), (1), (1) and (1, 1) Input: 2 4 5 3 3 3Output: 9Exp
8 min read
Maximum range subarray for each index in Array such that A[i] = min(A[L], A[L+1], ⦠A[R])
Given an array arr[] of N distinct integers, the task is to calculate for each index i (1â¤iâ¤N) a range [L, R] such that arr[i] = min(arr[L], arr[L+1], ⦠arr[R]), where Lâ¤iâ¤R and R-L is maximized. Examples: Input: N = 3, arr[] = {1, 3, 2}Output: 1 32 22 3Explanation: 1 is minimum in the range [1, 3]3
11 min read
Sum of minimum and maximum elements of all subarrays of size k.
Given an array of both positive and negative integers, the task is to compute sum of minimum and maximum elements of all sub-array of size k.Examples: Input : arr[] = {2, 5, -1, 7, -3, -1, -2} K = 4Output : 18Explanation : Subarrays of size 4 are : {2, 5, -1, 7}, min + max = -1 + 7 = 6 {5, -1, 7, -3
15+ min read
Count maximum non-overlapping subarrays with given sum
Given an array arr[] consisting of N integers and an integer target, the task is to find the maximum number of non-empty non-overlapping subarrays such that the sum of array elements in each subarray is equal to the target. Examples: Input: arr[] = {2, -1, 4, 3, 6, 4, 5, 1}, target = 6Output: 3Expla
7 min read
Maximize the Sum of Minimum in each Group of size K
Given an array nums[] of size N and a positive integer K, divide the elements of the array into N/K groups, each of size K such that the sum of the smallest elements in each group is maximized. Examples: Input: nums = {1,4,3,2}, K = 2Output: 4Explanation: All possible groupings (ignoring the orderin
8 min read