Input: S = “3242415”
Explanation: “24241” is the longest such substring which can be converted to the palindromic string “24142”.
Input: S = “213123”
Explanation: “213123” such substring which can be converted to the palindromic string “231132”.
Naive Approach: The simplest approach to solve this problem is to generate all possible substrings and for each substring check if it can be made a palindrome or not by counting the characters in each substring and check if only one or no odd frequent character is present or not.
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea to solve this problem is to use Bitmasking and Dynamic Programming. A palindrome can be formed if the count of each included number (except maybe one) is even. Follow the steps below to solve the problem:
- Initialize an integer variable, say mask. A bit in our mask is 0 if the count for the corresponding number is even, and 1 if it’s odd.
- Traverse through the string and while traversing the string, track odd/even counts in the variable mask.
- If the same mask is encountered again, the subarray between the first position (exclusive) and the current position (inclusive) with the same mask has all numbers with the even count.
- Let the size of the substring be stored in a variable, say res.
- Initialize an array, say dp, to track the smallest (first) position of each mask of size 1024, since the input only contains 10 digits (“0123456789”), and there can be only 2^10 or 1024 variations of bit masks.
- The size of the substring can be calculated by subtracting it from the current position. Note that the position for zero mask is -1, as the first character is to be included.
- Also, check all masks that are different from the current one by one bit. In other words, if two masks are different by one bit, that means that there is one odd count in the substring.
- Print res as the length of longest such substring.
Below is the implementation of the above approach:
Time Complexity: O(10*N)
Auxiliary Space: O(1024)
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.