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

Parsed numeric tuple sort key
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 result

Common follow-up questions