Compare Version Numbers
Given two version strings v1 and v2, compare them. If v1 > v2 return 1; if v1 < v2 return -1; otherwise return 0. Treat missing segments as 0.
- 1 <= v1.length, v2.length <= 500
- v1/v2 consist of digits and '.'
v1 = "1.01", v2 = "1.001"0v1 = "1.0", v2 = "1.0.0"0v1 = "1.10", v2 = "1.2"1Comparing versions is like navigating a legal document (Section 1.2 vs Section 1.10). Each number between dots is a Revision Level. We compare these levels from left to right, but we cannot use standard string comparison because "1.10" must be considered greater than "1.2".
The "dot-separated" format introduces three tricky scenarios:
1. Leading Zeros: "001" and "1" represent the same revision level (1).
2. Numerical Value: "10" is larger than "2", even though "2" comes after "1" alphabetically.
3. Missing Segments: "1.1" and "1.1.0" represent the same spiritual version. If one version runs out of segments, we treat the missing levels as 0.
The most robust approach is to iterate through both strings simultaneously and convert each segment into an integer. This automatically handles leading zeros and allows for direct numerical comparisons.
Instead of splitting the strings (which uses extra memory), we use two pointers to scan and build integers on the fly. We stop at every dot, compare the values, and continue.
i, j = 0, 0
while i < len(version1) or j < len(version2):
val1, val2 = 0, 0
# Extract numerical value for version1's current segment
while i < len(version1) and version1[i] != '.':
val1 = val1 * 10 + int(version1[i])
i += 1
# Extract numerical value for version2's current segment
while j < len(version2) and version2[j] != '.':
val2 = val2 * 10 + int(version2[j])
j += 1
# Hierarchical check: if levels differ, we found the winner
if val1 != val2:
return 1 if val1 > val2 else -1
i += 1; j += 1 # Skip current dots
return 0version delta analyzer
Comparing Version 1 ("1.0.1") and Version 2 ("1").