Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A symmetric integer must have an even number of decimal digits so its representation splits into equal halves. The two halves need equal digit sums, not identical digits or a palindrome structure. The bounded interval permits direct enumeration.
Approach
Visit every integer from low through high, inclusive, and convert it to decimal text. Skip odd-length representations. Sum digits in the first half and second half separately, counting the number when the sums match. Return the total. The conversion uses the ordinary representation without leading zeros, which is essential when deciding the number of digits.
class Solution:
def countSymmetricIntegers(self, low: int, high: int) -> int:
res = 0
for n in range(low, high + 1):
txt = str(n)
size = len(txt)
if size % 2 != 0:
continue
# First half count
count_a = 0
for i in range(size // 2):
count_a += int(txt[i])
# Second half count
count_b = 0
for i in range(size // 2, size):
count_b += int(txt[i])
if count_a == count_b:
res += 1
return resComplexity analysis
Let R = high - low + 1 and d be the maximum digit count. Time: O(R * d). Auxiliary space: O(d) for each temporary decimal string.
