Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Longest subsequence possible that starts and ends with 1 and filled with 0 in the middle
Next article icon

Length of the longest subsequence such that xor of adjacent elements is non-decreasing

Last Updated : 04 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sequence arr of N positive integers, the task is to find the length of the longest subsequence such that xor of adjacent integers in the subsequence must be non-decreasing.

Examples: 

Input: N = 8, arr = {1, 100, 3, 64, 0, 5, 2, 15} 
Output: 6 
The subsequence of maximum length is {1, 3, 0, 5, 2, 15} 
with XOR of adjacent elements as {2, 3, 5, 7, 13}
Input: N = 3, arr = {1, 7, 10} 
Output: 3 
The subsequence of maximum length is {1, 3, 7} 
with XOR of adjacent elements as {2, 4}. 

Approach: 

  • This problem can be solved using dynamic programming where dp[i] will store the length of the longest valid subsequence that ends at index i.
  • First, store the xor of all the pairs of elements i.e. arr[i] ^ arr[j] and the pair (i, j) also and then sort them according to the value of xor as they need to be non-decreasing.
  • Now if the pair (i, j) is considered then the length of the longest subsequence that ends at j will be max(dp[j], 1 + dp[i]). In this way, calculate the maximum possible value of dp[] array for each position and then take the maximum of them.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the length of the longest
// subsequence such that the XOR of adjacent
// elements in the subsequence must
// be non-decreasing
int LongestXorSubsequence(int arr[], int n)
{
 
    vector<pair<int, pair<int, int> > > v;
 
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // Computing xor of all the pairs
            // of elements and store them
            // along with the pair (i, j)
            v.push_back(make_pair(arr[i] ^ arr[j],
                                  make_pair(i, j)));
        }
    }
 
    // Sort all possible xor values
    sort(v.begin(), v.end());
 
    int dp[n];
 
    // Initialize the dp array
    for (int i = 0; i < n; i++) {
        dp[i] = 1;
    }
 
    // Calculating the dp array
    // for each possible position
    // and calculating the max length
    // that ends at a particular index
    for (auto i : v) {
        dp[i.second.second]
            = max(dp[i.second.second],
                  1 + dp[i.second.first]);
    }
 
    int ans = 1;
 
    // Taking maximum of all position
    for (int i = 0; i < n; i++)
        ans = max(ans, dp[i]);
 
    return ans;
}
 
// Driver code
int main()
{
 
    int arr[] = { 2, 12, 6, 7, 13, 14, 8, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << LongestXorSubsequence(arr, n);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
 
class GFG {
    // Function to find the length of the longest
    // subsequence such that the XOR of adjacent
    // elements in the subsequence must
    // be non-decreasing
    static int LongestXorSubsequence(int[] arr, int n)
    {
 
        List<int[]> v = new ArrayList<>();
 
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
 
                // Computing xor of all the pairs
                // of elements and store them
                // along with the pair (i, j)
                int[] l1 = { arr[i] ^ arr[j], i, j };
                v.add(l1);
            }
        }
 
        // Sort all possible xor values
        Comparator<int[]> byFirstElement
            = (int[] a, int[] b) -> a[0] - b[0];
 
        List<int[]> v1 = v.stream()
                             .sorted(byFirstElement)
                             .collect(Collectors.toList());
 
        int[] dp = new int[n];
 
        // Initialize the dp array
        for (int i = 0; i < n; i++) {
            dp[i] = 1;
        }
 
        // Calculating the dp array
        // for each possible position
        // and calculating the max length
        // that ends at a particular index
        Iterator<int[]> iter = v1.iterator();
        while (iter.hasNext()) {
            int[] list = iter.next();
            dp[list[2]]
                = Math.max(dp[list[2]], 1 + dp[list[1]]);
        }
 
        int ans = 1;
 
        // Taking maximum of all position
        for (int i = 0; i < n; i++)
            ans = Math.max(ans, dp[i]);
 
        return ans;
    }
    public static void main(String[] args)
    {
        // Driver code
        int[] arr = { 2, 12, 6, 7, 13, 14, 8, 6 };
        int n = arr.length;
 
        System.out.println(LongestXorSubsequence(arr, n));
    }
}
 
// this code is contributed by phasing17
 
 

Python3




# Python3 implementation of the approach
 
# Function to find the length of the longest
# subsequence such that the XOR of adjacent
# elements in the subsequence must
# be non-decreasing
def LongestXorSubsequence(arr, n):
 
    v = []
 
    for i in range(0, n):
        for j in range(i + 1, n):
 
             # Computing xor of all the pairs
            # of elements and store them
            # along with the pair (i, j)
            v.append([(arr[i] ^ arr[j]), (i, j)])
 
        # v.push_back(make_pair(arr[i] ^ arr[j], make_pair(i, j)))
         
    # Sort all possible xor values
    v.sort()
     
    # Initialize the dp array
    dp = [1 for x in range(88)]
 
    # Calculating the dp array
    # for each possible position
    # and calculating the max length
    # that ends at a particular index
    for a, b in v:
        dp[b[1]] = max(dp[b[1]], 1 + dp[b[0]])
     
    ans = 1
 
    # Taking maximum of all position
    for i in range(0, n):
        ans = max(ans, dp[i])
 
    return ans
 
# Driver code
arr = [ 2, 12, 6, 7, 13, 14, 8, 6 ]
n = len(arr)
print(LongestXorSubsequence(arr, n))
 
# This code is contributed by Sanjit Prasad
 
 

C#




// C# implementation of the approach
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to find the length of the longest
  // subsequence such that the XOR of adjacent
  // elements in the subsequence must
  // be non-decreasing
  static int LongestXorSubsequence(int[] arr, int n)
  {
 
    List<int[]> v = new List<int[]>();
 
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
 
        // Computing xor of all the pairs
        // of elements and store them
        // along with the pair (i, j)
        int[] l1 = { arr[i] ^ arr[j], i, j };
        v.Add(l1);
      }
    }
 
    // Sorting the array by First Value
    List<int[]> v1 = v.OrderBy(a => a[0])
      .ThenBy(a => a[1])
      .ToList();
 
    int[] dp = new int[n];
 
    // Initialize the dp array
    for (int i = 0; i < n; i++) {
      dp[i] = 1;
    }
 
    // Calculating the dp array
    // for each possible position
    // and calculating the max length
    // that ends at a particular index
    foreach(var list in v1) dp[list[2]]
      = Math.Max(dp[list[2]], 1 + dp[list[1]]);
 
    int ans = 1;
 
    // Taking maximum of all position
    for (int i = 0; i < n; i++)
      ans = Math.Max(ans, dp[i]);
 
    return ans;
  }
  public static void Main(string[] args)
  {
    // Driver code
    int[] arr = { 2, 12, 6, 7, 13, 14, 8, 6 };
    int n = arr.Length;
 
    Console.WriteLine(LongestXorSubsequence(arr, n));
  }
}
 
// This code is contributed by phasing17
 
 

Javascript




<script>
// Javascript implementation of the approach
 
// Function to find the length of the longest
// subsequence such that the XOR of adjacent
// elements in the subsequence must
// be non-decreasing
function LongestXorSubsequence(arr, n) {
 
    let v = [];
 
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
 
            // Computing xor of all the pairs
            // of elements and store them
            // along with the pair (i, j)
            v.push([arr[i] ^ arr[j], [i, j]]);
        }
    }
 
    // Sort all possible xor values
    v.sort((a, b) => a[0] - b[0]);
 
    let dp = new Array(n);
 
    // Initialize the dp array
    for (let i = 0; i < n; i++) {
        dp[i] = 1;
    }
 
    // Calculating the dp array
    // for each possible position
    // and calculating the max length
    // that ends at a particular index
    for (let i of v) {
        dp[i[1][1]]
            = Math.max(dp[i[1][1]],
                1 + dp[i[1][0]]);
    }
 
    let ans = 1;
 
    // Taking maximum of all position
    for (let i = 0; i < n; i++)
        ans = Math.max(ans, dp[i]);
 
    return ans;
}
 
// Driver code
let arr = [2, 12, 6, 7, 13, 14, 8, 6];
let n = arr.length;
 
document.write(LongestXorSubsequence(arr, n));
 
// This code is contributed by _saurabh_jaiswal.
</script>
 
 
Output
5

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



Next Article
Longest subsequence possible that starts and ends with 1 and filled with 0 in the middle

S

souradeep
Improve
Article Tags :
  • Arrays
  • C++ Programs
  • DSA
  • Dynamic Programming
  • Greedy
  • Bitwise-XOR
  • subsequence
Practice Tags :
  • Arrays
  • Dynamic Programming
  • Greedy

Similar Reads

  • Longest subarray such that adjacent elements have at least one common digit | Set 1
    Given an array of N integers, write a program that prints the length of the longest subarray such that adjacent elements of the subarray have at least one digit in common. Examples: Input : 12 23 45 43 36 97 Output : 3 Explanation: The subarray is 45 43 36 which has 4 common in 45, 43 and 3 common i
    11 min read
  • Number of subsequences of maximum length K containing no repeated elements
    Given an array arr[] of N elements and a positive integer K such that K ≤ N. The task is to find the number of subsequences of maximum length K i.e. subsequences of length 0, 1, 2, ..., K - 1, K that have all distinct elements. Examples: Input: arr[] = {2, 2, 3, 3, 5}, K = 2 Output: 14 All the valid
    15 min read
  • Length of longest strictly increasing subset with each pair of adjacent elements satisfying the condition 2 * A[i] ≥ A[i + 1]
    Given an array A[] of size N, the task is to find the length of the longest strictly increasing subset with every pair of adjacent elements satisfying the condition A[i + 1] ? 2 * A[i]. If multiple such subsets are present, then print any one of them. Examples: Input: A[] = {3, 1, 5, 11}Output: 3, 5
    9 min read
  • Find the longest subsequence of an array having LCM at most K
    Given an array arr[] of N elements and a positive integer K. The task is to find the longest sub-sequence in the array having LCM (Least Common Multiple) at most K. Print the LCM and the length of the sub-sequence, following the indexes (starting from 0) of the elements of the obtained sub-sequence.
    10 min read
  • Longest subsequence possible that starts and ends with 1 and filled with 0 in the middle
    Given a binary string s, the task is to find the length of the longest subsequence that can be divided into three substrings such that the first and third substrings are either empty or filled with 1 and the substring at the middle is either empty or filled with 0. Examples: Input: s = "1001" Output
    7 min read
  • Length of longest subarray for each index in Array where element at that index is largest
    Given an array arr[] of size N, the task is to calculate, for i(0<=i<N), the maximum length of a subarray containing arr[i], where arr[i] is the maximum element. Example: Input : arr[ ] = {62, 97, 49, 59, 54, 92, 21}, N=7Output: 1 7 1 3 1 5 1Explanation: The maximum length of subarray in which
    15 min read
  • Maximum contiguous decreasing sequence obtained by removing any one element
    Given an array arr[] of N integers. The task is to find the length of the contiguous strictly decreasing sequence that can be derived after removing at most one element from the array arr[]. Examples Input: arr[] = {8, 7, 3, 5, 2, 9} Output: 4 Explanation: If we remove 3, The maximum length of decre
    10 min read
  • Longest subarray of non-empty cells after removal of at most a single empty cell
    Given a binary array arr[], the task is to find the longest subarray of non-empty cells after the removal of at most 1 empty cell. The array indices filled with 0 are known as empty cell whereas the indices filled with 1 are known as non-empty cells. Examples: Input: arr[] = {1, 1, 0, 1} Output: 3 E
    9 min read
  • C/C++ Program for Longest Increasing Subsequence
    Given an array arr[] of size N, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order. Examples: Input: arr[] = {3, 10, 2, 1, 20}Output: 3Explanation: The longest incre
    8 min read
  • C++ Program for Longest Increasing Subsequence
    The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60,
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences