You're wrong in just about every way.
Your algorithm is flat out broken.
For example, "CIIO" and "IICO" are not considered equal, even though one is clearly a permutation of the other. Your algorithm prints nothing if the strings are of equal length but not a permutation (which is weird output).
This algorithm does not have the time/space complexities you mentioned.
Where are you getting O(n^2) from?
The main method doesn't do any looping at all, other than invoking permutation once, so we don't need to look at it.
permutation will first craft a new string by concatenating the 2 input strings; this takes n time and n space (s1 and s2 can't be collected nor can s, they're all in memory as long as permutation is running). You then loop over each character in it, which is also O(n). You then invoke size and length, both O(1) (i.e. ignorable) operations.
So, you have O(n), and then O(n), which is just O(n). (Because it's O(2n), and O(n) means: "If you feed this algorithm data that is incrementally more complicated, as defined by 'having incrementally higher n', and you graph 'n' against 'time/space taken', then eventually, at some unknown point, the graph starts looking like the graph y = x does.
y = 2x looks just like y = x, hence why saying something is O(2n) is useless and therefore not correct. That just becomes O(n). Same reason O(2n^2 + 1000n) is just O(n^2). Because y = 2x^2 + 1000n, eventually, looks exactly like y = x^2 does.
How would one write the correct algorithm?
Depends on what you mean by permutation. Presumably, if shuffling letters around for one of the strings lets you make the second, i.e. ciio and iico are permutation-wise equal, but ccio and ciio are not, nor are cio and ccio.
In that case:
- Turn s1 into a char array. (
O(n)).
- Sort this char array using
Arrays.sort, which is O(n logn) - but you'd have to know that this is the performance characteristic of sort.
- Do the same to s2. (
O(n) + O(n logn)).
- Check that the 2 arrays are equal. (
O(n)).
That sums up to 2 O(n logn) and a whole bunch of O(n), which just becomes O(n logn). It becomes quite easy to 'add them up', you're just looking for the most significant factor; any factors of lesser significance are irrelevant, as are constant repeats of the most complex fcator.
feetandfete