Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Version strings are sequences of integer revisions, not decimal numbers or ordinary text. The first unequal revision determines the ordering; leading zeros do not matter, and omitted trailing revisions behave like zeros. Thus 1.01 equals 1.1.0.
Approach
- Split both strings at their dots.
- Visit component positions up to the longer list's length. Convert an existing component to an integer, or use zero if that list has ended.
- Return
1or-1immediately when the first differing pair establishes the ordering. Later components cannot override it. - Return zero if every compared pair is equal, including any missing trailing components.
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
ver1 = version1.split('.')
ver2 = version2.split('.')
for i in range(max(len(ver1), len(ver2))):
v1 = int(ver1[i]) if i < len(ver1) else 0
v2 = int(ver2[i]) if i < len(ver2) else 0
if v1 > v2:
return 1
elif v1 < v2:
return -1
return 0Complexity analysis
For n and m input characters, splitting and comparing all revision components takes O(n + m) time and O(n + m) auxiliary space for the split component arrays.
