Introduction
Time complexity plays a vital role while writing the solutions for a particular problem. What do you mean by time complexity?.
Depending on the number of elements, the time the code or the algorithm takes to run is the time complexity.
As the definition implies, the time required is dictated by the number of iterations of one-line statements within the code. We can say that every piece of code we write takes time to execute—the lesser the time complexity, the faster the execution.
The time for a program to run does not depend entirely on the efficiency of code, and it’s also dependent on the processing power of a PC.
To compare the space and time complexity of the two algorithms, we will use Asymptotic Analysis. It figures out that how the performance changes as the input size increases.
Big-oh Notation(O) - Worst case
Big-oh is a formal method of expressing the upper bound of an algorithm’s running time.
It measures the longest time it could take for the algorithm to complete.
More formally, for non-negative functions, f (n) and g(n), if there exists an integer n0 and a constant c > 0 such that for all integers n > n0, f(n) < c * g(n).
Then, f (n) is the big-oh of g(n). This is denoted as f (n) O(g(n)), i.e., the set of functions which, as n gets large, grow faster than a constant time f (n).
Theta-Notation(Θ) - Average case
This notation bounds a function within a constant factor.
We say f(n) = g(n) if there exist positive constants n0, c1, and c2 in such a way that 0 ≤ c1g(n) ≤ f(n) ≤ c2g(n) for all n ≥ n0.
Pic from cs.fsu.edu.
Big Omega (Ω) - Best case
This notation gives a lower bound or the best case for a function within a constant factor.
We will write f(n) = g(n))when there are positive constants n0 and c such that 0 ≤ cg(n) ≤ f(n) for all n ≥ n0.
Pic from the medium.com
It will be more transparent when we see various examples of different time complexities.
Also see, kth largest element in an array
Must Read Lower Bound in C++
Example 1:
public static void main(String[] args) {
System.out.println("Coding Ninjas");
}
Output
Coding Ninjas
As you can see, the above example is not based on the input size n, which is why the time complexity taken by this code will be O(1).
O(1) means a constant amount of time is required to execute the code.