Compare two Version numbers

A version number is a string that is used to identify unique states of a software product. A version number looks like a.b.c.d where a, b, etc are number, so the version number is a string in which numbers are separated by dots. These numbers generally represent 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 dot but the versions can compared numeric part wise and then the latest version can be found. Traverse through strings and separate numeric part and compare them, if equal then next numeric part is compared and so on until they differ otherwise flag them as equal.
Implement a method to compare two versions, If there are more than two versions then the below versionCompare method can be used as compare method of sort method, which will sort all versions according to the specified comparison.



C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 untill 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

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right



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 contribute.geeksforgeeks.org or mail your article to contribute@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.

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details




My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.