163/670

163. Compare Version Numbers

Medium

You are given two version strings, version1 and version2. Each is a sequence of one or more revisions joined by dots, and each revision is a run of digits that may carry leading zeros — "1.02.4" has revisions 1, 2, and 4.

Compare the versions revision by revision, left to right, treating every revision as its integer value (so "02" equals "2"). When one version runs out of revisions first, its missing revisions count as 0 — which makes "1.0.0" equal to "1".

Return -1 if version1 is the smaller version, 1 if it is the larger, and 0 if they are equal.

Example 1:

Input: version1 = "1.2", version2 = "1.10"

Output: -1

Explanation: The first revisions tie at 1. The second revisions compare as integers: 2 < 10 — not as text, where "2" would sort after "10".

Example 2:

Input: version1 = "1.0.0", version2 = "1"

Output: 0

Explanation: version2 has no second or third revision, so both default to 0 and match version1's trailing zeros exactly.

Example 3:

Input: version1 = "3.1", version2 = "3.0.5"

Output: 1

Explanation: The second revisions decide it: 1 > 0, so nothing after that matters.

Constraints:

  • 1 ≤ version1.length, version2.length ≤ 500
  • Both strings contain only digits and dots, start and end with a digit, and never have two dots in a row.
  • Every revision's integer value fits in a 32-bit signed integer.

Hints:

Comparing revision strings as text breaks on "2" vs "10" and on leading zeros — convert each revision to a number before comparing.

Splitting both strings on dots and padding the shorter list with zeros gives a clean chunk-by-chunk comparison; the first unequal pair decides the answer.

To do it without allocating the split lists, run one pointer per string: accumulate digits into a number until you hit a dot or the end, compare the two accumulated values, then step both pointers past their dots. A pointer past the end simply contributes 0.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: version1 = "1.2", version2 = "1.10"

Expected output: -1