Advertisement
DeepRest

Sequential Digits

Jan 22nd, 2022 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. #1. Brute Force
  2. class Solution:
  3.     def sequentialDigits(self, low: int, high: int) -> List[int]:
  4.         res = []  
  5.         #s = '0123456789'
  6.         n = len(str(low))
  7.         #fix the size (2 to 9)
  8.         for i in range(n,10):
  9.             #fix the starting digit
  10.             for j in range(1, 10-i+1):  
  11.                 #build the number with sequential digits
  12.                 #num = int(s[j:i+j])
  13.                 num = 0
  14.                 for k in range(i):
  15.                     num = (num<<3)+(num<<1)+j+k
  16.                 if num>high:
  17.                     return res
  18.                 if num>=low:
  19.                     res.append(num)
  20.         return res
  21.  
  22. #2. BFS
  23. class Solution:
  24.     def sequentialDigits(self, low: int, high: int) -> List[int]:
  25.         ans = []
  26.         queue = deque(range(1, 9))
  27.         while queue:
  28.             curr = queue.popleft()  
  29.             if (rem := curr%10) != 9:
  30.                 num = curr*10+rem+1
  31.                 if num > high:
  32.                     return ans
  33.                 queue.append(num)  
  34.                 if num >= low:
  35.                     ans.append(num)
  36.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement