Always consider what happens when the worst case occurs.

Constant-time: O(1)

Running time is constant and is not dependent on the size of input. This includes:

  • loops that executes a set amount of times (including nested)
    • for example, for i in range(10)
  • sequence of basic operations
  • conditionals (if all cases take O(1))

Common loops

  • non nested loops that executes based on input size:
    • e.g. for i in range(n)
  • nested loops that only have statements inside:
    • e.g. for i in range(n): for j in range(m):
  • nested loops where the inner loop stops based on instead of :
    • e.g. for i in range(n): for j in range(n):

Functions and Procedure Calls

  • series of functions / procedure calls: take the highest time complexity
  • when a loop is applied, apply the product rule: if a loop iterates times and the inside call has complexity, then overall the loop will have complexity .

Difficult Examples

int x = 0;
int y = 0;
for(int i = 1; i <= n; i = i * 3) {
	x = x + 5;
	x++;
	y = y * y;
}
x = 0
y = 0
 
i=1
while i<=n:
	x +=  5
	x+=1
	y *= y
 
	i *= 3
int y = 0;
for(int j = 1; j*j <= n; j++)
	y = y*y*50;
y = 0
 
while j**2 <=n:
	y = y*y*50
	j++
int b = 0;
for(int i = n; i > 0; i--) {
	for(int j = 0; j < i; j++) {
		b = b + 4;
	}
}
int y = 1;
int j = 0;
for(j = 1; j <= 2 * n; j = j + 2) 
	y = y + j;
 
int s = 0;
for(int i = 1; i <= j; i++)
	s++;
int b = 0;
for(int i = 0; i < n; i++) {
	for(int j = 0; j < i * n; j++) {
		b = b + 5;
	}
}
int x = 0;
for(int i = 1; i <= n; i = i * 3) {
	if (i%2 != 0) {
		for(int j = 0; j < i; j++) {
			x++;
		}
	}
 }
int t = 0;
for(int i = 1; i <= n; i++)
   for(int j = 0; j*j < 4*n; j++)
      for(int k = 1; k*k <= 9*n; k++)
         t++;
int y = 0, s = 0;
for(int j = 0; j < n + 1; j++) {
   y=y+j;
}
for(int i = 1; i <= y; i++) {
   s++;
}
int i=1, z=0;
while(z < n*(n+1)/2)
{
	z+=i; i++;
}
int a = 0;
int k = n*n*n;
while(k > 1)
{
   for (int j=0; j<k; j++) { 
	   a--; 
   }
   
   k = k/2; 
}