We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Symmetric Integers

Number: 2998

Difficulty: Easy

Paid? No

Companies: Amazon


Problem Description

Given a range [low, high], count how many integers in this range are symmetric. An integer is symmetric if it has an even number of digits (2 * n) and the sum of its first n digits equals the sum of its last n digits. Numbers with an odd number of digits are automatically not symmetric.


Key Insights

  • Only integers with an even number of digits can be symmetric.
  • Convert each integer to a string to easily split it into two halves.
  • Calculate the sum of the first half and the second half digits.
  • Count the integer only if both sums are equal.
  • With high up to 10^4, iterating over the range is computationally efficient.

Space and Time Complexity

Time Complexity: O(n * d) where n is the number of integers in [low, high] and d is the number of digits per integer (constant given the constraints).
Space Complexity: O(1)


Solution

We solve the problem by iterating over each number in the given range. For every integer, we check if it has an even number of digits. If it does, the number is converted to a string and split into two halves. We calculate the sum of the digits in the first half and the second half; if they are equal, we increment our count. This approach uses simple string manipulation, arithmetic, and a loop iteration which are efficient given the constraints.


Code Solutions

def count_symmetric_integers(low, high):
    count = 0
    # Loop through each integer in the range [low, high]
    for x in range(low, high + 1):
        s = str(x)
        # Only consider integers with even number of digits
        if len(s) % 2 == 0:
            mid = len(s) // 2
            # Calculate the sum of the first half of the digits
            first_half = sum(int(ch) for ch in s[:mid])
            # Calculate the sum of the second half of the digits
            second_half = sum(int(ch) for ch in s[mid:])
            # If the two sums are equal, the number is symmetric
            if first_half == second_half:
                count += 1
    return count

# Example usage:
print(count_symmetric_integers(1, 100))   # Expected output: 9
print(count_symmetric_integers(1200, 1230))  # Expected output: 4
← Back to All Questions