Stepping Numbers in C++


Suppose we have two integers low and high, we have to find and show a sorted list of all the Stepping Numbers in the range [low, high] inclusive. A Stepping Number is an integer means all of its adjacent digits have an absolute difference of exactly 1. For example, 321 is a Stepping Number but 421 is not. So if the input is like low := 0 and high := 21, then the result will be [0,1,2,3,4,5,6,7,8,9,10,12,21]

To solve this, we will follow these steps −

  • create one array temp
  • make one method called solve(), this will take high, seed and len. the len is initially 0
  • if seed > high, then return
  • insert seed into the temp array
  • if seed is 0, then
    • for i in range 1 to 9, perform solve(high, i, 1)
  • otherwise
    • lastDigit := seed mod 10
    • if lastDigit >= 1 and len + 1 <= 10, then solve(high, (seed*10) + lastDigit – 1, len + 1)
    • if lastDigit <= 8 and len + 1 <= 10, then solve(high, (seed*10) + lastDigit + 1, len + 1)
  • The main method will be like −
  • solve(high, 0, 0)
  • sort the temp array
  • make one array ans
  • for i in range 0 to temp size – 1
    • if temp[i] >= low, then insert temp[i] into ans
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
typedef long long int lli;
class Solution {
public:
   vector <lli> temp;
   void solve(int high,lli seed=0, int len =0){
      if(seed>high){
         return;
      }
      temp.push_back(seed);
      if(!seed){
         for(int i =1;i<=9;i++){
            solve(high,i,1);
         }
      } else {
         int lastDigit = seed%10;
         if(lastDigit>=1 && len+1<=10)
            solve(high, (seed*10) + lastDigit-1,len+1);
         if(lastDigit<=8 && len+1<=10)
         solve(high, (seed*10) + lastDigit+1,len+1);
      }
   }
   vector<int> countSteppingNumbers(int low, int high) {
      solve(high);
      sort(temp.begin(),temp.end());
      vector <int> ans;
      for(int i =0;i<temp.size();i++){
         if(temp[i]>=low)ans.push_back(temp[i]);
      }
      return ans;
   }
};
main(){
   Solution ob;
   print_vector(ob.countSteppingNumbers(0,40));
}

Input

0
40

Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21, 23, 32, 34, ]

Updated on: 30-Apr-2020

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements