Python 2843.py
class Solution:
def countSymmetricIntegers(self, low: int, high: int) -> int:
result = 0
# two digits: both must be identical => divisible by 11
for n in range(11, 99 + 1, 11):
if low <= n <= high:
result += 1
if high < 1000:
return result
# create every two-digit number, group by its sum
two = defaultdict(list)
for i in range(10):
for j in range(10):
two[i + j].append(i * 10 + j)
# create every combination of those two digits
for same in two:
for a in two[same]:
if a * 100 > high:
break
if a > 9: # no leading zero
for b in two[same]:
x = a * 100 + b
if low <= x <= high:
result += 1
return result
Difficulty
and has an acceptance rate of about 83% (200k+ submissions).
Typical patterns to solve this problem:
- Enumeration
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation counts integers within a closed interval [low, high] whose first half of digits sum to the same value as the second half. The algorithm treats one-digit, two-digit, and four-digit numbers separately, exploiting arithmetic properties to avoid exhaustive enumeration of every candidate.
Key Steps
Counting two-digit symmetric numbers
The first loop enumerates two-digit numbers that are multiples of 11, because a two-digit number ab is symmetric exactly when a == b. The loop steps by 11, starting at 11 and ending at 99, and increments the result counter only when the current number lies inside the input interval.
result = 0
for n in range(11, 99 + 1, 11):
if low <= n <= high:
result += 1
Early exit for intervals that end before four digits
If the upper bound high is less than 1000, no four-digit numbers can appear in the range, so the function returns the count accumulated from the two-digit stage. This guard prevents unnecessary work for small intervals.
if high < 1000:
return result
Pre-computing two-digit numbers grouped by digit sum
A defaultdict(list) named two stores every two-digit combination ij (including those with a leading zero) under the key equal to the sum i + j. The nested loops generate all 100 possibilities (i from 0-9, j from 0-9) and append the numeric value i * 10 + j to the appropriate bucket. This structure enables constant-time lookup of all two-digit numbers that share a particular digit-sum, which is essential for constructing four-digit symmetric numbers.
two = defaultdict(list)
for i in range(10):
for j in range(10):
two[i + j].append(i * 10 + j)
Building four-digit symmetric numbers
The outer loop iterates over each possible digit-sum (same). For each sum, the inner loops pick a candidate a from the pre-computed list two[same] to serve as the first two digits of a four-digit number. The condition a * 100 > high provides an early break: once the smallest possible four-digit number formed with a exceeds the upper bound, no larger a can produce a valid number, so the loop stops.
A further guard if a > 9 eliminates numbers with a leading zero, ensuring that the constructed four-digit integer truly has four digits.
Inside the innermost loop, a second candidate b (also from two[same]) supplies the last two digits. The full number x = a * 100 + b is formed, and the interval check low <= x <= high determines whether to increment the result.
for same in two:
for a in two[same]:
if a * 100 > high:
break
if a > 9: # no leading zero
for b in two[same]:
x = a * 100 + b
if low <= x <= high:
result += 1
Returning the final count
After processing both two-digit and four-digit candidates, the function returns the accumulated total.
return result
Edge Cases Handled
The algorithm explicitly addresses intervals that contain only two-digit numbers by performing an early return when high < 1000. This prevents the four-digit construction logic from executing when it cannot possibly succeed.
Leading zeros are excluded for four-digit numbers through the condition if a > 9. Consequently, numbers such as 0011 are not mistakenly counted as four-digit symmetric integers.
The range check low <= n <= high inside the two-digit loop and the analogous check for x in the four-digit loop guarantee that numbers falling outside the user-specified bounds are ignored, even when the pre-computed groups contain values outside the interval.
The break condition if a * 100 > high ensures that once the smallest four-digit number formed with a particular prefix exceeds the upper bound, the algorithm stops iterating over larger prefixes, thereby handling the situation where the interval ends before the next viable four-digit candidate.
Performance Optimizations
The use of a defaultdict to group two-digit numbers by their digit sum eliminates the need to recompute sums repeatedly. By storing each pair once and reusing the groups, the algorithm reduces redundant arithmetic operations.
Iterating over the keys of two (the possible digit sums) rather than over all 100 two-digit numbers cuts down the search space for constructing four-digit numbers. Only combinations that share the same sum are considered, which aligns directly with the symmetry requirement.
The early break if a * 100 > high prevents the inner loops from exploring prefixes that cannot possibly yield a valid four-digit number, saving iterations especially when high is far below the maximum four-digit value (9999).
Skipping prefixes with a leading zero (if a > 9) avoids generating numbers that would be interpreted as three-digit values, thereby reducing unnecessary checks.
Overall, the algorithm balances pre-computation with early termination conditions to achieve a focused enumeration of only those numbers that can satisfy the symmetry property within the given interval.
ELI5 - Simplified Explanation
Imagine a big magical box filled with number cards, starting from the number low all the way up to the number high. This code is a little helper that looks through all those number cards to find the special ones that are symmetric. A symmetric number is like a mirror, where the first half of the digits adds up to the same amount as the second half of the digits.
To find these, the code first looks at all the short numbers that have two digits. For these, it just checks if both digits are exactly the same, like eleven, twenty-two, or thirty-three, because their two sides are perfectly equal.
If the numbers are bigger and have four digits, the code starts by grouping all the two-digit pairs based on their sum. It puts numbers that have the same sum into a little cubbyhole together. Then, it carefully picks one two-digit number to be the front half and one to be the back half to build a four-digit number. It checks if the sum of the digits in the front matches the sum of the digits in the back. If they match, that number gets a gold star inside the result pile. After checking every single possibility, all the gold stars are collected to see how many symmetric numbers were found in total.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | Java | Python | C++ | TS | ||||
| WalkCCC | Java | Python | C++ | ||||||
| leetcode.ca | Java | Python | C++ | C# | Go | Rust | TS | ||
| Progiez | Java | Python | C++ | ||||||
| github | charles-wangkai | Java | |||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 9: Palindrome Number
- problem 1837: Sum of Digits in Base K
Solved On The Same Day
- problem 2908: Minimum Sum of Mountain Triplets I
- problem 2938: Separate Black and White Balls
- problem 2981: Find Longest Special Substring That Occurs Thrice I
- problem 2982: Find Longest Special Substring That Occurs Thrice II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality