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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Binary Indexed Tree or Fenwick TreeBinary Indexed Trees are used for problems where we have following types of multiple operations on a fixed sized.Prefix Operation (Sum, Product, XOR, OR, etc). Note that range operations can also be solved using prefix. For example, range sum from index L to R is prefix sum till R (included minus pr
15 min read
Square Root (Sqrt) Decomposition AlgorithmSquare Root Decomposition Technique is one of the most common query optimization techniques used by competitive programmers. This technique helps us to reduce Time Complexity by a factor of sqrt(N) The key concept of this technique is to decompose a given array into small chunks specifically of size
15+ min read
Binary LiftingBinary Lifting is a Dynamic Programming approach for trees where we precompute some ancestors of every node. It is used to answer a large number of queries where in each query we need to find an arbitrary ancestor of any node in a tree in logarithmic time.The idea behind Binary Lifting:1. Preprocess
15+ min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem