EasyNo. 2843

Count Symmetric Integers — LeetCode 2843 Python Solution

Topics
Math, Enumeration
Reading time
2 min

The problem

You are given two positive integers low and high. An integer x consisting of 2 * n digits is symmetric if the sum of the first n digits of x is equal to the sum of the last n digits of x.

Example

Input
low = 1, high = 100
Output
9
Explanation
There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99.

Python solution

PythonSolution
class Solution:
    def countSymmetricIntegers(self, low: int, high: int) -> int:
        def f(x: int) -> bool:
            s = str(x)
            if len(s) & 1:
                return False
            n = len(s) // 2
            return sum(map(int, s[:n])) == sum(map(int, s[n:]))

        return sum(f(x) for x in range(low, high + 1))

Complexity

Time
O(n × log m)
Space · auxiliary
O(log m)

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2843. Count Symmetric Integers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0204Count PrimesMedium
0479Largest Palindrome ProductHard
0829Consecutive Numbers SumHard
0906Super PalindromesHard
1925Count Square Sum TriplesEasy
1952Three DivisorsEasy

Frequently asked questions

How hard is LeetCode 2843. Count Symmetric Integers?

LeetCode 2843. Count Symmetric Integers is rated Easy on LeetCode.

What is the time complexity of LeetCode 2843. Count Symmetric Integers?

The Python solution on this page runs in O(n × log m).

What is the space complexity of LeetCode 2843. Count Symmetric Integers?

The Python solution on this page uses O(log m) auxiliary space.

What topics does LeetCode 2843. Count Symmetric Integers cover?

LeetCode 2843. Count Symmetric Integers is tagged Math and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.