You are given two version numbers, version1
and version2
, represented as strings. A version number consists of one or more revisions joined by a dot '.'
. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being the highest significance. For example, 2.5.33
and 0.1
are valid version numbers.
To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that 1.0
is considered the same as 1
, and 1.0.0
is considered the same as 1
.
Return the following:
version1
< version2
, return -1
.version1
> version2
, return 1
.0
.version1
and version2
by the '.'
delimiter to extract individual revisions as strings.0
.-1
, 1
, or 0
based on the comparison results.def compareVersion(version1: str, version2: str) -> int:
# Split the version strings into lists of integers
v1 = list(map(int, version1.split('.')))
v2 = list(map(int, version2.split('.')))
# Determine the maximum length of the version lists
max_length = max(len(v1), len(v2))
# Compare corresponding revisions
for i in range(max_length):
revision1 = v1[i] if i < len(v1) else 0
revision2 = v2[i] if i < len(v2) else 0
if revision1 < revision2:
return -1
elif revision1 > revision2:
return 1
# If all corresponding revisions are equal
return 0
n
is the number of revisions in version1
and m
is the number of revisions in version2
. We split both version strings and then iterate through the maximum length of the two lists of revisions.This implementation efficiently compares version numbers by parsing and comparing each revision numerically.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?