617. Which Version Is Newer
Two version strings are given, each a sequence of one or more non-negative integers separated
by dots, such as 1.02.3.
Compare them part by part from the left. A part with leading zeros means the same number
without them, so 01 is 1. If one version has fewer parts than the other, the missing parts
count as 0, so 1.0 and 1.0.0 are equal.
Print -1 if the first is older, 1 if it is newer, and 0 if they are the same.
1.01 vs 1.001 -> 0 1 equals 1, and 01 equals 001
1.0 vs 1.0.0 -> 0 the missing part counts as 0
1.2 vs 1.10 -> -1 2 is less than 10
## Why string comparison fails
Comparing the two strings directly reports 1.2 as NEWER than 1.10, because 2 sorts after
1 as a character. Version parts are NUMBERS, and dictionary order is not numeric order once
they reach two digits.
Padding the strings to a common width does not rescue it either, because the parts have different widths in different positions.
## One cursor in each string
Walk both at once. At each step, read one whole part from each, as a number, and compare:
i = 0, j = 0
while i < len(x) or j < len(y):
v = 0; while i < len(x) and x[i] != '.': v = v*10 + digit(x[i]); i += 1
w = 0; while j < len(y) and y[j] != '.': w = w*10 + digit(y[j]); j += 1
if v != w: answer -1 or 1
i += 1; j += 1 step over the dot
answer 0
## The missing parts come free
The loop continues while EITHER cursor has work left, and a cursor already past the end
contributes a part of 0, because its inner loop runs zero times and v stays 0.
That is the whole reason no padding, no splitting and no length comparison is needed. Writing it as "split both, pad the shorter, then compare" also works and allocates two arrays; this allocates nothing.
## Leading zeros come free too
Accumulating with v = v * 10 + digit treats 007 and 7 identically, since the leading
zeros contribute nothing. No trimming step is required.
## Stepping over the dot
After each part, both cursors advance by one to pass the separator. When a cursor is at the end, that step just moves it further past the end, which the loop condition already tolerates.
## Boundaries
1 versus 1 is 0. 0 versus 0.0.0 is 0. 2 versus 1.9.9 is 1, decided on the first part
alone.
Parts fit in 32 bits, but accumulating into a 64 bit value costs nothing and removes the question.
## Cost
Time O(len(x) + len(y)). Space O(1).
Constraints - each version is 1 to 500 characters - each part is a non-negative integer below `10^9` - no version starts or ends with a dot
Input
The first line contains the first version string. The second line contains the second version string.
Output
Print one integer on a single line: -1 when the first version is older
than the second, 1 when it is newer, and 0 when the two are equal.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.