752. Open the Lock

An integer has sequential digits if and only if each digit in the number is one more than the previous digit.

Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.

1
2
3
4
Example 1:

Input: low = 100, high = 300
Output: [123,234]
1
2
3
4
Example 2:

Input: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]

Constraints:

  • 10 <= low <= high <= 10^9

Solution Sliding Window

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
    public List<Integer> sequentialDigits(int lo, int hi) {
        
        int lenLo = getLen(lo); 
        int lenHi = getLen(hi); 

        int i = lenLo;

        List<Integer> res = new ArrayList<>();
        while (i <= lenHi) {
            res.addAll(buildSeqNums(i, lo, hi));
            i++;
        }
        return res; 
    }

    int getLen(int n) {
        return Integer.toString(n).length();
    }

    String SAMPLE = "123456789";
    List<Integer> buildSeqNums(int n, int lo, int hi) { 

            if (n == 0) return Collections.emptyList();
            int start = 0;
            List<Integer> res = new ArrayList<>();
            while (start + n < SAMPLE.length() + 1) {
                int val = Integer.parseInt(SAMPLE.substring(start, start + n));
                if (val >= lo && val <= hi) {
                    res.add(val);
                }
                start++;
            }
                
            return res;
    }

}