Taro Logo

Count Integers With Even Digit Sum

#1 Most AskedEasy
Topics:
Math

Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even.

The digit sum of a positive integer is the sum of all its digits.

Example 1:

Input: num = 4
Output: 2
Explanation:
The only integers less than or equal to 4 whose digit sums are even are 2 and 4.    

Example 2:

Input: num = 30
Output: 14
Explanation:
The 14 integers less than or equal to 30 whose digit sums are even are
2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.

Constraints:

  • 1 <= num <= 1000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the upper bound (maximum possible value) for the input integer `num`?
  2. Are negative numbers or zero possible inputs, or is `num` strictly a positive integer as stated in the problem description?
  3. Should the solution account for performance at scale (e.g., up to $10^9$ or higher), or will `num` be relatively small so that a simple iteration is sufficient?
  4. What should be returned if `num` is less than 1, or is the minimum input guaranteed to be 1?
  5. Is the definition of a digit sum strictly standard (i.e., base-10 sum of individual digits), or should we consider any specific edge cases like leading zeros?

Brute Force Solution

Approach

The brute force approach for this problem involves examining every single number from one up to your given upper limit, one by one, to see if it meets the condition. For each number, you take all of its individual digits, add them together, and check if that total sum is an even number.

Here's how the algorithm would work step-by-step:

  1. Start at the number one.
  2. Look at the current number and separate it into its individual digits.
  3. Add all of those individual digits together to find their total sum.
  4. Check if this total sum can be divided evenly by two, which means it is an even number.
  5. If the sum is indeed even, keep a mental tally or point a finger to record that you found a valid number.
  6. Move on to the very next number in line.
  7. Repeat this entire process of separating digits, adding them up, and checking if the sum is even for every single number up to the upper limit you were given.
  8. Once you have checked every number all the way to the top limit, look at your final tally to see how many valid numbers you found and report that total.

Code Implementation

class Solution:
    def countEven(self, upper_limit: int) -> int:
        valid_number_count = 0

        # We iterate from one up to the upper limit to examine every single number as required
        for current_number in range(1, upper_limit + 1):
            digit_sum_total = 0
            number_copy = current_number

            # We extract individual digits to compute their cumulative sum for the parity check
            while number_copy > 0:
                digit_sum_total += number_copy % 10
                number_copy //= 10

            # We check if the digit sum is divisible by two to determine if the number is valid
            if digit_sum_total % 2 == 0:
                valid_number_count += 1

        return valid_number_count

Big(O) Analysis

Time Complexity
O(n log₁₀ n) – For each of the n integers from 1 up to the given upper limit, we must examine its individual digits to calculate their sum. Extracting the digits of any given number takes a number of operations proportional to the base-10 logarithm of that number, or log₁₀ n. As we repeat this digit-summing process sequentially for all n numbers, the total number of operations approximates n * log₁₀ n. By dropping the constant factors, this overall cost simplifies to the Big O time complexity of O(n log₁₀ n).
Space Complexity
O(1) – The algorithm only requires a few scalar primitive variables to store the current number, the running digit sum, and the tally of valid numbers. No auxiliary data structures, lists, or recursive call stacks are created during the execution. Because the amount of extra memory used remains constant regardless of how large the input number N is, the auxiliary space complexity is constant.

Optimal Solution

Approach

Instead of checking every single number one by one and adding up their digits, we can use a clever mathematical pattern to count the valid numbers almost instantly. By looking at how even and odd sums behave in groups of numbers, we can figure out the answer with a simple formula.

Here's how the algorithm would work step-by-step:

  1. Imagine lining up all the numbers from one up to your target number in sequential order.
  2. Notice that every time you move through a small block of numbers, the sums of the digits alternate predictably between even and odd.
  3. Because of this alternating pattern, exactly half of the numbers in any complete block will have an even digit sum.
  4. Take the target number, divide it in half by ignoring any leftover fractions, and that gives you the count for all the complete blocks.
  5. For the very last number left over at the end, check if its digits add up to an even number.
  6. If that final leftover sum is even, include it in your final count; otherwise, leave it out.
  7. Combine the counts from the complete blocks and the final check to get your total answer immediately without doing heavy calculations for every single number.

Code Implementation

def count_even_digit_sum(target_number):
    # Half the numbers in complete blocks always yield an even digit sum.
    base_count = target_number // 2

    digit_sum_accumulator = sum(int(digit_char) for digit_char in str(target_number))

    # The final boundary number dictates whether the trailing offset is included.
    has_even_digit_sum = (digit_sum_accumulator % 2 == 0)

    return base_count + (1 if (target_number % 2 != 0 and has_even_digit_sum) else 0)

Big(O) Analysis

Time Complexity
O(log n) – The input size is n, and the cost is driven by extracting the individual digits of the final number to check its digit sum. Extracting the digits of a number requires a number of operations proportional to the number of digits it contains, which grows logarithmically with respect to the input value n. Since the rest of the approach relies on constant time arithmetic operations like division and modulo, the total operations scale with the digit length of n, which simplifies to O(log n).
Space Complexity
O(1) – The algorithm relies entirely on a few scalar variables to perform basic arithmetic operations and a direct digit-sum check on the final leftover number. Because it computes the result mathematically using division and modulo operations without allocating any dynamic data structures or recursive calls, the extra memory usage remains constant regardless of the magnitude of the input integer N. Therefore, the auxiliary space complexity is strictly O(1).

Edge Cases

Minimum possible input where num is equal to 1
How to Handle:
The algorithm correctly calculates the digit sum of 1 as 1, recognizes it is odd, and returns a count of 0.
Input num is a single-digit even number such as 2
How to Handle:
It evaluates integers 1 and 2, finds that only 2 has an even digit sum, and returns a count of 1.
Input num is a power of 10 like 100
How to Handle:
The digit sum function processes each number up to 100 independently and correctly sums the valid even counts.
Maximum constraint boundary value for num
How to Handle:
Since the upper bound is typically small such as 1000 in this problem, a simple iterative approach easily scales without performance issues.
Numbers with trailing zeros like 20 or 200
How to Handle:
The modulo and division digit extraction logic accurately handles zeros without altering the core sum calculation.
Inputs where all digits are nine such as 99
How to Handle:
The digit sum accumulates correctly to 18, which is even, and counts the number as valid.
Zero or negative inputs violating the positive integer constraint
How to Handle:
Problem constraints specify a positive integer, but the function can guard against this by checking if num is less than 1 and returning 0.
Language-specific integer overflow during digit summation
How to Handle:
Standard 32-bit or 64-bit integers easily accommodate the small intermediate values produced by typical problem constraints.
0/10 completed