The Secret Efficiency Of -- "100 Lines Of Code"

Mahesh KumarMahesh Kumar
2 min read

We often believe that less number of lines = more efficiency, but is this true?
Let us discuss about this misconception in this blog.

Consider there are 9 balls, out of 9 balls 8 have are having same weight, and 1 ball have more weight.
The task is to find the heavy ball.

#include<bits/stdc++.h>
int main()
{
    // find the heaviest ball
    int balls [9] = {0,0,0,1,0,0,0,0,0};
}

You can apply brute force method, by visiting all the indexes and comparing each of them, and return the answer.

#include<bits/stdc++.h>
int main()
{
    // find the heaviest ball
    int balls [9] = {0,0,0,1,0,0,0,0,0};
    int heaviest = balls[0];
    for(int i =0; i < balls.length(); i++){
        // visiting all the elements 
        if (balls[i] > heaviest) heaviest = balls[i];
    }
    cout<<"Heaviest ball: "<<heaviest;
}

But you have missed the concept of Time Complexity. The algorithm should be time efficient to be the optimal solution.
In Brute Force approach, although the number of lines are under 10, but the time complexity is very high (as you are visiting all the elements in an array).

So what do we do??

We divide the array into equal sub parts, then compare those two parts. In our case, we divide 9 balls into 3 sub groups, say A, B, C. Then we compare each sub group’s total weight, if any one of the sub group’s total weight is greater, then the heaviest ball is present in that sub group.

#include<bits/stdc++.h>
int main()
{
    // find the heaviest ball
    int balls [9] = {0,0,0,1,0,0,0,0,0};
    int A = balls[0] + balls[1] + balls[2];
    int B = balls[3] + balls[4] + balls[5];
    int C = balls[6] + balls[7] + balls[8];
    if(A == B){
        // heavy ball is in C
        // further break down C into equal parts and compare
    }
    if(A > B){
        // heavy ball is in A
        // further break down A into equal parts and compare
    }
    if(A < B){
        // heavy ball is in B
        // further break down B into equal parts and compare
    }
}

Here the program’s Time Complexity is less, but the number of lines used is more. But how?
We are skipping most of the code by adding conditional statements, the program runs half of the time compared to the Brute Force Method.

Conclusion

  • Sometimes efficiency of the program lies on the time complexity not number of lines used.

  • You can approach to the solution through many ways, just find the most suited way by keeping the Time Complexity at minimum.

0
Subscribe to my newsletter

Read articles from Mahesh Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mahesh Kumar
Mahesh Kumar