Programming in a Better Way: Do You Really Need an Array?

While solving Codeforces Problem 71A – Way Too Long Words, I initially wrote this solution:

n = int(input())
words = []

for i in range(n):
    words.append(input())

for word in words:
    if len(word) > 10:
        print(word[0] + str(len(word) - 2) + word[-1])
    else:
        print(word)

At first, I thought this was the natural approach:

  1. Read all the inputs.
  2. Store them in a list.
  3. Process them later.

The solution is 100% correct, and it passes all the test cases.

Then I Found a Better Approach

Later, I came across this solution:

n = int(input())

for _ in range(n):
    word = input()
    if len(word) > 10:
        print(word[0] + str(len(word) - 2) + word[-1])
    else:
        print(word)

This version does exactly the same thing, but it is cleaner.

Why Is It Better?

Notice that each word is processed immediately after it is read.

The program doesn't need the previous words anymore, so storing them in a list is unnecessary.

This has a few advantages:

  • Uses less memory.
  • Simpler code.
  • Easier to read.
  • Follows the idea of Read → Process → Output.

The Lesson I Learned

One of the biggest lessons I learned from competitive programming is:

Don't store data unless you actually need it later.

If the problem allows you to process each input independently, there's no reason to keep everything in memory.

When Should You Use a List?

A list is useful when you need to:

  • Sort the data.
  • Traverse it multiple times.
  • Compare elements.
  • Access previous inputs later.

If none of these are required, processing the input immediately is often the better choice.

Final Thought

My first solution wasn't wrong—it solved the problem correctly.

The second solution taught me something more important than just passing the problem:

Good programming isn't only about getting the correct answer. It's also about writing code that's simple, efficient, and uses only what is necessary.

That's a small improvement, but making these small improvements consistently is what helps us become better programmers.