Dynamic Programming21 sections · 916 units
Open in Course

Stepping Numbers - Implementation

Handling started flag

When started=falsestarted = false: placing 0 keeps started=falsestarted = false. Placing 1-9 sets started=truestarted = true and lastDigitlastDigit. When started=truestarted = true: only place digits within 1 of lastDigitlastDigit. Update lastDigitlastDigit for next position. Edge case: what's the first digit of 0? We define single-digit numbers as valid (no adjacent pair to check). Time: O(n2102)=O(n)O(n \cdot 2 \cdot 10 \cdot 2) = O(n) where n=log10Nn = \log_{10} N. The constants are small. Space: O(logN10)O(\log N \cdot 10) for memoization table.

Time complexity: O(logN10)O(\log N \cdot 10).

Space complexity: O(logN)O(\log N).