Amazon Interview Question
SDE-2sCountry: United States
Interview Type: In-Person
Missed out few points from qn. Corrected in this upload
def step_num_count(n1, n2, num):
count = 0
q = []
q.append(num)
while q:
step_num = q.pop(0)
if step_num >= n1 and step_num <= n2 and (step_num/10):
count += 1
if step_num is 0 or step_num > n2:
continue
last_digit = step_num % 10
step_num1 = (step_num * 10) + last_digit + 1
step_num2 = (step_num * 10) + last_digit - 1
if last_digit is 0:
q.append(step_num1)
elif last_digit is 9:
q.append(step_num2)
else:
q.append(step_num1)
q.append(step_num2)
return count
def main():
count = 0
n1 = input("Enter value of n1:")
n2 = input("Enter value of n2:")
for i in range(10):
count += step_num_count(n1, n2, i)
print "Total stepping num :",count
main()
using System;
public class Program
{
public static void Main()
{
int n= 10 ;
int m = 100;
Console.WriteLine(DisplaySteppingNumber(n ,m));
}
public static int DisplaySteppingNumber(int n ,int m)
{
int count = 0;
for (int i = 1 ; i <= 9 ; i++)
{
findSteppingNum( n , m , i , ref count);
}
return count;
}
public static void findSteppingNum (int n , int m , int stepnum , ref int count)
{
if ( stepnum > m || stepnum == 0 )
{
return ;
}
if (stepnum > n )
{
count ++;
}
int lastDigit = stepnum % 10;
// There can be 2 cases either digit
// to be appended is lastDigit + 1 or
// lastDigit - 1
int stepnumA = stepnum*10 + (lastDigit-1);
int stepnumB = stepnum*10 + (lastDigit+1);
// If lastDigit is 0 then only possible
// digit after 0 can be 1 for a Stepping
// Number
if (lastDigit == 0)
findSteppingNum(n, m, stepnumB , ref count);
// If lastDigit is 9 then only possible
// digit after 9 can be 8 for a Stepping
// Number
else if(lastDigit == 9)
findSteppingNum(n, m, stepnumA , ref count);
else
{
findSteppingNum(n, m, stepnumA , ref count);
findSteppingNum(n, m, stepnumB , ref count);
}
}
}
using System;
public class Program
{
public static void Main()
{
int n= 10 ;
int m = 100;
Console.WriteLine(DisplaySteppingNumber(n ,m));
}
public static int DisplaySteppingNumber(int n ,int m)
{
int count = 0;
for (int i = 1 ; i <= 9 ; i++)
{
findSteppingNum( n , m , i , ref count);
}
return count;
}
public static void findSteppingNum (int n , int m , int stepnum , ref int count)
{
if ( stepnum > m || stepnum == 0 )
{
return ;
}
if (stepnum > n )
{
count ++;
}
int lastDigit = stepnum % 10;
// There can be 2 cases either digit
// to be appended is lastDigit + 1 or
// lastDigit - 1
int stepnumA = stepnum*10 + (lastDigit-1);
int stepnumB = stepnum*10 + (lastDigit+1);
// If lastDigit is 0 then only possible
// digit after 0 can be 1 for a Stepping
// Number
if (lastDigit == 0)
findSteppingNum(n, m, stepnumB , ref count);
// If lastDigit is 9 then only possible
// digit after 9 can be 8 for a Stepping
// Number
else if(lastDigit == 9)
findSteppingNum(n, m, stepnumA , ref count);
else
{
findSteppingNum(n, m, stepnumA , ref count);
findSteppingNum(n, m, stepnumB , ref count);
}
}
}
- montu March 09, 2017