Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

165. Compare Version Numbers

Two PointersString

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:

  1. Split the input strings version1 and version2 by the '.' delimiter.
  2. Iterate through the revisions of both versions simultaneously.
  3. Convert each revision to an integer and compare them.
  4. If one version has fewer revisions, treat the missing revisions as 0.
  5. If all revisions are equal up to that point, check if any remaining revisions in one version are greater than 0.
  6. Return -1 if version1 < version2, 1 if version1 > 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.

:

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.