Print the Longest Subarray whose Bitwise AND is maximum
Last Updated :
14 Sep, 2023
Given a positive integer array arr[] of size N, the task is to print the longest non-empty subarray whose bitwise AND is maximum in the array.
Examples:
Input: arr[ ] = {1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7}
Output: 7, 7, 7, 7
Explanation: The maximum Bitwise AND is 7 and the longest subarray whose bitwise AND is 7 is from index 8 to index 11.
Input: arr[ ]={3, 2, 6, 9, 4}
Output: 9
Naive Approach
The idea is to find all subarray and in those subarrays pick those subarrays which has maximum Bitwise AND. After that return/print that subarray which has the longest length
Steps to implement-
- Declare a variable temp to store the maximum BITWISE AND.
- Declare a vector ans to store final answer
- Run two loops to find all subarrays
- Simultaneously find the length of subarray and BIWISE AND of all the values of the subarray
- If any subarray has BITWISE AND more than previously found maximum BITWISE AND, then store this subarray in the vector after removing previously stored elements
- If any subarray has BITWISE AND equal to the previously found maximum BITWISE AND, then check the length of this subarray and previously stored subarray.
- If its length is more than the previously stored subarray then store this subarray in the vector after removing previously stored elements
Code-
C++
// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
// Function to find the length of the
// longest subarray whose bitwise AND is maximum
int longestSubarray(vector<int>& arr, int N)
{
// To store largest BITWISE AND
int temp = INT_MIN;
// To store answer
vector<int> ans;
// To find all subarray
for (int i = 0; i < N; i++) {
// To store BITWISE AND of Subarray
int val = INT_MIN;
// To store length of subarray
int length = 0;
for (int j = i; j < N; j++) {
// Increment the length of subarray
length++;
// Take BIWISE AND
if (val == INT_MIN) {
val = arr[j];
}
else {
val = val & arr[j];
}
// When BITWISE AND of this subarray is
// larger than previously stored BIWISE AND
if (val > temp) {
temp = val;
ans.clear();
for (int k = i; k <= j; k++) {
ans.push_back(arr[k]);
}
}
// When BITWISE AND of this subarray is
// equal to previously stored BIWISE AND
// but has larger length than previously
// stored subarray
else if (val == temp && length > ans.size()) {
temp = val;
ans.clear();
for (int k = i; k <= j; k++) {
ans.push_back(arr[k]);
}
}
}
}
// Print Final answer
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
}
// Driver Code
int main()
{
vector<int> arr
= { 1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7 };
int N = arr.size();
// Function call
longestSubarray(arr, N);
return 0;
}
Java
//Java Implementation
import java.util.ArrayList;
import java.util.List;
class GFG {
// Function to find the length of the longest subarray
// whose bitwise AND is maximum
public static void longestSubarray(List<Integer> arr, int N) {
// To store largest BITWISE AND
int temp = Integer.MIN_VALUE;
// To store answer
List<Integer> ans = new ArrayList<>();
// To find all subarrays
for (int i = 0; i < N; i++) {
// To store BITWISE AND of Subarray
int val = Integer.MIN_VALUE;
// To store length of subarray
int length = 0;
for (int j = i; j < N; j++) {
// Increment the length of subarray
length++;
// Take BITWISE AND
if (val == Integer.MIN_VALUE) {
val = arr.get(j);
} else {
val = val & arr.get(j);
}
// When BITWISE AND of this subarray is
// larger than previously stored BITWISE AND
if (val > temp) {
temp = val;
ans.clear();
for (int k = i; k <= j; k++) {
ans.add(arr.get(k));
}
}
// When BITWISE AND of this subarray is
// equal to previously stored BITWISE AND
// but has larger length than previously
// stored subarray
else if (val == temp && length > ans.size()) {
temp = val;
ans.clear();
for (int k = i; k <= j; k++) {
ans.add(arr.get(k));
}
}
}
}
// Print Final answer
for (int i = 0; i < ans.size(); i++) {
System.out.print(ans.get(i) + " ");
}
System.out.println();
}
// Driver Code
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(5);
arr.add(5);
arr.add(2);
arr.add(2);
arr.add(2);
arr.add(4);
arr.add(5);
arr.add(7);
arr.add(7);
arr.add(7);
arr.add(7);
int N = arr.size();
// Function call
longestSubarray(arr, N);
}
}
// This code is contributed by Vaibhav Nandan
Python3
# Function to find the length of the
# longest subarray whose bitwise AND is maximum
def longestSubarray(arr, N):
# To store largest BITWISE AND
temp = float('-inf')
# To store answer
ans = []
# To find all subarray
for i in range(N):
# To store BITWISE AND of Subarray
val = float('-inf')
# To store length of subarray
length = 0
for j in range(i, N):
# Increment the length of subarray
length += 1
# Take BIWISE AND
if val == float('-inf'):
val = arr[j]
else:
val = val & arr[j]
# When BITWISE AND of this subarray is
# larger than previously stored BIWISE AND
if val > temp:
temp = val
ans = arr[i:j+1]
# When BITWISE AND of this subarray is
# equal to previously stored BIWISE AND
# but has larger length than previously
# stored subarray
elif val == temp and length > len(ans):
temp = val
ans = arr[i:j+1]
# Print Final answer
for num in ans:
print(num, end=' ')
print()
# Test case
arr = [1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7]
N = len(arr)
longestSubarray(arr, N)
C#
using System;
using System.Collections.Generic;
class Program
{
// Driver Code
static void Main(string[] args)
{
List<int> arr = new List<int> { 1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7 };
int N = arr.Count;
LongestSubarray(arr, N);
}
// Function to find the length of the
// longest subarray whose bitwise AND is maximum
static void LongestSubarray(List<int> arr, int N)
{
// To store largest BITWISE AND
int temp = int.MinValue;
// To store answer
List<int> ans = new List<int>();
// To find all subarray
for (int i = 0; i < N; i++)
{
// To store BITWISE AND of Subarray
int val = int.MinValue;
// To store length of subarray
int length = 0;
for (int j = i; j < N; j++)
{
// Increment the length of subarray
length++;
// Take BIWISE AND
if (val == int.MinValue)
{
val = arr[j];
}
else
{
val = val & arr[j];
}
// When BITWISE AND of this subarray is
// larger than previously stored BIWISE AND
if (val > temp)
{
temp = val;
ans.Clear();
for (int k = i; k <= j; k++)
{
ans.Add(arr[k]);
}
}
// When BITWISE AND of this subarray is
// equal to previously stored BIWISE AND
// but has larger length than previously
// stored subarray
else if (val == temp && length > ans.Count)
{
temp = val;
ans.Clear();
for (int k = i; k <= j; k++)
{
ans.Add(arr[k]);
}
}
}
}
// Print Final answer
foreach (int num in ans)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
JavaScript
// Javascript Implementation
// Function to find the length of the
// longest subarray whose bitwise AND is maximum
function longestSubarray(arr) {
// To store largest BITWISE AND
let temp = -Infinity;
// To store answer
let ans = [];
// To find all subarray
for (let i = 0; i < arr.length; i++) {
// To store BITWISE AND of Subarray
let val = -Infinity;
// To store length of subarray
let length = 0;
for (let j = i; j < arr.length; j++) {
// Increment the length of subarray
length++;
// Take BITWISE AND
if (val === -Infinity) {
val = arr[j];
} else {
val = val & arr[j];
}
// When BITWISE AND of this subarray is
// larger than previously stored BITWISE AND
if (val > temp) {
temp = val;
ans = arr.slice(i, j + 1);
}
// When BITWISE AND of this subarray is
// equal to previously stored BITWISE AND
// but has larger length than previously
// stored subarray
else if (val === temp && length > ans.length) {
temp = val;
ans = arr.slice(i, j + 1);
}
}
}
// Print Final answer
console.log(ans.join(" "));
}
// Driver Code
const arr = [1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7];
// Function call
longestSubarray(arr);
Output-
7 7 7 7
Time Complexity: O(N3), because of two nested loops to find all subarray and a third loop to insert required subarray into vector
Auxiliary Space: O(N), for storing answer
Approach: The approach for code will be:
It is always better to take the maximum element and find the longest continous subarray having only the maximum element of the array.
Steps involved in the implementation of the code:
- Find the maximum value in the array using a loop and keep it in the variable maxi_val.
- Initialize two variables count and maxi to 1. count will keep track of the length of the current subarray with the maximum element repeated, and maxi will keep track of the maximum length seen so far.
- Traverse the array using a loop, and find the length of length occurring the same element.
Below is the implementation for the above approach:
C++
// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
// Function to find the length of the
// longest subarray with the
// maximum element repeated
int longestSubarray(vector<int>& nums)
{
// Find the maximum value in the array
int maxi_val = 0;
for (int i = 0; i < nums.size(); i++)
maxi_val = max(maxi_val, nums[i]);
int count = 1, maxi = 1;
// Traverse the array and count the
// length of the longest subarray with
// the maximum element repeated
for (int i = 0; i < nums.size() - 1; i++) {
// If the current element is equal
// to the maximum element and the
// next element is also equal to it,
// increment the count
if (nums[i] == maxi_val && nums[i] == nums[i + 1])
count++;
else
// If not, reset the count to 1
count = 1;
// Update the maximum
// length seen so far
maxi = max(maxi, count);
}
// Print maximum subarray
int i = 0;
while (i < maxi) {
cout << maxi_val << " ";
i++;
}
}
// Driver Code
int main()
{
vector<int> arr
= { 1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
longestSubarray(arr);
return 0;
}
Java
// Java implementation
import java.util.*;
public class GFG {
// Function to find the length of the
// longest subarray with the
// maximum element repeated
public static void longestSubarray(List<Integer> nums) {
// Find the maximum value in the array
int maxi_val = 0;
for (int i = 0; i < nums.size(); i++) {
maxi_val = Math.max(maxi_val, nums.get(i));
}
int count = 1, maxi = 1;
// Traverse the array and count the
// length of the longest subarray with
// the maximum element repeated
for (int i = 0; i < nums.size() - 1; i++) {
// If the current element is equal
// to the maximum element and the
// next element is also equal to it,
// increment the count
if (nums.get(i) == maxi_val && nums.get(i) == nums.get(i + 1)) {
count++;
} else {
// If not, reset the count to 1
count = 1;
}
// Update the maximum
// length seen so far
maxi = Math.max(maxi, count);
}
// Print maximum subarray
int i = 0;
while (i < maxi) {
System.out.print(maxi_val + " ");
i++;
}
}
// Driver Code
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>(Arrays.asList(1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7));
longestSubarray(arr);
}
}
Python3
def longestSubarray(nums):
# Find the maximum value in the array
maxi_val = 0
for i in range(len(nums)):
maxi_val = max(maxi_val, nums[i])
count = 1
maxi = 1
# Traverse the array and count the
# length of the longest subarray with
# the maximum element repeated
for i in range(len(nums) - 1):
# If the current element is equal
# to the maximum element and the
# next element is also equal to it,
# increment the count
if nums[i] == maxi_val and nums[i] == nums[i + 1]:
count += 1
else:
# If not, reset the count to 1
count = 1
# Update the maximum
# length seen so far
maxi = max(maxi, count)
# Print maximum subarray
i = 0
while i < maxi:
print(maxi_val, end=" ")
i += 1
arr = [1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7]
longestSubarray(arr)
C#
// C# code implementation
using System;
public class GFG {
// Function to find the length of the longest subarray
// with the maximum element repeated
static void longestSubarray(int[] nums)
{
// Find the maximum value in the array
int maxi_val = 0;
for (int i = 0; i < nums.Length; i++)
maxi_val = Math.Max(maxi_val, nums[i]);
int count = 1, maxi = 1;
// Traverse the array and count the length of the
// longest subarray with the maximum element
// repeated
for (int i = 0; i < nums.Length - 1; i++) {
// If the current element is equal to the
// maximum element and the next element is also
// equal to it, increment the count
if (nums[i] == maxi_val
&& nums[i] == nums[i + 1])
count++;
else
// If not, reset the count to 1
count = 1;
// Update the maximum length seen so far
maxi = Math.Max(maxi, count);
}
// Print maximum subarray
int k = 0;
while (k < maxi) {
Console.Write(maxi_val + " ");
k++;
}
}
static public void Main()
{
// Code
int[] arr = { 1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7 };
int N = arr.Length;
// Function call
longestSubarray(arr);
}
}
// This code is contributed by lokesh.
JavaScript
// Function to find the length of the
// longest subarray with the
// maximum element repeated
function longestSubarray(nums) {
// Find the maximum value in the array
let maxi_val = 0;
for (let i = 0; i < nums.length; i++)
maxi_val = Math.max(maxi_val, nums[i]);
let count = 1, maxi = 1;
// Traverse the array and count the
// length of the longest subarray with
// the maximum element repeated
for (let i = 0; i < nums.length - 1; i++) {
// If the current element is equal
// to the maximum element and the
// next element is also equal to it,
// increment the count
if (nums[i] == maxi_val && nums[i] == nums[i + 1])
count++;
else
// If not, reset the count to 1
count = 1;
// Update the maximum
// length seen so far
maxi = Math.max(maxi, count);
}
// Print maximum subarray
let i = 0;
while (i < maxi) {
console.log(maxi_val + " ");
i++;
}
return maxi;
}
// Driver Code
let arr = [1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7];
let result = longestSubarray(arr);
console.log("Length of longest subarray with maximum element repeated is: " + result);
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Length of the longest subarray whose Bitwise XOR is K
Given an array arr[] of size N and an integer K, the task is to find the length of the longest subarray having Bitwise XOR of all its elements equal to K. Examples: Input: arr[] = { 1, 2, 4, 7, 2 }, K = 1Output: 3Explanation: Subarray having Bitwise XOR equal to K(= 1) are { { 1 }, { 2, 4, 7 }, { 1
11 min read
Longest Subarray whose bitwise AND of every pair of elements is 0
Given a positive integer array arr[] of size N, the task is to find the longest subarray such that the bitwise AND of every pair of elements in the subarray is equal to 0. Examples: Input: arr[] = {1, 3, 8, 48, 10}Output: 3Explanation: The longest valid subarray is {3, 8, 48}, So, the length of a va
14 min read
Longest subarray such that the difference of max and min is at-most one
Given an array of n numbers where the difference between each number and the previous one doesn't exceed one. Find the longest contiguous subarray such that the difference between the maximum and minimum number in the range doesn't exceed one. Examples: Input : {3, 3, 4, 4, 5, 6} Output : 4 The long
7 min read
Print the longest increasing consecutive subarray
Given an array arr[] of size N, the task is to print the longest increasing subarray such that elements in the subarray are consecutive integers. Examples: Input: arr[] = {1, 9, 3, 4, 20, 2}Output: {3, 4}Explanation: The subarray {3, 4} is the longest subarray of consecutive elements Input: arr[] =
5 min read
Longest subarray having maximum sum
Given an array arr[] containing n integers. The problem is to find the length of the subarray having maximum sum. If there exists two or more subarrays with maximum sum then print the length of the longest subarray.Examples: Input : arr[] = {5, -2, -1, 3, -4}Output : 4There are two subarrays with ma
12 min read
Count subarrays which contains both the maximum and minimum array element
Given an array arr[] consisting of N distinct integers, the task is to find the number of subarrays which contains both the maximum and the minimum element from the given array. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1 Explanation: Only a single subarray {1, 2, 3, 4} consists of both the maxim
11 min read
Maximum Length Bitonic Subarray | Set 2 (O(n) time and O(1) Space)
Given an array arr[0...n-1] of n positive integers, a subarray arr[i ... j] is bitonic if there exists an index k (i ⤠k ⤠j) such that arr[i] ⤠arr[i+1] ⤠... ⤠arr[k] and arr[k] ⥠arr[k+1] ⥠... ⥠arr[j].Find the length of the longest bitonic subarray.ExamplesInput: arr[] = [12, 4, 78, 90, 45, 23]
5 min read
Find the maximum subarray XOR in a given array
Given an array of integers. The task is to find the maximum subarray XOR value in the given array. Examples: Input: arr[] = {1, 2, 3, 4}Output: 7Explanation: The subarray {3, 4} has maximum XOR value Input: arr[] = {8, 1, 2, 12, 7, 6}Output: 15Explanation: The subarray {1, 2, 12} has maximum XOR val
15+ min read
Maximum Bitwise AND value of subsequence of length K
Given an array a of size N and an integer K. The task is to find the maximum bitwise and value of elements of any subsequence of length K. Note: a[i] <= 109 Examples: Input: a[] = {10, 20, 15, 4, 14}, K = 4 Output: 4 {20, 15, 4, 14} is the subsequence with highest '&' value. Input: a[] = {255
15+ min read
Find the size of Largest Subset with positive Bitwise AND
Given an array arr[] consisting of N positive integers, the task is to find the largest size of the subset of the array arr[] with positive Bitwise AND. Note : If there exist more than one such subsets then return size of only one subset. Examples: Input: arr[] = [7, 13, 8, 2, 3]Output: 3Explanation
6 min read