Compare Version Numbers (LeetCode 165): Solution and Explanation
You get two version strings such as "1.2" and "1.10". Compare them revision by revision as integers, treating missing revisions as 0, and return -1, 0 or 1.
Intuition
A version is a list of numbers written with dots between them. Comparing two versions is like comparing two words letter by letter, except each letter is a whole number: the first position where they differ decides the answer.
The numbers have to be compared by value, not as text. As text, "10" sorts before "2" and "01" differs from "1". Building each revision as value * 10 + digit gives the integer directly, and leading zeros contribute nothing because 0 * 10 + 0 is still 0.
When one version is shorter, its missing revisions behave like 0. So "1.0" equals "1.0.0.0", but "1.0.1" is larger than "1". Keep reading until both strings are used up, letting the finished side produce 0.
Approach: Two pointers, one revision at a time
- Put
iat the start ofversion1andjat the start ofversion2. - While
i < norj < m, read digits fromversion1until a dot or the end, buildinga. Ifiis already past the end,astays 0. - Do the same on
version2to buildb. - If
a != b, return -1 whena < band 1 otherwise. - Step both pointers over the dot and repeat. If the loop finishes, every revision matched, so return 0.
Step-by-step example
version1 = "1.2", version2 = "1.10"
- Revision 1: read '1' from version1, so a = 1. Read '1' from version2, so b = 1. They are equal.
- Step i and j past the dots.
- Revision 2: read '2', so a = 2. Read '1' then '0' from version2, so b = 1 and then b = 10.
- 2 < 10, so return -1 without looking any further.
Code: Python, Java, C++
1class Solution:
2 def compareVersion(self, version1: str, version2: str) -> int:
3 i, j = 0, 0
4 n, m = len(version1), len(version2)
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 01class Solution {
2 public int compareVersion(String version1, String version2) {
3 int i = 0, j = 0;
4 int n = version1.length(), m = version2.length();
5 while (i < n || j < m) {
6 int a = 0;
7 while (i < n && version1.charAt(i) != '.') {
8 a = a * 10 + (version1.charAt(i) - '0');
9 i++;
10 }
11 int b = 0;
12 while (j < m && version2.charAt(j) != '.') {
13 b = b * 10 + (version2.charAt(j) - '0');
14 j++;
15 }
16 if (a != b) {
17 return a < b ? -1 : 1;
18 }
19 i++;
20 j++;
21 }
22 return 0;
23 }
24}1class Solution {
2public:
3 int compareVersion(string version1, string version2) {
4 int i = 0, j = 0;
5 int n = version1.size(), m = version2.size();
6 while (i < n || j < m) {
7 int a = 0;
8 while (i < n && version1[i] != '.') {
9 a = a * 10 + (version1[i] - '0');
10 i++;
11 }
12 int b = 0;
13 while (j < m && version2[j] != '.') {
14 b = b * 10 + (version2[j] - '0');
15 j++;
16 }
17 if (a != b) {
18 return a < b ? -1 : 1;
19 }
20 i++;
21 j++;
22 }
23 return 0;
24 }
25};Time and space complexity
O(n + m)
Each pointer only moves forward, so every character of both strings is read at most once.
O(1)
Only the two pointers and the two revision values are stored. No lists of revisions are built.
Other approaches
Split on dots and compare integers (time O(n + m), space O(n + m))
Split both strings on '.', convert each piece to an integer and compare index by index, using 0 when a list is shorter. It is the shortest code, but it allocates both lists of pieces.
Strip leading zeros and compare strings (time O(n + m), space O(n + m))
Remove leading zeros from each revision, then compare by length first and lexicographically second. This avoids integer conversion entirely and works even if revisions were too large for an integer type.
Common mistakes
- Comparing revisions as strings. "10" is smaller than "2" as text but larger as a number.
- Stopping when the shorter version runs out. "1.0.1" is larger than "1", so the trailing revisions must still be compared against 0.
- Returning as soon as two revisions are equal. Only a difference ends the scan early; equal revisions mean keep going.
- Forgetting to move both pointers over the dot, which makes the next revision read as empty.
Frequently asked questions
Why does "1.01" equal "1.001"?
Revisions are compared as integers. Both "01" and "001" have the value 1, so the second revisions match and the versions are equal.
How are versions with different numbers of revisions compared?
The shorter one is padded with zeros. "1.0" and "1.0.0.0" are equal because the missing revisions are 0, while "1.0.1" beats "1" because 1 > 0 in the third revision.
Can a revision overflow a 32-bit integer?
Not under the given constraints, which guarantee every revision fits in a 32-bit integer. If that were not guaranteed, strip leading zeros and compare the digit strings by length and then lexicographically.
Is the two-pointer version faster than splitting?
Both are linear. The two-pointer version avoids allocating lists of substrings, so it uses constant extra space.