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
version1is 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.
- 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.
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.
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.
Approach
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.
Two ways to solve it
Each pointer builds the next revision digit by digit, then the pair is compared.
- Memory: two pointers and two numbers.
- Stops early: nothing after the first difference is read.
The answer interviewers expect when they ask for constant space.
Split both strings into lists of integers, then compare position by position.
- Memory: two lists, one entry per revision.
- Code: short, with the parsing done by the library.
The obvious first idea, and fine at 500 characters.
Both compare the versions revision by revision in O(n + m) time. Two pointers need no extra memory, so the steps, code and live demo below use them; the split version comes after the demo.
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.
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.
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.
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.
Code in Python, C++ and Java
i until a dot or the end: "1" becomes the number 1.j: "1" becomes 1.i until a dot or the end: "2" becomes the number 2.j: "10" becomes 10.i until a dot or the end: "1" becomes the number 1.j: "1" becomes 1.i until a dot or the end: "01" becomes the number 1. The leading zeros add nothing, so they vanish.j: "001" becomes 1. Its leading zeros vanish too.i until a dot or the end: "1" becomes the number 1.j: "1" becomes 1.i until a dot or the end: "0" becomes the number 0.j: "0" becomes 0.a stays 0 and the comparison goes on.j: "5" becomes 5.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.
Common pitfalls
Comparing revisions as text
if p1 != p2:
return -1 if p1 < p2 else 1 # p1, p2 are stringsif int(p1) != int(p2):
return -1 if int(p1) < int(p2) else 1Text 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
return (float(version1) > float(version2)) - (float(version1) < float(version2))
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
String[] a = version1.split(".");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
while i < n and j < m:
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.
Complexity
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.