Saturday, December 3, 2022
HomeSoftware DevelopmentLongest Subarray whose bitwise AND of each pair of components is 0

Longest Subarray whose bitwise AND of each pair of components is 0


Enhance Article

Save Article

Like Article

Enhance Article

Save Article

Given a optimistic integer array arr[] of measurement N, the duty is to search out the longest subarray such that the bitwise AND of each pair of components within the subarray is the same as 0.

Examples: 

Enter: arr[] = {1, 3, 8, 48, 10}
Output: 3
Rationalization: The longest legitimate subarray is {3, 8, 48}, So, the size of a legitimate subarray is 3
=> 3 AND 8 = 0.
=> 3 AND 48 = 0.
=> 8 AND 48 = 0.

Enter: arr = {3, 1, 5, 11, 13}
Output: 1

An strategy utilizing Bit Manipulation:

The bitwise AND of each pair within the subarray ought to be zero this assertion implies that In a legitimate subarray bits of each factor ought to be distinctive. 

We’ll use a sliding window strategy, monitoring used bits. We use bitwise OR to mix bits. If the following quantity has a conflicting bit (used & arr[i] != 0), shrink the window till there are not any conflicts. We’ll use the XOR operation to take away bits through the window shrinks.

Observe the steps beneath to implement the above concept:

  • Initialize a variable used to maintain observe of used bit.
  • Initialize a variable begin to maintain observe of beginning place of the sliding window.
  • Initialize a variable outcome to maintain observe of the reply.
  • Iterate over the given array:
    • Shrink the window till (used & arr[i] != 0).
    • Set the bits of the present factor within the used variable.
    • Maximize the outcome with a legitimate subarray size.
  • Return the outcome.

Beneath is the implementation of the above strategy.

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

int longestValidSubarray(vector<int>& arr)

{

    int used = 0;

    int begin = 0;

    int n = arr.measurement();

    int outcome = 0;

  

    for (int i = 0; i < n; i++) {

  

        

        

        whereas ((used & arr[i]) != 0) {

  

            

            

            used ^= arr[start];

            begin++;

        }

        

        used |= arr[i];

  

        if (begin < i)

            outcome = max(outcome, i - begin + 1);

    }

  

    return outcome;

}

  

int primary()

{

    

    vector<int> arr = { 3, 1, 5, 11, 13 };

    cout << longestValidSubarray(arr) << endl;

  

    

    arr = { 1, 3, 8, 48, 10 };

    cout << longestValidSubarray(arr) << endl;

  

    

    arr = { 2, 4, 8, 16 };

    cout << longestValidSubarray(arr) << endl;

  

    return 0;

}

Time Complexity: O(N)
Auxiliary House: O(1)

Associated Articles:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments