Finding Integers with Sequential Digits in a Range
Problem Definition
An integer is defined as having sequential digits if every digit in the number is exactly one greater than the previous digit. For example, 123 and 3456 satisfy this condition, while 135 or 121 do not.
Given two integers, low and high, the task is to return a sorted list of all integers within the inclusive range [low, high] that consist of sequential digits.
Examples
Example 1:
- Input: low = 100, high = 300
- Output: [123, 234]
Example 2:
- Input: low = 1000, high = 13000
- Output: [1234, 2345, 3456, 4567, 5678, 6789, 12345]
Approach 1: Pre-calculation and Filtering
Since the constraint limits the input to 109, the maximum possible sequential number is 123456789. The total number of valid sequential integers is small (only 36). We can generate all possible valid numbers by iterating through possible lengths and starting digits, then filter the results based on the provided bounds.
/**
* @param {number} low
* @param {number} high
* @return {number[]}
*/
var sequentialDigits = function(low, high) {
const candidates = [];
// Iterate through the number of digits (length)
for (let len = 2; len < 10; len++) {
// Iterate through the starting digit (1 to 9)
for (let start = 1; start <= 10 - len; start++) {
let currentNum = 0;
let digit = start;
// Build the sequential number
for (let i = 0; i < len; i++) {
currentNum = currentNum * 10 + digit;
digit++;
}
candidates.push(currentNum);
}
}
// Filter candidates within the [low, high] range
return candidates.filter(num => num >= low && num <= high);
};
Approach 2: String Construction
This approach constructs numbers as strings to simplify the logic. By determining the required length range from the input bounds, we can build strings by concatenating incrementing characters. This avoids arithmetic construction complexities and allows for parsing back to integers for comparison.
/**
* @param {number} low
* @param {number} high
* @return {number[]}
*/
var sequentialDigits = function(low, high) {
const result = [];
const minLen = String(low).length;
const maxLen = String(high).length;
for (let len = minLen; len <= maxLen; len++) {
for (let start = 1; start <= 10 - len; start++) {
let str = '';
let current = start;
for (let i = 0; i < len; i++) {
str += current;
current++;
}
const num = parseInt(str, 10);
if (num > high) {
return result;
}
if (num >= low) {
result.push(num);
}
}
}
return result;
};