LeetCode 2801: Count Stepping Numbers in Range Solution
Master LeetCode problem 2801 (Count Stepping Numbers in Range), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2801. Count Stepping Numbers in Range
Problem Explanation
Explanation:
- We can solve this problem using a breadth-first search (BFS) approach.
- Starting from each digit from 1 to 9, we perform a BFS traversal by considering all possible next stepping numbers.
- For each stepping number, we check if it falls within the range [low, high].
- We continue the BFS traversal until we exhaust all stepping numbers within the given range.
- Finally, we return the count of stepping numbers modulo 10^9 + 7. Solution:
Solution Code
class Solution {
public int countSteppingNumbers(String low, String high) {
long mod = 1000000007;
long result = 0;
long l = Long.parseLong(low);
long h = Long.parseLong(high);
Queue<Long> queue = new LinkedList<>();
for (long i = 1; i <= 9; i++) {
queue.offer(i);
}
if (l == 0) {
result++;
}
while (!queue.isEmpty()) {
long num = queue.poll();
if (num >= l && num <= h) {
result++;
}
if (num > h) {
continue;
}
long lastDigit = num % 10;
if (lastDigit > 0) {
queue.offer(num * 10 + lastDigit - 1);
}
if (lastDigit < 9) {
queue.offer(num * 10 + lastDigit + 1);
}
}
return (int) (result % mod);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2801 (Count Stepping Numbers in Range)?
This page provides optimized solutions for LeetCode problem 2801 (Count Stepping Numbers in Range) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2801 (Count Stepping Numbers in Range)?
The time complexity for LeetCode 2801 (Count Stepping Numbers in Range) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2801 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2801 in Java, C++, or Python.