Skip to main content

Time Complexity

Author: @wingkwong

Overview

Time Complexity is one of the important measurements when it comes to writing an efficient solution. It estimates how much time your solution needs based on some input. If your solution is too slow, even it passes some test cases, it will still consider it as a wrong answer.

The time complexity is denoted by Big O notation. Normally, nn means the input size. For example, if the input is a string ss, then nn would be the length of ss.

image

Estimating Time Complexity

Input sizeTime Complexity
n<=10n <= 10O(n!),O(n7),O(n6)O(n!), O(n^7),O(n^6)
n<=20n <= 20O(2n)O(2^n)
n<=80n <= 80O(n4)O(n^4)
n<=400n <= 400O(n3)O(n^3)
n<=7500n <= 7500O(n2)O(n^2)
n<=106n <= 10^6O(nlogn)O(nlogn), O(n)O(n)
largelargeO(1)O(1), O(logn)O(logn)

Example 1:

In the following case, the time complexity depends on nn. Therefore, it is O(n)O(n).

for (int i = 0; i < n; i++) {
// do something
}

Example 2:

In the following case, the time complexity depends on nn and mm. Therefore, it is O(nm)O(n*m).

for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// do something
}
}

Example 3:

In the following case, the time complexity is O(n)O(\sqrt n). You can see ii<=ni * i <= n as i<=ni <= \sqrt n.

As sqrt() returns double, it would be safe to use ii<=ni * i <= n to check the condition instead of using i<=sqrt(n)i <= sqrt(n).

for (int i = 2; i * i <= n; i++) {
// do something
}

Useful Resources