Sequential digits are numerical sequences where each digit in a number is incremented by one compared to its predecessor. For example, 123, 234, and 345 are sequential digits because each subsequent number follows a pattern of increasing by one. These sequences are not only intriguing but also have practical applications in mathematics, computer science, and puzzle-solving.
Algorithmic Approach:
The provided Java solution utilizes a TreeSet to maintain a sorted collection of unique sequential digits within the given range. Let’s break down the algorithm:
- Calculate the length of digits in the low and high range numbers.
- Iterate through each starting digit from 1 to 9.
- For each starting digit, generate sequential digits of varying lengths from lowDigitLength to highDigitLength.
- Check if the generated number falls within the specified range.
- Add valid sequential digits to the TreeSet to ensure uniqueness and sorted order.
- Convert the TreeSet to an ArrayList for the final result.
class Solution {
public List<Integer> sequentialDigits(int low, int high) {
int lowDigitLength = Integer.toString(low).length();
int highDigitLength = Integer.toString(high).length();
TreeSet<Integer> list = new TreeSet<Integer>();
for(int startDigit=1;startDigit<=9;startDigit++) {
for(int digitLength=lowDigitLength;digitLength<=highDigitLength;digitLength++) {
int number = getNextNumber(startDigit, digitLength);
if (number>= low && number <= high) {
list.add(number);
}
}
}
return new ArrayList<Integer>(list);
}
private int getNextNumber(int start, int length) {
if (start + length > 10) {
return -1;
}
StringBuilder sb = new StringBuilder(Integer.toString(start));
int nextDigit = start;
for(int i=1;i<length;i++) {
nextDigit++;
sb.append(nextDigit);
}
return Integer.valueOf(sb.toString());
}
}
https://leetcode.com/problems/sequential-digits/