LeetCode 165: Compare Version Numbers Solution
Master LeetCode problem 165 (Compare Version Numbers), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
165. Compare Version Numbers
Problem Explanation
Explanation:
To solve this problem, we can split the input strings version1 and version2 by the '.' delimiter and compare each revision value one by one. We iterate through both versions simultaneously, converting each revision to an integer and comparing them. If one version has fewer revisions, we consider the missing revisions as 0. After comparing all revisions, if the versions are equal up to that point, we also need to consider the case where one version has additional revisions that are greater than 0.
Algorithm:
- Split the input strings
version1andversion2by the '.' delimiter. - Iterate through the revisions of both versions simultaneously.
- Convert each revision to an integer and compare them.
- If one version has fewer revisions, treat the missing revisions as 0.
- If all revisions are equal up to that point, check if any remaining revisions in one version are greater than 0.
- Return -1 if
version1 < version2, 1 ifversion1 > version2, and 0 if they are equal.
Time Complexity: O(max(N, M)), where N and M are the lengths of the input strings version1 and version2 respectively.
Space Complexity: O(N+M), where N and M are the lengths of the input strings version1 and version2 respectively.
:
Solution Code
class Solution {
public int compareVersion(String version1, String version2) {
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
int n = Math.max(v1.length, v2.length);
for (int i = 0; i < n; i++) {
int r1 = i < v1.length ? Integer.parseInt(v1[i]) : 0;
int r2 = i < v2.length ? Integer.parseInt(v2[i]) : 0;
if (r1 < r2) {
return -1;
} else if (r1 > r2) {
return 1;
}
}
return 0;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 165 (Compare Version Numbers)?
This page provides optimized solutions for LeetCode problem 165 (Compare Version Numbers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 165 (Compare Version Numbers)?
The time complexity for LeetCode 165 (Compare Version Numbers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 165 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 165 in Java, C++, or Python.