Dynamic Programming21 sections · 915 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(n⋅2⋅10⋅2)=O(n)O(n \cdot 2 \cdot 10 \cdot 2) = O(n) where n=log⁡10Nn = \log_{10} N. The constants are small. Space: O(log⁡N⋅10)O(\log N \cdot 10) for memoization table.

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

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