Compare Version Numbers
Compare Version Numbers is a medium arrays & hashing problem solved with the string basics pattern.
The best approach, optimal (two pointers, parse on the fly), runs in O(n + m) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from split and compare up.
Problem
A version string is a list of non-negative integer revisions separated by dots, such as "2.10.3". Compare version1 and version2 revision by revision from left to right, reading each revision as a number so that leading zeros do not matter. If one string has fewer revisions, its missing revisions count as 0. Return -1 if version1 is smaller, 1 if it is larger, and 0 if the two are equal.
Examples
Example 1
- Input
version1 = "3.4", version2 = "3.10"- Output
-1- Why
- The first revisions are equal (3 and 3). The second revisions are 4 and 10, and 4 < 10, so version1 is smaller.
Example 2
- Input
version1 = "1.02", version2 = "1.2.0.0"- Output
0- Why
- "02" is the number 2, and the missing third and fourth revisions of version1 count as 0, so every revision matches.
Example 3
- Input
version1 = "7.0.1", version2 = "7"- Output
1- Why
- version2 is treated as 7.0.0; the third revisions are 1 and 0, so version1 is larger.
Constraints
1 <= version1.length, version2.length <= 500- Both strings contain only digits and
'.'. - Every revision is a non-empty run of digits (no leading, trailing or doubled dots).
- Every revision's value fits in a 32-bit signed integer.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 52 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Split and compare | O(n + m) | O(n + m) |
| Optimal (two pointers, parse on the fly) | O(n + m) | O(1) |
1Split and compare
O(n + m)O(n + m)The split arrays hold copies of every revision.Split both strings on the dot, convert each piece to an integer, and compare position by position, using 0 for any position past the end of the shorter list.
- a = version1 split on '.', b = version2 split on '.'.
- For i from 0 to max(len(a), len(b)) - 1: x = a[i] as int or 0, y = b[i] as int or 0.
- If x < y return -1; if x > y return 1.
- Return 0.
class Solution {
public int compareVersion(String version1, String version2) {
String[] a = version1.split("\\.");
String[] b = version2.split("\\.");
int len = Math.max(a.length, b.length);
for (int i = 0; i < len; i++) {
int x = i < a.length ? Integer.parseInt(a[i]) : 0;
int y = i < b.length ? Integer.parseInt(b[i]) : 0;
if (x < y) return -1;
if (x > y) return 1;
}
return 0;
}
}class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
a = version1.split('.')
b = version2.split('.')
for i in range(max(len(a), len(b))):
x = int(a[i]) if i < len(a) else 0
y = int(b[i]) if i < len(b) else 0
if x < y:
return -1
if x > y:
return 1
return 0class Solution {
public:
int compareVersion(string version1, string version2) {
vector<long long> a = split(version1), b = split(version2);
size_t len = max(a.size(), b.size());
for (size_t i = 0; i < len; i++) {
long long x = i < a.size() ? a[i] : 0;
long long y = i < b.size() ? b[i] : 0;
if (x < y) return -1;
if (x > y) return 1;
}
return 0;
}
private:
vector<long long> split(const string& s) {
vector<long long> parts;
string piece;
stringstream ss(s);
while (getline(ss, piece, '.')) parts.push_back(stoll(piece));
return parts;
}
};function compareVersion(version1, version2) {
const a = version1.split('.').map(Number);
const b = version2.split('.').map(Number);
const len = Math.max(a.length, b.length);
for (let i = 0; i < len; i++) {
const x = i < a.length ? a[i] : 0;
const y = i < b.length ? b[i] : 0;
if (x < y) return -1;
if (x > y) return 1;
}
return 0;
}2Optimal (two pointers, parse on the fly)
O(n + m)Each character is read once.O(1)Only a few counters; no substrings or arrays are built.Walk both strings with one pointer each. At every step read the next revision from each string as a number (stopping at a dot or the end); a string that is already exhausted contributes 0. Compare the two numbers and move both pointers past their dots.
- i = 0, j = 0.
- While i < n or j < m: read x from version1 starting at i until '.' or end (x = 0 if i >= n); do the same for y from version2 at j.
- If x != y return x < y ? -1 : 1.
- Skip the dots: i++, j++.
- Return 0.
class Solution {
public int compareVersion(String version1, String version2) {
int n = version1.length(), m = version2.length();
int i = 0, j = 0;
while (i < n || j < m) {
long x = 0, y = 0;
while (i < n && version1.charAt(i) != '.') x = x * 10 + (version1.charAt(i++) - '0');
while (j < m && version2.charAt(j) != '.') y = y * 10 + (version2.charAt(j++) - '0');
if (x != y) return x < y ? -1 : 1;
i++;
j++;
}
return 0;
}
}class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
n, m = len(version1), len(version2)
i = j = 0
while i < n or j < m:
x = y = 0
while i < n and version1[i] != '.':
x = x * 10 + (ord(version1[i]) - 48)
i += 1
while j < m and version2[j] != '.':
y = y * 10 + (ord(version2[j]) - 48)
j += 1
if x != y:
return -1 if x < y else 1
i += 1
j += 1
return 0class Solution {
public:
int compareVersion(string version1, string version2) {
int n = (int)version1.size(), m = (int)version2.size();
int i = 0, j = 0;
while (i < n || j < m) {
long long x = 0, y = 0;
while (i < n && version1[i] != '.') x = x * 10 + (version1[i++] - '0');
while (j < m && version2[j] != '.') y = y * 10 + (version2[j++] - '0');
if (x != y) return x < y ? -1 : 1;
i++;
j++;
}
return 0;
}
};function compareVersion(version1, version2) {
const n = version1.length, m = version2.length;
let i = 0, j = 0;
while (i < n || j < m) {
let x = 0, y = 0;
while (i < n && version1[i] !== '.') x = x * 10 + (version1.charCodeAt(i++) - 48);
while (j < m && version2[j] !== '.') y = y * 10 + (version2.charCodeAt(j++) - 48);
if (x !== y) return x < y ? -1 : 1;
i++;
j++;
}
return 0;
}Edge cases to test
- Leading zeros like "001" versus "1"
- Different numbers of revisions with trailing zero revisions ("1.0.0" vs "1")
- Multi-digit revisions where string comparison would be wrong ("9" vs "10")
- Single-revision versions
Hints
Hint 1
Compare revision by revision as numbers, not as strings.
Hint 2
When one version runs out of revisions, treat its remaining revisions as 0.
Hint 3
You can parse each revision on the fly with two pointers instead of splitting the strings.
FAQ
What is the best time complexity for Compare Version Numbers?
Optimal (two pointers, parse on the fly) runs in O(n + m) time and O(1) extra space. Each character is read once.
Which pattern does Compare Version Numbers use?
It is a arrays & hashing problem that uses the string basics pattern. Other problems with the same pattern: Longest Common Prefix, Minimum Changes To Make Alternating Binary String, Rotate String.
Is there a brute force solution for Compare Version Numbers?
Yes. Split and compare takes O(n + m) time and O(n + m) space. Split both strings on the dot, convert each piece to an integer, and compare position by position, using 0 for any position past the end of the shorter list.
Which edge cases should I test for Compare Version Numbers?
Leading zeros like "001" versus "1"; Different numbers of revisions with trailing zero revisions ("1.0.0" vs "1"); Multi-digit revisions where string comparison would be wrong ("9" vs "10"); Single-revision versions.