Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to Find Out the Occurrence of a Digit from a Given Range in Python
When working with digit counting problems, we need to find how many times a specific digit appears in a range of numbers. This problem asks us to count occurrences of digit d in all numbers from 1 to n.
For example, if n = 45 and d = 5, we need to count digit 5 in numbers: [5, 15, 25, 35, 45], giving us a total count of 5.
Using Recursive Approach
The recursive solution breaks down the problem by processing digits systematically ?
class Solution:
def solve(self, n, d):
if n < 0:
return 0
k = n // 10 - 1
ans = self.solve(k, d) * 10 + k + 1
if d == 0:
ans -= 1
m = n // 10 * 10
while m <= n:
ans += str(m).count(str(d))
m += 1
return ans
# Test the solution
solution = Solution()
result = solution.solve(45, 5)
print(f"Digit 5 appears {result} times in range 1 to 45")
Digit 5 appears 5 times in range 1 to 45
Using Simple Iterative Approach
A more straightforward method iterates through all numbers and counts digit occurrences ?
def count_digit_occurrences(n, d):
count = 0
for i in range(1, n + 1):
count += str(i).count(str(d))
return count
# Test with different examples
print(f"Digit 5 in range 1-45: {count_digit_occurrences(45, 5)}")
print(f"Digit 1 in range 1-100: {count_digit_occurrences(100, 1)}")
print(f"Digit 0 in range 1-20: {count_digit_occurrences(20, 0)}")
Digit 5 in range 1-45: 5 Digit 1 in range 1-100: 21 Digit 0 in range 1-20: 2
How the Recursive Algorithm Works
The recursive approach uses these key steps:
-
Base case: If
n < 0, return 0 - Recursive calculation: Count occurrences in smaller ranges
- Special handling: Adjust count for digit 0 (no leading zeros)
- Final range: Count occurrences in remaining numbers
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(log n) | O(log n) | Large ranges |
| Iterative | O(n × log n) | O(1) | Small ranges, clarity |
Practical Example
Let's trace through the numbers containing digit 5 in range 1-45 ?
def find_numbers_with_digit(n, d):
numbers = []
for i in range(1, n + 1):
if str(d) in str(i):
numbers.append(i)
return numbers
# Find all numbers containing digit 5
numbers_with_5 = find_numbers_with_digit(45, 5)
print(f"Numbers containing digit 5: {numbers_with_5}")
print(f"Total count: {len(numbers_with_5)}")
Numbers containing digit 5: [5, 15, 25, 35, 45] Total count: 5
Conclusion
Use the iterative approach for simple cases and better readability. The recursive method is more efficient for large ranges but requires careful handling of edge cases like digit 0.
