Leetcode 165. Compare Version Numbers
The task is to compare two version numbers, version1
and version2
.
Each version number is composed of one or more revisions joined by a dot (.
). Each revision consists of digits and may contain leading zeros. Each version can have multiple revisions.
Compare the versions and return:
1
if version1
is greater than version2
-1
if version1
is less than version2
0
if they are equalFor example:
Input: version1 = "1.01", version2 = "1.001" Output: 0
Input: version1 = "1.0", version2 = "1.0.0" Output: 0
Input: version1 = "0.1", version2 = "1.1" Output: -1
1.0
and 1.0.0
)?
split("\\.")
method in Java to break the version strings into their individual numeric components.public class CompareVersionNumbers {
public int compareVersion(String version1, String version2) {
String[] v1Parts = version1.split("\\.");
String[] v2Parts = version2.split("\\.");
int length = Math.max(v1Parts.length, v2Parts.length);
for (int i = 0; i < length; i++) {
int v1Component = i < v1Parts.length ? Integer.parseInt(v1Parts[i]) : 0;
int v2Component = i < v2Parts.length ? Integer.parseInt(v2Parts[i]) : 0;
if (v1Component > v2Component) {
return 1;
} else if (v1Component < v2Component) {
return -1;
}
}
return 0;
}
public static void main(String[] args) {
CompareVersionNumbers comparator = new CompareVersionNumbers();
System.out.println(comparator.compareVersion("1.01", "1.001")); // Output: 0
System.out.println(comparator.compareVersion("1.0", "1.0.0")); // Output: 0
System.out.println(comparator.compareVersion("0.1", "1.1")); // Output: -1
}
}
The time complexity of this solution is O(max(N, M)), where N
and M
are the lengths of the version strings when split by .
. This ensures that we linearly compare each component pair and, therefore, achieve efficient comparison.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?