Time complexity is one of the most important concepts in DSA.
It tells us how the running time of an algorithm changes when the input size gets bigger (from 10 items β 100 β 10,000 β 1 million).
Real-Life Examples to Understand Time Complexity
1. Taking One Book From a Shelf ποΈ
You go to a library and always take the first book from the shelf.
It does not matter if the shelf has:
- 10 books
- 100 books
- 10,000 books
π Time taken is almost the same β you just pick the first one.
2. Searching a Name in an Unsorted List π
You are searching for βRahulβ in a list of names. You check one by one:
- Rahul is first β very fast
- Rahul is in the middle β takes moderate time
- Rahul is last (or not present) β you check every name
π Worst case: You may need to look at the entire list.
3. Sorting Exam Papers π
A teacher wants to arrange exam papers from lowest to highest marks.
They compare many papers with each other.
If number of papers increases:
- 10 papers β manageable
- 100 papers β many comparisons
- 1000 papers β huge number of comparisons
π More papers β much more work to sort them.
Simple Code Examples
Example 1: Single Loop (Grows linearly with n)
for(int i = 0; i < n; i++) {
cout << i << endl;
}
If n = 5 β loop runs 5 times β 5 print operations
If n = 100 β loop runs 100 times
π More input size β more repetitions
Example 2: Two Separate Loops
for(int i = 0; i < n; i++) {
cout << i << endl;
}
for(int j = 0; j < n; j++) {
cout << j << endl;
}
If n = 5 β first loop 5 times + second loop 5 times = 10 operations
If n = 100 β 100 + 100 = 200 operations
π Total work doubles when n doubles (still reasonable)
Quick Summary β Rough Ideas Only
- Some algorithms take almost same time no matter how big input is (very fast)
- Some algorithms become slow gradually (like single loop β acceptable for most cases)
- Some algorithms become extremely slow very quickly when input grows (like bad sorting methods)
O( ), Ξ©( ), Ξ( ) and how to calculate them properly.