VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-the-longest-subarray-whose-bitwise-and-is-maximum/

⇱ Print the Longest Subarray whose Bitwise AND is maximum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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-

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:


Output
7 7 7 7 

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

Comment