The Wayback Machine - https://web.archive.org/web/20210126184434/https://www.geeksforgeeks.org/length-of-the-longest-subsequence-such-that-xor-of-adjacent-elements-is-equal-to-k/
Related Articles

Related Articles

Length of the longest subsequence such that XOR of adjacent elements is equal to K
  • Last Updated : 25 Jan, 2021

Given an array arr[] of N non-negative integers and an integer K, the idea is to find the length of the longest subsequence having Xor of adjacent elements equal to K.

Examples:

Input: N = 5, arr[] = {3, 2, 4, 3, 5}, K = 1
Output: 3
Explanation:
All the subsequences having Xor of adjacent element equal to K are {3, 2}, {2, 3}, {4, 5}, {3, 2, 3}.
Therefore, the length of the longest subsequence having xor of adjacent element as 1 is 3.

Input: N = 8, arr[] = {4, 5, 4, 7, 3, 5, 4, 6}, K = 2
Output: 3
Explanation:
All the subsequences having Xor of adjacent element equal to K are {4, 6}, {5, 7}, {7, 5}, {5, 7, 5}.
Therefore, the length of the longest subsequence having xor of adjacent element as 1 is 3

Naive Approach: The idea is to use Dynamic Programming. The given problem can be solved based on the following observations:



  • Suppose Dp(i) represent maximum length of subsequence ending at index i.
  • Then, transition of one state to another state will be as follows:
    • Find index j such that j < i and a[j] ^ a[i] = k.
    • Therefore, Dp(i) = max(Dp(j)+1, Dp(i)) 

Follow the steps below to solve the problem:

  • Initialize an integer, say ans, to store the length of the longest subsequence and an array, say dp[], to store the dp states.
  • Define base case as dp[0] = 1.
  • Iterate over the range [1, N – 1]:
    • Iterate over the range [0, i-1] and update dp[i] as max(dp[i], dp[j] + 1) if a[i] ^ a[j] = K.
    • Update ans as max(ans, dp[i]).
  • Finally, print the maximum length of the longest subsequence ans.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for above approach
  
import java.io.*;
import java.util.*;
class GFG {
  
    // Function to find maximum length
    // of subsequence having XOR of
    // adjacent elements equal to K
    public static int xorSubsequence(int a[],
                                     int n, int k)
    {
  
        // Store maximum length of subsequnce
        int ans = 0;
  
        // Stores the dp-states
        int dp[] = new int[n];
  
        // Base case
        dp[0] = 1;
  
        // Iterate over the range [1, N-1]
        for (int i = 1; i < n; i++) {
  
            // Iterate over the range [0, i - 1]
            for (int j = i - 1; j >= 0; j--) {
  
                // If arr[i]^arr[j] == K
                if ((a[i] ^ a[j]) == k)
  
                    // Update the dp[i]
                    dp[i] = Math.max(dp[i], dp[j] + 1);
            }
            // Update the maximum subsequence length
            ans = Math.max(ans, dp[i]);
  
            dp[i] = Math.max(1, dp[i]);
        }
        // If length of longest susequnce
        // is less than 2 then return 0
        return ans >= 2 ? ans : 0;
    }
    // Driver Code
    public static void main(String[] args)
    {
        // Input
        int arr[] = { 3, 2, 4, 3, 5 };
        int K = 1;
        int N = arr.length;
        // Print the length of longest subsequence
        System.out.println(xorSubsequence(arr, N, K));
    }
}

chevron_right


Output:

3

Time Complexity: O(N2)
Auxiliary Space: O(N)

Efficient Approach: The above approach can be optimized by using the property of Xor and Hashmap with dynamic programming to store the maximum length of subsequence ending at an integer, resulting in constant time transition of states in DP. 

  • Initialize an integer say ans =0 to store the length of the longest subsequence and an array say dp[] to store the state of DP.
  • Initialize a HashMap say mp to store the longest length of subsequence ending at an element.
  • Define base case as dp[0] = 1 and push the pair {arr[0], 1} in mp.
  • Iterate over the range [1, N-1]:
    • Find the length of the longest subsequence say dpj ending at element arr[i] ^K from HashMap mp.
    • Update dp[i] as max(dp[i], dpj+1) and update the longest length of subsequence ending at element arr[i] in HashMap mp.
    • Update the ans = max(ans, dp[i]).
  • Finally, print the maximum length of the longest subsequence ans.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for above approach
  
import java.io.*;
import java.util.*;
class GFG {
  
    // Function to find maximum length of subsequence
    public static int xorSubsequence(int a[], int n, int k)
    {
        // Stores maximum length of subsequence
        int ans = 0;
  
        // HashMap to store the longest length of
        // subsequence ending at an integer, say X
        HashMap<Integer, Integer> map = new HashMap<>();
  
        // Stores the maximum length of
        // subsequence ending at index i
        int dp[] = new int[n];
  
        // Base case
        map.put(a[0], 1);
        dp[0] = 1;
  
        // Iterate over the range [1, N-1]
        for (int i = 1; i < n; i++) {
  
            // Retrieve the longest length of
            // subsequnec ending at integer a[]^K
            Integer dpj = map.get(a[i] ^ k);
  
            // If dpj is not NULL
            if (dpj != null)
  
                // Update dp[i]
                dp[i] = Math.max(dp[i], dpj + 1);
  
            // Update ans
            ans = Math.max(ans, dp[i]);
  
            // Update the maximum length of subsequence
            // ending at element is a[i] in HashMap
            map.put(
                a[i],
                Math.max(map.getOrDefault(a[i], 1), dp[i]));
        }
  
        // Return the ans if ans>=2.
        // Otherwise, return 0
        return ans >= 2 ? ans : 0;
    }
    // Driver Code
    public static void main(String[] args)
    {
        // Input
        int arr[] = { 3, 2, 4, 3, 5 };
        int N = arr.length;
        int K = 1;
  
        // Print the length of the longest subsequence
        System.out.println(xorSubsequence(arr, N, K));
    }
}

chevron_right


Output:

3

Time Complexity: O(N)
Auxiliary Space: O(N
)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :