Drill

ProblemsPython › validation

Compare two version strings

hardvalidationPython

A deploy tool decides whether the version on the server is behind the one being released.

compare_versions(first: string, second: string) → int

Solve it in the editor →

Where you start

def compare_versions(first: str, second: str) -> int:
    

Worked examples

CallResult
compare_versions("1.2.10", "1.10.2")-1
compare_versions("1.2", "1.2.0")0
compare_versions("2.0", "1.9.9")1
compare_versions("1.0.0", "1.0.0")0

Hint

Walk both to the length of the longer one, reading a missing part as zero.

Reference solution in Python
def compare_versions(first: str, second: str) -> int:
    a = first.split('.')
    b = second.split('.')
    for i in range(max(len(a), len(b))):
        x = int(a[i]) if i < len(a) else 0
        y = int(b[i]) if i < len(b) else 0
        if x != y:
            return -1 if x < y else 1
    return 0

The same problem in another language

More validation problems in Python