LeetCode #1291 Sequential Digits Solution & Explanation

LeetCode Problem

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.

💡Hint 1

Generate all numbers with sequential digits and check if they are in the given range.

💡Hint 2

Fix the starting digit then do a recursion that tries to append all valid digits.


Solution

In our first try, we use the length of low and high numbers to control a while loop.

C# Solution

Solution1

public class Solution {
    public IList<int> SequentialDigits(int low, int high) {
        List<int> res = new List<int>();

        int len = low.ToString().Length;
        int highLen = high.ToString().Length;
        int startNum = 1;
        while (true) {
            if(startNum+len<=10){
                int num = genNum(startNum, len);
                if (num > high){
                    break;
                }
                if (num >= low && num <= high){
                    res.Add(num);
                }
            }
            
            if(startNum == 9){
                startNum = 1;
                len+=1;
            }
            else{
                startNum+=1;
            }

            if(len>highLen){
                break;
            }
        }

        return res;
    }

    private int genNum(int start, int length) {
        int result = 0;
        int curr = start;
        for (int i = 0; i < length; i++) {
            result = result * 10 + curr;
            if (curr == 9){
                break;
            }
            curr+=1;
        }
        return result;
    }
}

The genNum method generates sequential numbers. It starts from a given starting number (start) and generates numbers with a specific length (length). It iterates through each digit, incrementally adding it to the result.

The statement startNum + len <= 10 is a conditional statement, which ensures that the generation of sequential numbers does not exceed the range of single digits (1 to 9).

When the sum of startNum and len is less than or equal to 10, this condition holds true. This design ensures that the maximum value of the generated sequential numbers in the loop does not exceed 10, thereby ensuring the validity of these numbers.


Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link : Sequential Digits – LeetCode

Some Random LeetCode posts

Leave a Reply

Your email address will not be published. Required fields are marked *