In an online assessment I got one coding challenge and I wrote one recursive code for it. The question was -
Given an integer n, return all the reversible numbers that are of length n.
A reversible number is a number that looks the same when rotated 180 degrees (looked at upside down).
Example:
Input: n = 2
Output: ["11","69","88","96"]
I wrote some kind of recursive approach and it passed.
vector<string> recursion(int n, int m) {
if (n == 0) {
vector<string> res = {""};
return res;
}
if (n == 1) {
vector<string> res = {"0", "1", "8"};
return res;
}
vector<string> ans = recursion(n - 2, m);
vector<string> res;
for (auto subAns: ans) {
// We can only append 0's if it is not first digit.
if (n != m) {
res.push_back('0' + subAns + '0');
}
res.push_back('1' + subAns + '1');
res.push_back('6' + subAns + '9');
res.push_back('8' + subAns + '8');
res.push_back('9' + subAns + '6');
}
return res;
}
vector<string> getAllNumbers(int n) {
return recursion(n, n);
}
I thought because we are calling 5 recursion it is something like 5^N but I want to do exact space and time complexity analysis for it.
Can anyone help me out what could be the exact solution, it is very tricky for me to figure out the exact space time complextiy for recursive approaches