Given an integer
p
and a destination baseb
, return a string representation ofp
in baseb
. The string should have the least significant bit at the end
^ This is the problem I'm giving myself.
The naive recursive algorithm (in C++) I came up with is as follows:
string convertIntToBaseRecursive(int number, int base) {
// Base case
if (!number) return "";
// Adding least significant digit to "the rest" computed recursively
// Could reverse these operations if we wanted the string backwards.
return convertToBaseRecursive(number / base, base) + to_string(number % base);
}
While the algorithm is incredibly simple, I want to make sure I understand the complexity breakdown. My thoughts are below and I would like to know if they are correct, or wrong, and if they are wrong then knowing where I'm off track would be nice!
Claim:
n = logb(p)
is the length of return string- Time complexity:
O(n^2)
- Space complexity:
O(n)
Reasoning:
In order to keep the least significant bit at the end of a string when it is the value we calculate before anything else, we'd either have to:
- Compute the string recursively as we are
- Keep "shifting" the array every time we calculate a bit so we can add the most recent bit to the front of the string, not the end
- Write the string backwards, and reverse it before we return (most efficient)
We're doing the first method in the above C++ algorithm, and the +
operator creates a new string at each stack frame. The initial frame creates and returns a string of length n
, the next frame creates a string of length n-1
, n-2
, n-3
, and so on. Following this trend (without going into a proof of why 1 + 2 + 3 ... + n = O(n^2)
, it is clear the time complexity is O(n^2) = O(logb^2(p))
. We'll also only need to be storing O(n)
things in memory at any time. When the original stack frame resolves (just before algorithm completes) we'll have the memory in terms of a raw string, but before it resolves it will be in terms of a single character (O(1)
) + recursive stack frames (O(n)
). We do this at each level storing n
amounts of single characters until we complete. Therefore the space complexity is O(n)
.
Of course the more efficient version of this solution would be
string convertIntToBaseIterative(int number, int base) {
string retString = "";
while (number) {
retString += to_string(number % base);
number /= base;
}
// Only needed if least significant
reverse(retString.begin(), retString.end());
return retString;
}
I believe this above solution , where n = logb(p)
has:
- Time complexity:
O(n)
- Space complexity:
O(n)
Are these analysis correct or am I off somewhere?