Approach
Breadth-first search
For Count Fancy Numbers in a Range, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 81 lines of Python from the credited upstream file count-fancy-numbers-in-a-range.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def countFancy(self, l, r):7 """8 :type l: int9 :type r: int10 :rtype: int11 """12 def count(x):13 def length(n): 14 result = 015 while n:16 result += 117 n = 1018 return result19 20 def total(n): 21 result = 022 while n:23 result += i%1024 n = 1025 return result26 27 def check(n): 28 asc = desc = True29 while n >= 10:30 if not (n10)%10 < n%10:31 asc = False32 if not (n10)%10 > n%10:33 desc = False34 n = 1035 return asc or desc36 37 def bfs(x): 38 result = [i for i in xrange(1, min(9, x)+1)]39 for diff in (1, -1):40 q = []41 for i in xrange(1, min(9, x)+1):42 q.append(i)43 while q:44 new_q = []45 for u in q:46 curr = u%1047 d = curr+diff48 while 0 <= d <= 9:49 v = u*10+d50 if v <= x:51 new_q.append(v)52 result.append(v)53 d += diff54 q = new_q55 return result56 57 def dp(x): 58 l = length(x)59 mx = l*960 dp = [[0]*(mx+1) for _ in xrange(2)] 61 dp[1][0] = 162 base = 10**(l-1)63 for i in xrange(l):64 new_dp = [[0]*(mx+1) for _ in xrange(2)]65 v = (xbase)%1066 base = 1067 for t in xrange(2):68 for s in xrange(mx+1):69 if dp[t][s] == 0:70 continue71 for d in xrange((v if t == 1 else 9)+1):72 new_dp[t == 1 and d == v][s+d] += dp[t][s]73 dp = new_dp74 return sum(dp[0][i]+dp[1][i] for i in xrange(mx+1) if lookup[i])75 76 lookup = [check(i) for i in xrange(length(x)*9+1)]77 good = bfs(x)78 return len(good)+dp(x)-sum(lookup[total(x)] for x in good)79 80 return count(r)-count(l-1)81