Given a string s consisting of digits, find the length of the longest even-length substring such that the sum of the digits in the first half equals the sum of the digits in the second half.
Return 0 if no such substring exists.
Function Signature
def longest_even_length_substring(s: str) -> int:
Rules
-
A substring is a contiguous run of characters of
s
. A substring of length
2k
splits into a first half of its first
k
characters and a second half of its last
k
characters.
-
Only even lengths of 2 or more count, so a single character never qualifies.
-
Return only the length. If several substrings tie for the longest, the length is the same.
Constraints
-
1 <= len(s) <= 1000
-
s
consists of digit characters
'0'
to
'9'
only.
Examples
Input: s = "123123"
Output: 6
The whole string has length 6, and both halves "123" sum to 6.
Input: s = "1538023"
Output: 4
"5380" has half sums 5 + 3 = 8 and 8 + 0 = 8. Neither length-6 substring qualifies ("153802" gives 9 and 10, "538023" gives 16 and 5), and no length-4 substring other than "5380" balances.
Input: s = "1234"
Output: 0
All adjacent digits differ, so no length-2 substring balances, and the whole string has half sums 3 and 7.