Skip to content
Related Articles

Related Articles

Improve Article
Compare two Version numbers
  • Difficulty Level : Easy
  • Last Updated : 20 Jun, 2021

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 smaller). 

Example: 

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

Input: 
V1 = “1.0.10”
V2 = “1.0.27”
Output:  v1 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.
 

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

Python




# 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 delimeters)
    if n>m:
      for i in range(m, n):
         arr2.append(0)
    elif 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
      elif 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"
elif 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.

This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes 




My Personal Notes arrow_drop_up
Recommended Articles
Page :