#3871

Count Commas in Range II

Medium
MathMathematical CountingRange Queries
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Count the number of integers in ranges based on digit length and multiply by the number of commas each range contributes. This avoids iterating through each number.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a total comma counter.
  2. 2Step 2: For each range of digit lengths (1-3, 4-6, ...), calculate how many numbers are in that range up to n.
  3. 3Step 3: Multiply the count of numbers in each range by the number of commas that range contributes and add to the total.
solution.py6 lines
1def count_commas(n):
2    total_commas = 0
3    for digits in range(4, len(str(n)) + 1):
4        total_commas += (min(n, 10**digits - 1) - 10**(digits - 1) + 1) * (digits // 3 - 1)
5    return total_commas
6

Complexity note: The complexity is O(log n) because we only iterate through the number of digits in n, which is logarithmic in relation to n.

  • 1Commas appear only in numbers with 4 or more digits.
  • 2Count ranges of numbers based on digit lengths.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.