The Version Parade
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L5
- Asked in
- TetraScience
Problem
Given semantic version strings in 'major.minor.patch' format, return them sorted from oldest to newest. Compare each component as an integer, not lexicographically.
1.0 before 2.0. Don't let the dots confuse you.
Example 1
Input:
versions = ["1.2.3","1.0.0","2.0.0","1.2.1"]
Output:
["1.0.0","1.2.1","1.2.3","2.0.0"]
Example 2
Input:
versions = ["10.0.0","9.0.0","9.9.9"]
Output:
["9.0.0","9.9.9","10.0.0"]
Worked solution and explanation
Why this problem exists in real interviews
This tests custom sorting with parsed keys. Semantic version strings must be compared numerically, not lexicographically. It probes whether a candidate can parse structured strings into comparable tuples.
Break down the requirements
Step 1: Parse each version string into numeric components
Split on . and convert each part to an integer. '1.10.0' becomes (1, 10, 0).
Step 2: Sort using the numeric tuples as keys
Python's tuple comparison is lexicographic on elements, which gives correct version ordering.
The solution
def sort_versions(versions: list) -> list:
def version_key(v):
parts = v.split(".")
nums = []
for p in parts:
nums.append(int(p))
return tuple(nums)
result = sorted(versions, key=version_key)
return resultCommon follow-up questions
- What if versions had optional pre-release tags like '1.0.0-beta'? (Tests parsing and comparing pre-release suffixes with specific precedence rules.)
- What if some versions had fewer components (e.g., '1.0' vs '1.0.0')? (Tests padding missing components with zeros before comparison.)
- How does semver define precedence for build metadata? (Tests knowledge that build metadata (after +) is ignored for precedence.)