Algorithmsstring length comparison

String Length Comparison (sort by len, quick rejects)

TT
Testlaa Team
May 14, 20261 min read

Comparing lengths picks shorter/longer strings, sorts by size first, or proves impossibility (cannot fit pattern if len(text) < len(pat)). Lexicographic order is separate from length order.

Why this shows up in the real world

Password managers reject passwords shorter than policy. Greedy packing compares remaining capacity to next item length.

Core idea (explained for students)

Use tuples in sort keys: sorted(words, key=len) for shortest-first. For custom tie-breaking, sorted(words, key=lambda w: (len(w), w)).

Try this in Python

def longest_first(words: list[str]) -> list[str]:
    return sorted(words, key=len, reverse=True)


print(longest_first(["a", "abc", "ab"]))

Common mistakes

  • Sorting by length then forgetting stable tie-break for determinism.
  • Using < on strings when you meant < on lengths.

Key takeaways

  • Cheap rejection: if len(pat) > len(text), skip heavy search.
  • Document whether equal lengths sort alphabetically or arbitrarily.

Tags:

StringsPythonStudents