#3870
Count Commas in Range
EasyMathMathematical countingRange-based calculations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Count commas directly based on the number of digits in the range. Numbers from 1000 to n will each contribute one comma.
⚙️
Algorithm
3 steps- 1Step 1: If n < 1000, return 0.
- 2Step 2: Calculate the number of integers from 1000 to n, which is n - 999.
- 3Step 3: Return the count of integers from 1000 to n as the total number of commas.
solution.py2 lines
1def count_commas(n):
2 return max(0, n - 999)ℹ
Complexity note: Only a few arithmetic operations are performed, leading to constant time complexity.
- 1Numbers from 1000 to 9999 have exactly one comma.
- 2Count commas based on ranges rather than individual numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.