Algorithmscharacter sequence comparison
Character Sequence Comparison (Lexicographic vs Semantic)
TT
Testlaa Team
May 14, 2026•1 min read
Comparing sequences of characters is lexicographic order: first mismatch decides unless one string is a prefix. Distinct from semantic equality (for example the string '01' versus the integer 1).
Why this shows up in the real world
Version sorting in package managers uses structured comparison, not naive string compare. Dictionary ordering of words matches lexicographic rules for letters.
Core idea (explained for students)
Python: s < t, s == t, min(strings). For tuples of chars, same rules extend component-wise. When comparing numeric strings, convert with int if values fit memory.
Try this in Python
def cmp_version(a: str, b: str) -> int:
pa = [int(x) for x in a.split(".")]
pb = [int(x) for x in b.split(".")]
return (pa > pb) - (pa < pb)
print(cmp_version("1.10", "1.2"))
Common mistakes
- Leading zeros breaking numeric intent while string compare looks fine.
- Locale collation differs from ASCII—contests usually specify ASCII.
Key takeaways
- State whether you mean string order or numeric order in API docs.
- Use
tuple(map(int, parts))when comparing dotted versions numerically per segment.
Tags:
StringsPythonStudents
