Space and time complexity - sorting

function compareStringLengths ( a, b )
{
if ( a.length < b.length )
return -1;
if ( a.length > b.length )
return 1;
return 0;
}
var fruits = [ "apple", "pear", "orange", "banana" ];
fruits.sort ( compareStringLengths );
Can someone please tell me the time and space complexity of this code? I'm guessing the time complexity is O(n^2).

Space complexity: linear, i.e. O(n) (because all your data is in an array)
Time complexity: O(n log(n)) (because of sorting)

Related

What is the time complexity of this algorithm if I know n > m?

I have the following algorithm that finds the items in common of two sorted lists:
findIntersection(List1, List2) {
list intersection;
int i = 0;
int j = 0;
while i < size of List1 and j < size of List2 {
if List1[i] < List2[j] {
i++;
}
else if List1[i] > List2[j] {
j++;
}
else {
add List1[i] to intersection;
i++;
j++;
}
}
return intersection;
}
I think the time complexity is O(m+n), but what if I know that the size of List2 is greater than the size of List1?
My conclusion was that it would still be O(m+n) because in a worst case scenario where both lists have no items in common, the algorithm will still have to visit every single item in both lists, independent of their size. For example, if List1 = {10, 20, 100} and List2 = {5, 15, 25, 35, 45, 55, 65, 75, 85, 95}. But I read online that in algorithms where the time complexity is O(m+n), it we know that n>m, it becomes O(n), so now I am not sure I am correct.
You're right in your thinking, the loop will never run only n times as long as m > 1. And it is always true to say that the complexity is O(n + m). But think about this:
If you know that n > m, then n + m < n + n = 2n.
So then O(n + m) = O(2n) = O(n).
It would be O(x), x being whichever of n and m is greater. Assuming n>m, in the worst-case scenario, it would be O(m+(n-m)) which is still O(n).

Find an upper and lower bound of following code

I need to find a closest upper and lower bound of following code. I am beeginer in this so sorry for my mistake.
Upper bound for p() is O(log(n)), and lower bound is O(1)
Upper bound for notp() is O(log(n)), and lower bound is O(1)
I think that lower bound is O(1) because if I have n=4 then I get in the loop and since n%i==0 I call p() and it notice that is not a prime number so O(1) then since i=2 the other notp would not be executed. That is bast case scenario.
Worst case scenario that I go through loop so that log(n), and execute a p and a upper bound is O(log(n)) so it is O(log(n)^2) but I am not so sure that this is good, please tell me where I made a mistake?
int i;
for (i = 2; i*i <= n; i++) {
if (n % i == 0) {
p();
break;
}
}
if(i*i > n)
notp();
For order calculations, you would normally multiply them together when there is a loop.
for( i = 0; i < n ; i++ ){
DoSomething(i);
}
That would be O(n), as the loop is a single case.
A nested loop would be
for( i = 0; i < n ; i++ ){
for( j =0; j < n; j++ ){
DoSomething(i,j);
}
}
That becomes O( n^2 ) as they are additive.
If you have non-nested loops...
for( i = 0; i < n ; i++ ){
DoSomething(i);
}
for( j = 0; j < sqrt(n) ; j++ ){
DoSomething(j);
}
Then the O( x ), is the largest term. That is because for very large n, the smaller values of x don't matter.
So you have a loop in your case, which is O( sqrt( n ) ). That is because it is limited by i *i being less than n.
Then either one of p() or notp() will be called.
(I think p() and notp() are the wrong way round).
Re-factoring your code....
int i;
for (i = 2; i*i <= n; i++) {
if (n % i == 0) {
/* p(); */
break;
}
}
if(i*i > n)
notp();
else
p();
So we have the O( sqrt(n) ) time plus either of the p / notp functions which are O( log(n) )
O( sqrt(n ) + log(n) )
As the sqrt grows faster than n, it overpowers the log(n) wikipedia Big O, leaving it as the final value.
O( sqrt(n) )
As the termination condition of the loop is i*i <= n, the most possible number of iteration of the loop is sqrt(n). As there is a break in the condition of n % i == 0, the worst case of this part is sqrt(n) + log(n) which is O(sqrt(n)). Also, eighter the second condition is true or not, as the worst case of nopt() is O(log(n)), the worst case of the algorithm in total is O(sqrt(n)).

Time complexity for two nested for loops

This question is for revision from a past test paper just needed advice if I on the right track.
Work out the time complexity T(n) of the following piece of code in terms of number of operations for a given integer n:
for ( int k = n; k >0; k /= 3 ) {
for ( int i = 0; i < n; i += 2 ) {
// constant number C of elementary operations
}
for ( int j = 2; j < n; j = (j*j)) {
// constant number C of elementary operations
}
}
So I thought the outer loop would be O(logn), the first inner loop would be O(n) and the second inner loop would be O(logn). Just wanted to know if I had a rough idea and how to move forward from here.
There was recently a question somewhat similar few days ago for which I provided a step-by-step description of complexity analysis: https://stackoverflow.com/a/49093954/926701
The outer loop is indeed O(log3(n))
The first inner loop is indeed O(n)
The second inner loop is O(log2(log2(n)))
Informally, for the second loop, with j(k) the sequence of values taken by the index j of the for loop, we can write:
j(1) = 2, j(2) = j(1)^2 = 4, j(3) = j(2)^2 = 16, ..., j(k) = j(k-1)^2 >= n
=> j(k) = j(k-1)^2 = j(k-2)^4 = ... = j(1)^(2^k) = 2^(2^k)
=> k = log2(log2(n))
Since the number of operations in the inner loops is independent from that of the outer loop, we can multiply the complexity:
T(n) = O(log3(n) * (n + log2(log2(n))))
= O(n.log3(n))
because log2(log2(n)) << n as n -> +Inf.

What's the running time of this "compute all palindrome substrings" algorithm?

public PriorityQueue<String> findPalindromesSubstring(String string) {
PriorityQueue<String> palindromes = new PriorityQueue<>();
string = string.replace("","#");
for (int i = 0; i < string.length(); i++) { //n iterations
int j = 0;
while (i-j >= 0 && i+j < string.length() && string.charAt(i-j) == string.charAt(i+j)) {
String palindrome = string.substring(i-j, i+j+1);
if (palindrome.charAt(0) != '#') {
palindromes.add(palindrome.replace("#", ""));
}
j++;
}
}
return palindromes;
}
I used a PriorityQueue because I need the palindrome substrings sorted alphabetically. At the moment I don't care about duplicates, but I am not sure about the worst case running time the result, from my understanding it is something like
n (chars in string because of for loop)
*
n (max possible length of a palindrome because of inner while loop/2)
*
log(max number of palindromes because of PriorityQueue's add operation)
So the running time is O(n^2*logn) ? Or should I replace one of the n with something else?
Running time complexity is O(N^3*log(N^2)). Let's take a closer look at palindromes.add(palindrome.replace("#", "")); replace function takes O(n), add function makes O(lg N^2) comparisons (because we have at most N^2 palindromes, so height of heap is lg N^2). Each comparison of a string takes O(N) so total time of this line is O((log N^2) * N + N)

What is the time complexity of the following method in terms of Big-O notation?

Help me solve the time complexity of this method below here:
void method(int n, int[] array)
{
int i = 0, j = 0;
for(; i < n; ++i)
{
while(j < n && array[i] < array[j])
{
j++;
}
}
}
The runtime is O(n).
In some iterations of the outer loop the inner loop might progress several times and at other it might not progress at all, but in total there will be at most n increases of j. As this is independent of when (which values of i) this happens, you might say this is O(n) for the outer loop plus O(n) for the (up to) n increases of j. O(n) + O(n) = O(n).
This is contrary to the typical 'loop inside loop' which would perform n iterations of the inner loop for every iteration of the outer loop and thus be O(n) * O(n) = O(n^2).

Resources