Skip to content
Related Articles

Related Articles

Longest subsequence with a given AND value | O(N)

Improve Article
Save Article
  • Last Updated : 09 Nov, 2021
Improve Article
Save Article

Given an array arr[], the task is to find the longest subsequence with a given AND value M. If there is no such sub-sequence then print 0.
Examples: 
 

Input: arr[] = {3, 7, 2, 3}, M = 3 
Output:
{3, 7, 3} is the required subsequence. 
3 & 7 & 3 = 3
Input: arr[] = {2, 2}, M = 3 
Output:
 

 

Naive approach: A simple way to solve this problem is to generate all the possible sub-sequences and then find the largest among them with the required AND value.
Efficient approach: One key observation is that all of the numbers in the required sub-sequence should yield the value M when they get ANDed with M. So filter out all of such elements whose AND with M equals to M
Now, the task is to find the longest sub-sequence among this filtered subset. It’s pretty obvious that all of these numbers will be ANDed together. If the result of this AND is M then the answer will be equal to the size of this filtered set. Otherwise answer will be 0. This is because AND only unsets the set bits. So, the larger the numbers in the set, the more optimal it is.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the required length
int findLen(int* arr, int n, int m)
{
    // To store the filtered numbers
    vector<int> filter;
 
    // Filtering the numbers
    for (int i = 0; i < n; i++)
        if ((arr[i] & m) == m)
            filter.push_back(arr[i]);
 
    // If there are no elements to check
    if (filter.size() == 0)
        return 0;
 
    // Find the AND of all the
    // filtered elements
    int c_and = filter[0];
    for (int i = 1; i < filter.size(); i++)
        c_and &= filter[i];
 
    // Check if the AND is equal to m
    if (c_and == m)
        return filter.size();
 
    return 0;
}
 
// Driver code
int main()
{
    int arr[] = { 7, 3, 3, 1, 3 };
    int n = sizeof(arr) / sizeof(int);
    int m = 3;
 
    cout << findLen(arr, n, m);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
class GFG
{
     
// Function to return the required length
static int findLen(int []arr, int n, int m)
{
    // To store the filtered numbers
    Vector<Integer> filter = new Vector<>();
 
    // Filtering the numbers
    for (int i = 0; i < n; i++)
        if ((arr[i] & m) == m)
            filter.add(arr[i]);
 
    // If there are no elements to check
    if (filter.size() == 0)
        return 0;
 
    // Find the AND of all the
    // filtered elements
    int c_and = filter.get(0);
    for (int i = 1; i < filter.size(); i++)
        c_and &= filter.get(i);
 
    // Check if the AND is equal to m
    if (c_and == m)
        return filter.size();
 
    return 0;
}
 
// Driver code
public static void main(String []args)
{
    int arr[] = { 7, 3, 3, 1, 3 };
    int n = arr.length;
    int m = 3;
 
    System.out.println(findLen(arr, n, m));
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Python3 implementation of the approach
 
# Function to return the required length
def findLen(arr, n, m) :
 
    # To store the filtered numbers
    filter = [];
 
    # Filtering the numbers
    for i in range(n) :
        if ((arr[i] & m) == m) :
            filter.append(arr[i]);
 
    # If there are no elements to check
    if (len(filter) == 0) :
        return 0;
 
    # Find the OR of all the
    # filtered elements
    c_and = filter[0];
    for i in range(1, len(filter)) :
        c_and &= filter[i];
 
    # Check if the OR is equal to m
    if (c_and == m) :
        return len(filter);
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 7, 3, 3, 1, 3 ];
    n = len(arr);
    m = 3;
 
    print(findLen(arr, n, m));
     
# This code is contributed by AnkitRai01


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to return the required length
static int findLen(int []arr, int n, int m)
{
    // To store the filtered numbers
    List<int> filter = new List<int>();
 
    // Filtering the numbers
    for (int i = 0; i < n; i++)
        if ((arr[i] & m) == m)
            filter.Add(arr[i]);
 
    // If there are no elements to check
    if (filter.Count == 0)
        return 0;
 
    // Find the AND of all the
    // filtered elements
    int c_and = filter[0];
    for (int i = 1; i < filter.Count; i++)
        c_and &= filter[i];
 
    // Check if the AND is equal to m
    if (c_and == m)
        return filter.Count;
 
    return 0;
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = { 7, 3, 3, 1, 3 };
    int n = arr.Length;
    int m = 3;
 
    Console.WriteLine(findLen(arr, n, m));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the required length
function findLen(arr, n, m)
{
    // To store the filtered numbers
    var filter = [];
 
    // Filtering the numbers
    for (var i = 0; i < n; i++)
        if ((arr[i] & m) == m)
            filter.push(arr[i]);
 
    // If there are no elements to check
    if (filter.length == 0)
        return 0;
 
    // Find the AND of all the
    // filtered elements
    var c_and = filter[0];
    for (var i = 1; i < filter.length; i++)
        c_and &= filter[i];
 
    // Check if the AND is equal to m
    if (c_and == m)
        return filter.length;
 
    return 0;
}
 
// Driver code
var arr = [7, 3, 3, 1, 3];
var n = arr.length;
var m = 3;
document.write( findLen(arr, n, m));
 
</script>


Output: 

4

 

Time Complexity: O(n)

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!