...
for digit in num_as_string[::-1]:
. In this loop, it's just \$O(n)\$ where n is just number of digits of the input.
I am assuming the time complexity of this code is something like O(n) + 2 * O(number of digits in base10) which is linear.
This is not quite right. The second and third loops will loop the number of digits in base \$b_2\$ (not in base 10), which is approximately \$n * \frac {\log b_1}{\log b_2}\$ times, so your time complexity would be:
$$O(n) + 2 * \frac{\log b_1}{\log b_2} * O(n)$$
which is of course is still simply \$O(n)\$.
This also means your space complexity is not "O(number of digits in base10)"; it is O(number digits in \$b_2\$), but again, these are constant factors, and becomes simply \$O(n)\$.
Still, it is unusual to express it the complexity in terms of the number of digits of the input. Usually, you have an input value N, (which can be expressed in \$\log_{b_1}N\$ digits), and would express the complexity of the algorithm as \$O(\log N)\$.
Except ...
res = ''
for i in converted[::-1]:
res += string.hexdigits[i].upper()
Which actually makes this an \$O(n^2)\$ algorithm, since while you are looping, you are copying all previous digits to add one character. Convert all the digits into the appropriate character, and then join them all together at once:
res = ''.join(string.hexdigits[digit] for digit in converted[::-1]).upper()
Using % b2
and //= b2
back-to-back is generally inefficient. When the math library computes one, it almost always has computed the other as a side effect. The divmod()
function returns both values:
while base10 > 0:
base10, digit = divmod(base10, b2)
converted.append(digit)
Practice for a coding interview? You'd better clean up this code considerably. In addition to @Reinderien's suggestions, look at your two return
statements
return '-' + str(base10) if is_neg else str(base10)
return '-' + res if is_neg else res
These look exactly the same, if res = str(base10)
. Try to rework your code to handle the is_neg
test only once, and only use 1 return
statement.