Find the length of the longest contiguous substring of a given string, such that the length of the substring is 2×n digits and the sum of the leftmost n digits is equal to the sum of the rightmost n digits. If there is no such substring, return 0.

The problem differs from the problem of finding the longest even-length palindromic sum subsequence. Unlike subsequences, substrings are required to occupy consecutive positions within the original string.

 
For example,

Input:  13267224
 
The length of the longest palindromic sum substring is 6.
 
326722 = (3 + 2 + 6) = (7 + 2 + 2) = 11
 
 
Input:  546374
 
The length of the longest palindromic sum substring is 4.
 
4637 = (4 + 6) = (3 + 7) = 10

Practice this problem

The idea is to consider every even length substring present in the string and calculate the sum of digits of their left and right half. Then, return the maximum length among the length of all substrings that have an equal sum in the left and right half.

 
The algorithm can be implemented as follows in C++, Java, and Python. To calculate the sum of the left and right half in constant time, a sum array is maintained.

C++


Download  Run Code

Output:

The length of the longest palindromic sum substring is 6

Java


Download  Run Code

Output:

The length of the longest palindromic sum substring is 6

Python


Download  Run Code

Output:

The length of the longest palindromic sum substring is 6

The time complexity of the above solution is O(n2) and requires O(n) extra space, where n is the length of the input string.

Can we do it with constant space?

We know that an even length palindrome will have two middle points. The idea is to consider every adjacent pair of digits in the string as midpoints and expand in both directions to find the maximum length palindrome. The longest palindromic substring problem inspires the idea.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The length of the longest palindromic sum substring is 4

Java


Download  Run Code

Output:

The length of the longest palindromic sum substring is 4

Python


Download  Run Code

Output:

The length of the longest palindromic sum substring is 4

The time complexity of the above solution is O(n2), where n is the length of the input string and doesn’t require any extra space.