I’m trying to brush up on my big o calculations. If I have function that shifts all of the items to the right of ‘i’ 2 spaces I have a formula that looks something like:
(n -1) + (n - 2) + (n - 3) ... (n - n)
Where the first iteration I have to move (x-1) items, the second (x-2) items, and so on…
the method:
int[] s = {1,2,3,4, , }
public static char[] moveStringDownTwoSpaces(char[] s){
for(int j = 0; j < s.length; j++){
for(int i = s.length-3; i > j; i--){
s[i+2] = s[i];
}
return s;
}
}
I know this is O(n^2), but I don’t quite understand the math behind transforming this:
(n -1) + (n - 2) + (n - 3) ... (n - n)
into this
O(n^2)
In my mind if n = 5 (String is of length 5), I would have…
(5-1) + (5-2) + (5-3) + (5-4) + (5-5) = 5(5 - ???)
which is
(n-1) + (n-2) + (n-3) + (n-4) + (n-5) = n(n - ???)
so that gives me 5*5 = 25 which is n^2. but what is the ??? I don’t know what to put for the variables in the formula. I don’t even know if I’m even going by this the correct way. AKA I forgot how to do math 🙁
Just rewrite the following as:
which is equal to:
(n(n+1)/2 - n).Now you can see it is
O(n^2).As noted by @hvd you may want to put the
returnstatement outside the loop.