How more lines of code is better than less lines of code?


Hi everyone. Welcome to a new blog post! Today, I’m excited to share what I have learned on Day 1 of Data Structure and Algorithms.
What is Time complexity?
Time complexity is a way to describe how the number of operations in an algorithm grows relative to the size of the input. It doesn't measure actual "clock time" but rather how many steps, iterations, or comparisons an algorithm performs as the input increases.
Example
Let’s suppose I have 8 water bottles(1000 ml each) filled completely with water and I have 1 more water bottle which is half filled. Now can you tell me how to find the half filled bottle in this group of 9?
Method #1 :
I will go with the common man approach which is basically using the loops and check one by one ! and I think you are thinking this same….. okay lets see the code for it !!.
for (int = 1 ; int <= 9 ; i++){
if (bottle_weight[i]<1000){
// cout ==> bottle_weight[i]
}
}
// just a logic not the exact code.
Here you can see the loop will iterate one by one and maximum 9 iteration can be possible.
Method #2 :
Why don’t reduce the iteration number. So here’s the idea of doing that make a group of 3 water bottles and compare the weight , in this case we will directly reject the 6 iterations and we finally got 3 iteration to do so by this we can make more better codes. Lets see this…..
// This is not the exact code, its just the logic of thinking. You can write it by
// your own.
int WaterBottles[9] = {1000,1000,1000,1000,1000,1000,1000,500,1000};
int Bottle_Group_A = WaterBottles[0]+WaterBottles[1]+WaterBottles[2];
int Bottle_Group_B = WaterBottles[3]+WaterBottles[4]+WaterBottles[5];
int Bottle_Group_C = WaterBottles[6]+WaterBottles[7]+WaterBottles[8];
// when weight of both group is equall.
if (Bottle_Group_A == Water_Group_B){
if(WaterBottles[6] < WaterBottles[7]){
//return WaterBottles[6];
}
else if (WaterBottles[7] < WaterBottles[8]){
//return WaterBottles[7];
}
}
// when weight of both group is not equall.
if (Bottle_Group_A > Water_Group_B){
if(WaterBottles[0] < WaterBottles[1]){
//return WaterBottles[0];
}
else if (WaterBottles[1] < WaterBottles[2]){
//return WaterBottles[1];
}
}
// and again a case when both are not equall and the code logic will remain same.
By looking to this we can say we just reject the two groups just by comparing one time and you are seeing the 3 loops here, but for your insight I can tell that when you compare, than only one loop will be in the running position and rest of them are of no use. And now we can easily perform the iteration on the left group. This is what we should do while learning the time complexity.
Conclusion
Time complexity is nothing related with time but with the iteration and inputs.
Subscribe to my newsletter
Read articles from Abhinav directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Abhinav
Abhinav
I am B-Tech 2nd year Student (Electrical Engineering)