LeetCode #165 Medium

Compare Version Numbers

Compare Version Numbers is LeetCode 165 (Medium). A version string is a list of revisions joined by dots. Compare version1 and version2 one revision at a time, from left to right:

  • Each revision is read as a whole number, so leading zeros are ignored.
  • A revision that one version does not have counts as 0.
  • Return −1 if version1 is smaller, 1 if it is larger, and 0 if they are equal.

Each string is at most 500 characters, and every revision fits in a 32-bit integer.

Constraints
  • 1 <= version1.length, version2.length <= 500
  • version1 and version2 only contain digits and '.'.
  • version1 and version2 are valid version numbers.
  • All the given revisions in version1 and version2 can be stored in a 32-bit integer.
stringtwo-pointers
Open on LeetCode ↗
02

Intuition

Compare versions the way you compare dates: the first revision matters most, and the first place where the two disagree decides the answer. Each revision is a whole number and a missing one is 0, so one pointer per string can read a revision from each side, compare the pair as numbers, and move on. Nothing needs to be split or stored.

How to spot this pattern

Comparing two strings field by field, where each field has to be parsed out first, is a two-pointer parse: each pointer reads up to the next separator, then the two fields are compared. Dotted IP addresses and dates sort with the same loop.

03

Approach

Try it first

Before reading on, compare "1.2" with "1.10", and "1.0" with "1", by hand, and write down the rule you used each time. Then plan how to read one revision at a time from each string without splitting either one into a list.

1

Keep one pointer per string

Start i at the front of version1 and j at the front of version2. Loop while either pointer still has characters left, so every revision of the longer version gets compared against something.

2

Read one revision from each side

From i, multiply a running number by 10 and add each digit, until a dot or the end of the string. Do the same from j. Building the number this way drops leading zeros on its own, and a pointer already past the end leaves its number at 0.

3

Stop at the first difference

If the two numbers differ, return −1 when the one from version1 is smaller and 1 when it is larger. Earlier revisions outrank later ones, so nothing further along can change the result.

4

Step over the dots and repeat

Move both pointers one place past the dot they stopped on, then read the next pair. If both strings run out with no difference found, every revision matched, so return 0.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def compareVersion(self, version1: str, version2: str) -> int:
▶3 n, m = len(version1), len(version2)
▶4 i = j = 0
▶5 while i < n or j < m:
▶6 a = 0
▶7 while i < n and version1[i] != ".":
▶8 a = a * 10 + int(version1[i])
▶9 i += 1
▶10 b = 0
▶11 while j < m and version2[j] != ".":
▶12 b = b * 10 + int(version2[j])
▶13 j += 1
▶14 if a != b:
▶15 return -1 if a < b else 1
▶16 i += 1
▶17 j += 1
▶18 return 0
version11.2iversion21.10jcomparefrom 1from 2both pointers at the start
i0
j0
One pointer per string. Each round reads one revision from each side, as a number, and compares the pair. The first pair that differs decides the answer.
version11.2iversion21.10jcomparefrom 1from 21version1's first revision is 1
a1
i1
Read digits from i until a dot or the end: "1" becomes the number 1.
version11.2iversion21.10jcomparefrom 1from 211version2's first revision is 1
b1
j1
Same from j: "1" becomes 1.
version11.2iversion21.10jcomparefrom 1from 211=both are 1 → step past the dots
i2
j2
The first revisions match, so they cannot decide the answer. Both pointers skip the dot they stopped on and the next round starts.
version11.2iendversion21.10jcomparefrom 1from 22version1's second revision is 2
a2
i3
Read digits from i until a dot or the end: "2" becomes the number 2.
version11.2iendversion21.10jendcomparefrom 1from 2210version2's second revision is 10
b10
j4
Same from j: "10" becomes 10.
version11.2iendversion21.10jendcomparefrom 1from 2210<result-12 < 10 → answer -1
return-1
2 is smaller than 10, so version1 is older. Every earlier revision was equal, and later revisions rank lower, so nothing left can change this. Return -1.
05

Split on the dots

Split each string on the dots and turn every piece into an integer, which removes leading zeros. Walk up to the length of the longer list, using 0 wherever a list has run out, and return at the first pair that differs.

▶1class Solution:
▶2 def compareVersion(self, version1: str, version2: str) -> int:
▶3 a = [int(x) for x in version1.split(".")]
▶4 b = [int(x) for x in version2.split(".")]
▶5 for k in range(max(len(a), len(b))):
▶6 x = a[k] if k < len(a) else 0
▶7 y = b[k] if k < len(b) else 0
▶8 if x != y:
▶9 return -1 if x < y else 1
▶10 return 0
06

Common pitfalls

Comparing revisions as text

✗ Wrong
if p1 != p2:
    return -1 if p1 < p2 else 1  # p1, p2 are strings
✓ Right
if int(p1) != int(p2):
    return -1 if int(p1) < int(p2) else 1

Text is compared one character at a time, and '1' comes before '9', so "10" counts as smaller than "9". On "1.10" against "1.9" the code returns −1, but revision 10 is the newer one, so the answer is 1. It also calls "1.01" and "1.1" different.

Reading the whole version as a decimal number

✗ Wrong
return (float(version1) > float(version2)) - (float(version1) < float(version2))
✓ Right
compare the revisions one by one as integers

The dot separates revisions; it is not a decimal point. float("1.10") is 1.1, which is below 1.9, so "1.10" against "1.9" gives −1 instead of 1. A version with two dots, such as "1.2.3", cannot be read as a number at all and crashes.

Splitting on "." in Java

✗ Wrong
String[] a = version1.split(".");
✓ Right
String[] a = version1.split("\\.");

Java's split takes a regular expression, and a bare . there means "any character". Every character becomes a separator, the array comes back empty, and the loop never runs, so "1.2" against "1.10" returns 0 instead of −1.

Stopping when the shorter version ends

✗ Wrong
while i < n and j < m:
✓ Right
while i < n or j < m:

The extra revisions of the longer version are never looked at. On "1.0.1" against "1" the loop compares only the first revision, finds 1 and 1, and returns 0. The third revision, 1, is above the missing one (0), so the answer is 1.

07

Complexity

Time
O(n + m)
Space
O(1)
Each pointer passes over its string once, reading each digit and each dot one time. Only two pointers and two running numbers are stored. The split version takes the same time but O(n + m) space for its two lists.
08

Compare Version Numbers FAQ

How do you sort version numbers?

Use this comparison as the sort order. In Python: sorted(versions, key=cmp_to_key(Solution().compareVersion)), with cmp_to_key from functools. Another way is to turn each version into a tuple of integers with its trailing zeros removed, and sort by those tuples.

Does this match how semantic versioning compares versions?

Only for the numeric part. Semantic versioning also allows labels such as 2.0.0-beta, where a pre-release ranks below 2.0.0. This problem has only digits and dots, so there are no labels to handle.