“100 Lines vs. 2 Lines of Code: Why More Can Mean Faster”

Harsh JosolkarHarsh Josolkar
2 min read

The Hidden Cost of Short Code and the Power of Explicit Logic.

In software development, there a usual term that “Shorter Code is better code“, but every time its not like that. It is assumed that less lines of code equals less time complexity but there are some cases where writing more lines can give less complexity then writing same code in shorter format.

Let’s explore the idea with a classic example:

You have given 9 balls are given, where 8 balls have same weights and one of the 9 balls is heavier. You have to find heavy ball using a balance scale with the minimum number of weighing.

Shorter and Simpler approach

Here’s the straightforward approach, with simple for loop

balls = [1, 1, 1, 1, 1, 2, 1, 1, 1]

def find_heavy_ball(balls):
    for i in range(len(balls)):
        if balls[i] > 1:
            return i  # return the index of the heavy ball

index = find_heavy_ball(balls)
print(f"The heavy ball is at index: {index}")

Here the code goes through each and every balls and compare weights of every ball and tell which ball is heavier.

Here the code is Shorter but the Time Complexity is

O(n)

Smarter Approach (More Code but Better Complexity)

Now, let’s apply some logic — and more lines — to improve efficiency. If we split the balls into three groups of three and compare them using a balance scale, we can find the heavy ball in just two weighing.

Here’s the implementation:

def find_heavy_ball(balls):
    group1 = balls[0:3]
    group2 = balls[3:6]
    group3 = balls[6:9]

    def weight(group):
        return sum(group)

    # Determine which group contains the heavy ball
    if weight(group1) > weight(group2):
        heavy_group = group1
        offset = 0  # group1 starts at index 0
    elif weight(group1) < weight(group2):
        heavy_group = group2
        offset = 3  # group2 starts at index 3
    else:
        heavy_group = group3
        offset = 6  # group3 starts at index 6

    # Find the heavy ball within the selected group
    if heavy_group[0] > heavy_group[1]:
        return offset + 0
    elif heavy_group[0] < heavy_group[1]:
        return offset + 1
    else:
        return offset + 2

Example Test:

balls = [1, 1, 1, 1, 1, 2, 1, 1, 1]
print("Heavy ball is at index:", find_heavy_ball(balls))

Output:

Heavy ball is at index: 5

Now here the complexity is
O(1) Constant time

It is easy to debug and understand.

Yes, it takes ~20 lines instead of 2. But you’ve gained massive performance improvement.

Conclusion:

Writing more code isn’t always a bad thing. In fact, more lines can bring more clarity, better performance, and smarter logic.

0
Subscribe to my newsletter

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

Written by

Harsh Josolkar
Harsh Josolkar