In today's LeetCode Problem of the Day, we tackle 1291: Sequential Digits. This problem asks us to return all integers in a given range [low, high] where each digit is exactly one more than the previous digit (e.g., 123, 234, 345).
We explore two approaches:
Brute Force Approach
The naive solution iterates through every number from low to high, checking if its digits are sequential. While straightforward, this is inefficient for large ranges.
Optimized String Approach (Best Solution)
A more elegant method generates sequential numbers directly. Starting from digits 1 through 9, we build numbers by appending the next digit until the number exceeds high. This avoids checking invalid numbers and runs in O(1) time relative to the input size.
Java Implementation Highlights:
- Use a nested loop: outer loop for the starting digit (1-9), inner loop to extend the digit sequence.
- Convert the constructed number to an integer and check if it falls within
[low, high]. - Add valid numbers to a result list.
Complexity:
- Time: O(1) — at most 45 sequential numbers exist (from 12 to 123456789).
- Space: O(1) — excluding output.
Watch the full video on Explainedbychhavi for a step-by-step walkthrough.