Open In App

Compare two Version numbers

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A version number is a string that is used to identify the unique state of a software product. A version number looks like a.b.c.d, where a, b, etc are numbers, so the version number is a string in which numbers are separated by dots. These numbers generally represent the hierarchy from major to minor (a is major and d is minor). 

In this problem, we are given two version numbers. We need to compare them and conclude which one is the latest version number (that is, which version number is greater). 

Example: 

Input: 
V1 = “1.0.31”
V2 = “1.0.27”
Output: v1 is latest
Because V2 < V1
Input:
V1 = “1.0.10”
V2 = “1.0.27”
Output: v2 is latest
Because V1 < V2

Approach: It is not possible to compare them directly because of the dot, but the versions can compare numeric part wise and then the latest version can be found. Traverse through strings and separate numeric parts and compare them. If equal, then the next numeric part is compared and so on until they differ, otherwise flag them as equal. 

Implement a method to compare the two versions. If there are more than two versions, then the below versionCompare method can be used as a compare method of sort method, which will sort all versions according to the specified comparison.

Implementation:

C++




// C/C++ program to compare
// two version number
#include <bits/stdc++.h>
using namespace std;
 
// Method to compare two versions.
// Returns 1 if v2 is smaller, -1
// if v1 is smaller, 0 if equal
int versionCompare(string v1, string v2)
{
    // vnum stores each numeric
    // part of version
    int vnum1 = 0, vnum2 = 0;
 
    // loop until both string are
    // processed
    for (int i = 0, j = 0; (i < v1.length()
                            || j < v2.length());) {
        // storing numeric part of
        // version 1 in vnum1
        while (i < v1.length() && v1[i] != '.') {
            vnum1 = vnum1 * 10 + (v1[i] - '0');
            i++;
        }
 
        // storing numeric part of
        // version 2 in vnum2
        while (j < v2.length() && v2[j] != '.') {
            vnum2 = vnum2 * 10 + (v2[j] - '0');
            j++;
        }
 
        if (vnum1 > vnum2)
            return 1;
        if (vnum2 > vnum1)
            return -1;
 
        // if equal, reset variables and
        // go for next numeric part
        vnum1 = vnum2 = 0;
        i++;
        j++;
    }
    return 0;
}
 
// Driver method to check above
// comparison function
int main()
{
    string version1 = "1.0.3";
    string version2 = "1.0.7";
 
    if (versionCompare(version1, version2) < 0)
        cout << version1 << " is smaller\n";
    else if (versionCompare(version1, version2) > 0)
        cout << version2 << " is smaller\n";
    else
        cout << "Both version are equal\n";
    return 0;
}


Java




// Java program to compare two version number
import java.util.*;
 
class GFG {
 
    // Method to compare two versions.
    // Returns 1 if v2 is
    // smaller, -1 if v1 is smaller, 0 if equal
    static int versionCompare(String v1, String v2)
    {
        // vnum stores each numeric part of version
        int vnum1 = 0, vnum2 = 0;
 
        // loop until both String are processed
        for (int i = 0, j = 0; (i < v1.length()
                                || j < v2.length());) {
            // Storing numeric part of
            // version 1 in vnum1
            while (i < v1.length()
                   && v1.charAt(i) != '.') {
                vnum1 = vnum1 * 10
                        + (v1.charAt(i) - '0');
                i++;
            }
 
            // storing numeric part
            // of version 2 in vnum2
            while (j < v2.length()
                   && v2.charAt(j) != '.') {
                vnum2 = vnum2 * 10
                        + (v2.charAt(j) - '0');
                j++;
            }
 
            if (vnum1 > vnum2)
                return 1;
            if (vnum2 > vnum1)
                return -1;
 
            // if equal, reset variables and
            // go for next numeric part
            vnum1 = vnum2 = 0;
            i++;
            j++;
        }
        return 0;
    }
 
    // Driver method to check above
    // comparison function
    public static void main(String[] args)
    {
        String version1 = "1.0.3";
        String version2 = "1.0.7";
 
        if (versionCompare(version1, version2) < 0)
            System.out.println(version1 + " is smaller");
        else if (versionCompare(version1, version2) > 0)
            System.out.println(version2 + " is smaller");
        else
            System.out.println("Both version are equal");
    }
}
 
// This code is contributed by shivanisinghss2110


Python3




# Python program to compare two version number
 
# Method to compare two versions.
# Return 1 if v2 is smaller,
# -1 if v1 is smaller,,
# 0 if equal
def versionCompare(v1, v2):
     
    # This will split both the versions by '.'
    arr1 = v1.split(".")
    arr2 = v2.split(".")
    n = len(arr1)
    m = len(arr2)
     
    # converts to integer from string
    arr1 = [int(i) for i in arr1]
    arr2 = [int(i) for i in arr2]
  
    # compares which list is bigger and fills
    # smaller list with zero (for unequal delimiters)
    if n>m:
      for i in range(m, n):
         arr2.append(0)
    else if m>n:
      for i in range(n, m):
         arr1.append(0)
     
    # returns 1 if version 1 is bigger and -1 if
    # version 2 is bigger and 0 if equal
    for i in range(len(arr1)):
      if arr1[i]>arr2[i]:
         return 1
      else if arr2[i]>arr1[i]:
         return -1
    return 0
 
# Driver program to check above comparison function
version1 = "1.0.3"
version2 = "1.0.7"
 
ans = versionCompare(version1, version2)
if ans < 0:
    print (version1 + " is smaller")
else if ans > 0:
    print (version2 + " is smaller")
else:
    print ("Both versions are equal")
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
# and improved by Tuhin Das (tuhindas221b)


C#




// C# program to compare
// two version number
using System;
class GFG
{
 
  // Method to compare two versions.
  // Returns 1 if v2 is smaller, -1
  // if v1 is smaller, 0 if equal
  static int versionCompare(string v1, string v2)
  {
    // vnum stores each numeric
    // part of version
    int vnum1 = 0, vnum2 = 0;
 
    // loop until both string are
    // processed
    for (int i = 0, j = 0; (i < v1.Length || j < v2.Length);)
    {
       
      // storing numeric part of
      // version 1 in vnum1
      while (i < v1.Length && v1[i] != '.')
      {
        vnum1 = vnum1 * 10 + (v1[i] - '0');
        i++;
      }
 
      // storing numeric part of
      // version 2 in vnum2
      while (j < v2.Length && v2[j] != '.')
      {
        vnum2 = vnum2 * 10 + (v2[j] - '0');
        j++;
      }
 
      if (vnum1 > vnum2)
        return 1;
      if (vnum2 > vnum1)
        return -1;
 
      // if equal, reset variables and
      // go for next numeric part
      vnum1 = vnum2 = 0;
      i++;
      j++;
    }
    return 0;
  }
 
  // Driver code
  static void Main()
  {
    string version1 = "1.0.3";
    string version2 = "1.0.7";
 
    if (versionCompare(version1, version2) < 0)
      Console.WriteLine(version1 + " is smaller");
    else if (versionCompare(version1, version2) > 0)
      Console.WriteLine(version2 + " is smaller");
    else
      Console.WriteLine("Both version are equal");
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript




<script>
// Javascript implementation
 
// Method to compare two versions.
// Returns 1 if v2 is smaller, -1
// if v1 is smaller, 0 if equal
function versionCompare(v1, v2)
{
    // vnum stores each numeric
    // part of version
    var vnum1 = 0, vnum2 = 0;
 
    // loop until both string are
    // processed
    for (var i = 0, j = 0; (i < v1.length
                            || j < v2.length);) {
        // storing numeric part of
        // version 1 in vnum1
        while (i < v1.length && v1[i] != '.') {
            vnum1 = vnum1 * 10 + (v1[i] - '0');
            i++;
        }
 
        // storing numeric part of
        // version 2 in vnum2
        while (j < v2.length && v2[j] != '.') {
            vnum2 = vnum2 * 10 + (v2[j] - '0');
            j++;
        }
 
        if (vnum1 > vnum2)
            return 1;
        if (vnum2 > vnum1)
            return -1;
 
        // if equal, reset variables and
        // go for next numeric part
        vnum1 = vnum2 = 0;
        i++;
        j++;
    }
    return 0;
}
 
// Driver method to check above
// comparison function
var version1 = "1.0.3";
var version2 = "1.0.7";
 
if (versionCompare(version1, version2) < 0)
    document.write(version1 + " is smaller" + "<br>");
else if (versionCompare(version1, version2) > 0)
    document.write(version2 + " is smaller" + "<br>");
else
    document.write("Both version are equal" + "<br>");
 
// This is code is contributed
// by shubhamsingh10
</script>


Output

1.0.3 is smaller












Complexity Analysis:  

  • Time Complexity: O(n), where n is the length of the string. 
    Only one traversal of the string is needed.
  • Auxiliary space: O(1). 
    As no extra space is needed.

Another Approach(Using Recursion):

Intuition:

The idea is quite simple, first you split the version strings by the dots. Once you have the constituent parts, you then find the shorter and iterate through the split sections till you hit the lenght of the shorter version number after splitting. Whatever index youre in, it will be at i. What you do next is recursively call the comparison function parsing in a splice of the longer version number starting from the index of the shorter length and the shorter length version is parsed in as [“0”] since leading 0s do not affect the number anyway.

At each stage, check for whichever is greater and appropriately return 0 or 1. When the lengths are equal ater iteration till the end index(Can be checked by seeing if the version lengths are the same as the end loop index), if and no difference can be detected, return 0.

Approach:

  • Split version1 and version2 strings into a list on the “.” pattern.
  • Map each string element in the list into an integer.
  • Relying upon the power of pattern matching in function definitions, recursively step down each item in the two lists and compare them.
  • Fill in a single item list of [0] where a version’s list representation has exhausted all elements.
  • If we reach the end of the list, the versions are equivalent; return 0.

C++




// C/C++ program to compare
// two version number
#include <bits/stdc++.h>
using namespace std;
 
// Method to compare two versions.
// Returns 1 if v2 is smaller, -1
// if v1 is smaller, 0 if equal
int  check(string v1, string v2){
        if(v1==v2)return 0;
        if(v1=="")v1 = "";
        if(v2=="")v2 = "";
         
        int p1 = 0, p2 = 0;
        int n1 = v1.length(), n2 = v2.length();
         
        //find the location of the next '.' if it exists
        if(v1.find('.')!=string::npos){
            n1 = v1.find('.');
             
        }
        if(v2.find('.')!=string::npos){
            n2 = v2.find('.');
        }
         
        // create the sub-version string
        string str1 = "", str2 = "";
        while(p1<n1)str1+=v1[p1++];
        while(p2<n2)str2+=v2[p2++];
         
        //convert the subversion string to integer to match it
        int st1 = 0, st2 =0 ;
        if(str1.length()>0)
             st1 = stoi(str1);
        if(str2.length()>0)
             st2 = stoi(str2);
         
        // check according to the given condition
        if(st1<st2) return -1;
        else if(st1>st2) return 1;
         
        if(n1< v1.length())
         v1 = v1.substr(n1+1);
        else v1 = "";
         
        if(n2< v2.length())
         v2 = v2.substr(n2+1);
        else v2= "";
         
        // if the sub version strings are equal, then check for the next part using recursion
        // say 1.001 and 1.02
        // 1 and 1 are equal so now check 001 and 02
        int ans = check(v1, v2 );
        return ans;
         
    }
int compareVersion(string version1, string version2) {
        int ans = check(version1, version2);
        return ans;
    }
 
// Driver method to check above
// comparison function
int main()
{
    string version1 = "1.0.3";
    string version2 = "1.0.7";
 
    if (compareVersion(version1, version2) < 0)
        cout << version1 << " is smaller\n";
    else if (compareVersion(version1, version2) > 0)
        cout << version2 << " is smaller\n";
    else
        cout << "Both version are equal\n";
    return 0;
}


Java




public class VersionComparison {
    // Method to compare two sub-versions.
    // Returns 1 if v2 is smaller, -1 if v1 is smaller, 0 if equal
    public static int check(String v1, String v2) {
        if (v1.equals(v2)) return 0;
        if (v1.isEmpty()) v1 = "";
        if (v2.isEmpty()) v2 = "";
 
        int p1 = 0, p2 = 0;
        int n1 = v1.length(), n2 = v2.length();
 
        // Find the location of the next '.' if it exists
        if (v1.contains(".")) {
            n1 = v1.indexOf('.');
        }
        if (v2.contains(".")) {
            n2 = v2.indexOf('.');
        }
 
        String str1 = "", str2 = "";
        while (p1 < n1) str1 += v1.charAt(p1++);
        while (p2 < n2) str2 += v2.charAt(p2++);
 
        int st1 = 0, st2 = 0;
        if (!str1.isEmpty()) st1 = Integer.parseInt(str1);
        if (!str2.isEmpty()) st2 = Integer.parseInt(str2);
 
        if (st1 < st2) return -1;
        else if (st1 > st2) return 1;
 
        if (n1 < v1.length())
            v1 = v1.substring(n1 + 1);
        else v1 = "";
 
        if (n2 < v2.length())
            v2 = v2.substring(n2 + 1);
        else v2 = "";
 
        // If the sub-version strings are equal, then check for the next part using recursion
        int ans = check(v1, v2);
        return ans;
    }
 
    // Method to compare two versions.
    public static int compareVersion(String version1, String version2) {
        int ans = check(version1, version2);
        return ans;
    }
 
    public static void main(String[] args) {
        String version1 = "1.0.3";
        String version2 = "1.0.7";
 
        // Compare the versions and display the result
        int result = compareVersion(version1, version2);
 
        if (result < 0)
            System.out.println(version1 + " is smaller");
        else if (result > 0)
            System.out.println(version2 + " is smaller");
        else
            System.out.println("Both versions are equal");
    }
}


Python3




def compareVersion(version1, version2):
    # Helper function to parse a version string into a list of integers
    def parse_version(version):
        version_parts = version.split('.'# Split the version string by '.'
        version_ints = [int(part) for part in version_parts]  # Convert each part to an integer
        return version_ints
 
    # Parse the input version strings into lists of integers
    v1_parts = parse_version(version1)
    v2_parts = parse_version(version2)
 
    # Compare each part of the version numbers
    for i in range(max(len(v1_parts), len(v2_parts))):
        v1_num = v1_parts[i] if i < len(v1_parts) else 0  # Use 0 if no more parts in v1
        v2_num = v2_parts[i] if i < len(v2_parts) else 0  # Use 0 if no more parts in v2
 
        if v1_num < v2_num:
            return -1  # version1 is smaller
        elif v1_num > v2_num:
            return 1   # version2 is smaller
 
    return 0  # Both versions are equal
 
# Example usage:
version1 = "1.0.3"
version2 = "1.0.7"
 
result = compareVersion(version1, version2)
if result < 0:
    print(version1, "is smaller")
elif result > 0:
    print(version2, "is smaller")
else:
    print("Both versions are equal")


C#




using System;
 
class Program
{
    // Method to compare two version strings.
    // Returns 1 if version2 is smaller, -1 if version1 is smaller, 0 if equal.
    static int CompareVersion(string version1, string version2)
    {
        // If both versions are equal, return 0.
        if (version1 == version2)
            return 0;
 
        // Split the version strings by dot ('.') to compare individual parts.
        string[] parts1 = version1.Split('.');
        string[] parts2 = version2.Split('.');
         
        int length = Math.Max(parts1.Length, parts2.Length);
 
        for (int i = 0; i < length; i++)
        {
            int part1 = i < parts1.Length ? int.Parse(parts1[i]) : 0;
            int part2 = i < parts2.Length ? int.Parse(parts2[i]) : 0;
 
            // Compare the individual parts of the versions.
            if (part1 < part2)
                return -1;
            else if (part1 > part2)
                return 1;
        }
 
        // If no difference is found, return 0 (versions are equal).
        return 0;
    }
 
    static void Main()
    {
        string version1 = "1.0.3";
        string version2 = "1.0.7";
 
        int result = CompareVersion(version1, version2);
 
        if (result < 0)
            Console.WriteLine(version1 + " is smaller");
        else if (result > 0)
            Console.WriteLine(version2 + " is smaller");
        else
            Console.WriteLine("Both versions are equal");
    }
}


Javascript




// JavaScript Program for the above approach
function check(v1, v2) {
  if (v1 === v2) return 0;
  if (v1 === "") v1 = "";
  if (v2 === "") v2 = "";
 
  let p1 = 0, p2 = 0;
  let n1 = v1.length, n2 = v2.length;
 
  // find the location of the next '.' if it exists
  if (v1.indexOf('.') !== -1) {
    n1 = v1.indexOf('.');
  }
  if (v2.indexOf('.') !== -1) {
    n2 = v2.indexOf('.');
  }
 
  // create the sub-version string
  let str1 = "", str2 = "";
  while (p1 < n1) str1 += v1[p1++];
  while (p2 < n2) str2 += v2[p2++];
 
  // convert the subversion string to integer to match it
  let st1 = 0, st2 = 0;
  if (str1.length > 0)
    st1 = parseInt(str1);
  if (str2.length > 0)
    st2 = parseInt(str2);
 
  // check according to the given condition
  if (st1 < st2) return -1;
  else if (st1 > st2) return 1;
 
  if (n1 < v1.length)
    v1 = v1.substring(n1 + 1);
  else v1 = "";
 
  if (n2 < v2.length)
    v2 = v2.substring(n2 + 1);
  else v2 = "";
 
  // if the sub version strings are equal, then check for the next part using recursion
  // say 1.001 and 1.02
  // 1 and 1 are equal so now check 001 and 02
  let ans = check(v1, v2);
  return ans;
}
 
function compareVersion(version1, version2) {
  let ans = check(version1, version2);
  return ans;
}
 
// Driver method to check above comparison function
const version1 = "1.0.3";
const version2 = "1.0.7";
 
const result = compareVersion(version1, version2);
if (result < 0)
    console.log(`${version1} is smaller`);
else if (result > 0)
    console.log(`${version2} is smaller`);
else
    console.log("Both versions are equal");
 
// THIS CODE IS CONTRIBUTED BY KIRGI AGARWAL


Output

1.0.3 is smaller












Time Complexity: O(n), where n is the length of the string, recursive calls in the string.
Auxiliary space: O(n), Auxillary stack space.

Approach: 

The approach compares two version numbers by splitting them into individual parts and comparing each part numerically. Here’s the intuition behind this approach:

  1. Splitting the Version Numbers: The approach begins by splitting the input version numbers (v1 and v2) into arrays version1 and version2, respectively. This is done by using the dot (.) as the delimiter. For example, the version number “1.0.3” would be split into the array [1, 0, 3].
  2. Comparing Corresponding Parts: The approach then iterates through each part of the version numbers, comparing the corresponding parts numerically. It starts with the first part of both version numbers and continues until it reaches the end of the longer version number.
  3. Handling Missing Parts: If one version number has fewer parts than the other, it is assumed that the missing parts are 0. This is handled by assigning 0 to num1 or num2 when accessing a part beyond the length of the corresponding version number array.
  4. Numeric Comparison: For each part, the approach compares the numeric values of num1 and num2. If num1 is greater than num2, it means that v1 is larger and the method returns 1. If num2 is greater than num1, it means that v2 is larger, and the method returns -1.
  5. Equality Check: If the loop completes without any larger or smaller parts being found, it means that the version numbers are equal, and the method returns 0.
  6. Output: Finally, in the main method, the comparison result is used to print the appropriate message indicating whether version1 is smaller, version2 is smaller, or both versions are equal.

This approach provides a straightforward way to compare version numbers by breaking them down into individual parts and comparing them numerically. It ensures that each part is compared correctly, even if the version numbers have different lengths or contain missing parts.

C++




#include <iostream>
#include <sstream>
#include <string>
#include <vector>
 
using namespace std;
 
// Method to compare two versions.
// Returns 1 if v2 is smaller, -1 if v1 is smaller, 0 if
// equal
int versionCompare(string v1, string v2)
{
    vector<int> version1, version2;
    istringstream iss1(v1);
    istringstream iss2(v2);
    string token;
 
    // Split the versions by dot and store in vectors
    while (getline(iss1, token, '.')) {
        version1.push_back(stoi(token));
    }
    while (getline(iss2, token, '.')) {
        version2.push_back(stoi(token));
    }
 
    int length = max(version1.size(), version2.size());
 
    for (int i = 0; i < length; i++) {
        int num1 = (i < version1.size()) ? version1[i] : 0;
        int num2 = (i < version2.size()) ? version2[i] : 0;
 
        if (num1 > num2)
            return 1;
        if (num2 > num1)
            return -1;
    }
 
    return 0;
}
 
// Driver method to check above comparison function
int main()
{
    string version1 = "1.0.3";
    string version2 = "1.0.7";
 
    int result = versionCompare(version1, version2);
 
    if (result < 0)
        cout << version1 << " is smaller" << endl;
    else if (result > 0)
        cout << version2 << " is smaller" << endl;
    else
        cout << "Both versions are equal" << endl;
 
    return 0;
}


Java




import java.util.*;
 
class GFG {
 
    // Method to compare two versions.
    // Returns 1 if v2 is smaller, -1 if v1 is smaller, 0 if equal
    static int versionCompare(String v1, String v2) {
        String[] version1 = v1.split("\\.");
        String[] version2 = v2.split("\\.");
 
        int length = Math.max(version1.length, version2.length);
 
        for (int i = 0; i < length; i++) {
            int num1 = (i < version1.length) ? Integer.parseInt(version1[i]) : 0;
            int num2 = (i < version2.length) ? Integer.parseInt(version2[i]) : 0;
 
            if (num1 > num2)
                return 1;
            if (num2 > num1)
                return -1;
        }
 
        return 0;
    }
 
    // Driver method to check above comparison function
    public static void main(String[] args) {
        String version1 = "1.0.3";
        String version2 = "1.0.7";
 
        int result = versionCompare(version1, version2);
 
        if (result < 0)
            System.out.println(version1 + " is smaller");
        else if (result > 0)
            System.out.println(version2 + " is smaller");
        else
            System.out.println("Both versions are equal");
    }
}


Python3




def version_compare(v1, v2):
    # Split the input version strings into lists of integers by splitting on the period ('.').
    version1 = list(map(int, v1.split('.')) if v1 else [])  # Convert v1 to a list of integers, or an empty list if v1 is empty.
    version2 = list(map(int, v2.split('.')) if v2 else [])  # Convert v2 to a list of integers, or an empty list if v2 is empty.
 
    # Find the maximum length of the version lists to ensure we compare all components.
    length = max(len(version1), len(version2))
 
    # Compare each component of the version strings.
    for i in range(length):
        num1 = version1[i] if i < len(version1) else 0  # Get the component or use 0 if it doesn't exist.
        num2 = version2[i] if i < len(version2) else 0  # Get the component or use 0 if it doesn't exist.
 
        if num1 > num2:
            return 1  # v1 is greater than v2.
        if num2 > num1:
            return -1  # v2 is greater than v1.
 
    return 0  # The versions are equal.
 
# Example version strings to compare
version1 = "1.0.3"
version2 = "1.0.7"
 
# Call the version_compare function to compare the two versions.
result = version_compare(version1, version2)
 
# Print the result of the comparison.
if result < 0:
    print(f"{version1} is smaller")
elif result > 0:
    print(f"{version2} is smaller")
else:
    print("Both versions are equal")


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
    // Function to compare two version strings.
    // Returns 1 if v2 is smaller, -1 if v1 is smaller, 0 if
    // equal.
    static int VersionCompare(string v1, string v2)
    {
        // Split version strings by dot and convert them to
        // integer lists.
        List<int> version1
            = v1.Split('.').Select(int.Parse).ToList();
        List<int> version2
            = v2.Split('.').Select(int.Parse).ToList();
 
        // Determine the maximum length of the two version
        // lists.
        int length
            = Math.Max(version1.Count, version2.Count);
 
        for (int i = 0; i < length; i++) {
            // Get the i-th component of each version.
            int num1
                = (i < version1.Count) ? version1[i] : 0;
            int num2
                = (i < version2.Count) ? version2[i] : 0;
 
            if (num1 > num2)
                return 1;
            if (num2 > num1)
                return -1;
        }
 
        // If no difference is found, the versions are
        // equal.
        return 0;
    }
 
    static void Main(string[] args)
    {
        string version1 = "1.0.3";
        string version2 = "1.0.7";
 
        // Call the VersionCompare function to compare the
        // versions.
        int result = VersionCompare(version1, version2);
 
        if (result < 0)
            Console.WriteLine(version1 + " is smaller");
        else if (result > 0)
            Console.WriteLine(version2 + " is smaller");
        else
            Console.WriteLine("Both versions are equal");
    }
}


Javascript




function versionCompare(v1, v2) {
    const version1 = v1.split('.').map(Number);
    const version2 = v2.split('.').map(Number);
 
    const length = Math.max(version1.length, version2.length);
 
    for (let i = 0; i < length; i++) {
        const num1 = i < version1.length ? version1[i] : 0;
        const num2 = i < version2.length ? version2[i] : 0;
 
        if (num1 > num2) return 1;
        if (num2 > num1) return -1;
    }
 
    return 0;
}
 
const version1 = "1.0.3";
const version2 = "1.0.7";
 
const result = versionCompare(version1, version2);
 
if (result < 0)
    console.log(version1 + " is smaller");
else if (result > 0)
    console.log(version2 + " is smaller");
else
    console.log("Both versions are equal");


Output:

1.0.3 is smaller

 Time Complexity: O(max(m, n)), where m and n represent the number of parts in the respective version numbers.

Space Complexity: O(max(m, n)).

This article is contributed by Utkarsh Trivedi.  



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads