VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-common-substring-with-max-xor/

⇱ Longest Common Substring with max XOR - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Common Substring with max XOR

Last Updated : 4 Oct, 2023

Given two strings s1 and s2, the task is to find the length of the longest common substring of s1 and s2 such that the XOR is maximum.

Examples:

Input:  s1 = "79567",   s2 = "56779"
Output: 2
Explanation: The longest common substring with a max XOR is "79", which has an XOR  of 14 and a length is 2.

Input: s1 = "123456",  s2 = "8762347"
Output: 3
Explanation: The longest common substring with a max XOR is "234", which has an XOR  of 5 and a length is 3.

Approach: This can be solved with the following idea:

This approach uses the fact that two binary numbers have the same XOR value if and only if their bitwise XOR operation is a power of 2. Therefore, we generate all possible substrings of s1 and store their hash values in a set. Then we generate all possible substrings of s2 and check if their hash values are present in the set. If the hash value is present in the set, we update the maximum XOR value to the length of the substring.

Steps of the above approach:

  • Initialize the maximum XOR value to 0 and create an empty unordered set.
  • Iterate over all possible lengths of substrings starting from length 1 up to the length of s1.
  • For each substring length, generate all possible substrings of that length in s1.
  • For each substring generated, calculate its hash value by treating the substring as a binary number and adding it to the hash value using bitwise left shift and bitwise OR operations.
  • Store the hash value in the unordered set.
  • Generate all possible substrings of length len in s2.
  • For each substring generated, calculate its hash value using the same method as step 4.
  • Check if the hash value is present in the unordered set.
  • If the hash value is present, update the maximum XOR value to the length of the substring.
  • Repeat steps 2-9 for all possible substring lengths.
  • Return the final value of max_xor as the length of the longest common substring of s1 and s2 with maximum XOR.

Below is the implementation of the above approach:


Output
2
3

Time Complexity: O(n^3 * log n)
Auxiliary Space: O(n^2)

Comment