Count Symmetric Integers — LeetCode 2843 Python Solution
- Problem
- #2843
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log m) |
| Space | O(\log m) auxiliary |
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
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 \times \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.