Skip to content

Time Complexity

  • Behavior as data size goes to Infinity
  • Notation: O( )
  • Most of the notes in this is pure math & code
NN^23N^2100N1000
10^4T:0.1sT:0.3sT:0.001sT:10^-6
10^9T:31yrsT:95yrsT= 100s = 1.66mmT: 10^-6
104104109=NN109
void ex1()
{
    int A[7] = {5, 1, 9 ,3, 5, 9, 5};
    int N=7;
    int T = 4;
    int k;

    k = 0; //executed 1
    while(k < T) // 4 T times
    {
        printf("%4d, ", A[K]); //4 T times
        K++; //4 T times
    }
    printf("\N) //1
}

1 + T + T +T + 1 +1 = 3T + 3 = O( T )


for ( j = 1 (O(1)); j < N (O(N)); j++)
{

}

(N-1)(3T+3) = 3NT-3T+3N-3 = O(NT) N+T = O(N+T)

N2+T=O(N2+T)=TN2(N2notdominater)
for(j = 0; j < N; j++)
{
    printf(a(j));
}

toal TC is Sum

iterjTCiter
00O(1)
11O(1)
22O(1)
.
N-1O(1)

for(j=1; j<= n; j++)
{
    for(k=0; k<t; k++)
    {
        printf(A[K]);
    }
}
jTCiters(j)=O(T)
1O(T)
2O(T)
3O(T)
......
......
NO(T)
sum=O(t)+O(t)+...O(t)=NT=O(NT)

TC of Function Calls

int count(int nums[], int T, int V) // this functions has TC:O(T)
{
    int count = 0;
    for (int k=0; k<T; k++)
    {
        if(nums[k] == V)
            count++;
    }
    return count;
}
TCiter(k)=O(1)+O(1)+O(1)...+O(1)=O(1)
  • TCiter stands for time complexity of that iteration, in this example its the for loop for the function
kTC1iter(k)=O(1)
0O(1)
1O(1)
2O(1)
3O(1)
......
......
T-1O(1)
  • We do O(1) T times, so ...
O(1)+O(1)...+O(1)=O(1)T=O(T)

Remember our function count, what if we called it, what would its time complexity be if it looked like this?

count(nums,n,val);

AnswerO(N)
Tip: any function that processes an array will have a loop!

Sequential Loops

Write the O( ) time complexity of this code

for(j = left; j<= right; j++)
{
    printf("%d,  ", A[i]);
}
for(i = 0; i < p; i++)
{
    for(k=0; k<r; k++)
        printf("B");
}
Answer

Total TC: O(C + Pr) C = Right - Left + 1

TC iter j * x

for(j=1; j<=N; j=j*2)
{
    for(k=0;k<j;k++)
        printf(A[k]);
}
jTc1iter(j)=O(j)
1O(1)
2O(2)
4O(4)
8O(8)
NO(N)
1+2+4+8+16+32...+N20+21+22+23+...2P=2N+1121=2P==P=log2N

TC: O(Log_2N)

  • can be written as lgN
  • this is the same proccess if it was j/2

TC j + x

for(v=1; v<=t; v+5)
{
    someFunc(v); //O(V);
}

TC1iter(v) = O(1) + O(1) +O(V) = O(V)

VTciters
5^01O(1)
5^15O(5)
5^225O(25)
5^3125O(125)
TO(T)
50+51+52...+5p=T5p+1151=O(T);

Growth of functions

O = Big Oh            - Upper Bound <=
θ = Theta (Uppercase) - Tight bound =
Ω = Omega (Uppercase) - Lower bound >=
ω = Omega (LowerCase) - Strictly lower bound >
o = little oh         - Strictly upper bound <

Using it:

  • Insertion sort takes O(N^2) or Ω(N)