Compare two Version numbers

Last Updated : 18 Jun, 2026

Given two non-empty strings v1 and v2 representing version numbers in the form a.b.c..., where each part is a number separated by dots(.), determine which version is greater. To compare the versions:

  • Compare corresponding parts separated by dot(.) from left to right.
  • Treat each part as an integer (ignoring leading zeros) and consider missing parts as 0.
  • Stop at the first mismatch; otherwise, the versions are equal.

Return 1 if v1 > v2, -1 if v1 < v2, otherwise return 0.

Example: 

Input: v1 = "0.2", v2 = "1.0"
Output: -1
Explanation: Compare the first part before .: 0 < 1, so v2 is greater than v1.

Input: v1 = "1.0.1", v2 = "1"
Output: 1
Explanation: First part: 1 == 1. Second part: 0 == 0 (since missing part in v2 is treated as 0). Third part: 1 > 0, so v1 > v2.

Input: v1 = "1.01", v2 = "1.001"
Output: 0
Explanation: First part: 1 == 1. Second part: 01 and 001 both represent the integer 1. Hence, all corresponding parts are equal and the versions are considered equal.

[Naive Approach] Split and Compare Parts - O(|v1|+|v2|) Time and O(|v1|+|v2|) Space

The idea is to split both version strings into arrays using the dot (.) separator and compare the corresponding parts from left to right. Convert each part into an integer and compare the values. If one version has fewer parts, treat the missing parts as 0. The comparison stops at the first mismatch; if no mismatch is found, both versions are considered equal.

  • Split both version strings into arrays using dot(.) as the separator.
  • Traverse both arrays from left to right.
  • Convert the current parts into integers.
  • Compare the extracted values.
  • If they differ, return the result immediately.
  • Otherwise, continue by treating missing parts as 0.
  • If all parts are equal, return 0.
C++
#include <bits/stdc++.h>
using namespace std;

int versionCompare(string v1, string v2)
{

    // Split version strings by '.'
    vector<string> v1Parts, v2Parts;
    string temp;

    stringstream s1(v1), s2(v2);

    while (getline(s1, temp, '.'))
    {
        v1Parts.push_back(temp);
    }

    while (getline(s2, temp, '.'))
    {
        v2Parts.push_back(temp);
    }

    int n = v1Parts.size();
    int m = v2Parts.size();

    int len = max(n, m);

    for (int i = 0; i < len; i++)
    {

        // If part is missing, treat as 0
        int num1 = (i < n) ? stoi(v1Parts[i]) : 0;
        int num2 = (i < m) ? stoi(v2Parts[i]) : 0;

        // Compare corresponding parts
        if (num1 < num2)
            return -1;
        if (num1 > num2)
            return 1;
    }

    return 0;
}

int main()
{

    string v1 = "0.2", v2 = "1.0";
    cout << versionCompare(v1, v2) << "\n";
}
Java
class GFG {

    static int versionCompare(String v1, String v2)
    {

        // Split version strings by '.'
        String[] v1Parts = v1.split("\\.");
        String[] v2Parts = v2.split("\\.");

        int n = v1Parts.length;
        int m = v2Parts.length;

        int len = Math.max(n, m);

        for (int i = 0; i < len; i++)
        {

            // If part is missing, treat as 0
            int num1 = (i < n) ? Integer.parseInt(v1Parts[i]) : 0;
            int num2 = (i < m) ? Integer.parseInt(v2Parts[i]) : 0;

            // Compare corresponding parts
            if (num1 < num2)
                return -1;
            if (num1 > num2)
                return 1;
        }

        return 0;
    }

    public static void main(String[] args)
    {
        String v1 = "0.2", v2 = "1.0";
        System.out.println(versionCompare(v1, v2));
    }
}
Python
def versionCompare(v1, v2):

    # Split version strings by '.'
    v1Parts = v1.split('.')
    v2Parts = v2.split('.')

    n = len(v1Parts)
    m = len(v2Parts)

    len_ = max(n, m)

    for i in range(len_):

        # If part is missing, treat as 0
        num1 = int(v1Parts[i]) if i < n else 0
        num2 = int(v2Parts[i]) if i < m else 0

        # Compare corresponding parts
        if num1 < num2:
            return -1
        if num1 > num2:
            return 1

    return 0


if __name__ == "__main__":
    v1 = "0.2"
    v2 = "1.0"
    print(versionCompare(v1, v2))
C#
using System;

class GFG
{
    static int versionCompare(string v1, string v2)
    {

        // Split version strings by '.'
        string[] v1Parts = v1.Split('.');
        string[] v2Parts = v2.Split('.');

        int n = v1Parts.Length;
        int m = v2Parts.Length;

        int len = Math.Max(n, m);

        for (int i = 0; i < len; i++)
        {

            // If part is missing, treat as 0
            int num1 = (i < n) ? int.Parse(v1Parts[i]) : 0;
            int num2 = (i < m) ? int.Parse(v2Parts[i]) : 0;

            // Compare corresponding parts
            if (num1 < num2)
                return -1;
            if (num1 > num2)
                return 1;
        }

        return 0;
    }

    static void Main()
    {
        string v1 = "0.2", v2 = "1.0";
        Console.WriteLine(versionCompare(v1, v2));
    }
}
JavaScript
function versionCompare(v1, v2) {

    // Split version strings by '.'
    let v1Parts = v1.split('.');
    let v2Parts = v2.split('.');

    let n = v1Parts.length;
    let m = v2Parts.length;

    let len = Math.max(n, m);

    for (let i = 0; i < len; i++) {

        // If part is missing, treat as 0
        let num1 = (i < n) ? parseInt(v1Parts[i]) : 0;
        let num2 = (i < m) ? parseInt(v2Parts[i]) : 0;

        // Compare corresponding parts
        if (num1 < num2)
            return -1;
        if (num1 > num2)
            return 1;
    }

    return 0;
}

// Driver code
let v1 = "0.2", v2 = "1.0";
console.log(versionCompare(v1, v2));

Output
-1

[Expected Approach] Two Pointer Traversal - O(|v1|+|v2|) Time and O(1) Space

The idea is to compare the version numbers while traversing the strings directly, without splitting them into separate arrays.

Use two pointers to process both version strings simultaneously. For each version, extract the numeric part between two dots (.) (or between a dot and the end of the string) and convert it into an integer. Compare the extracted numbers immediately. If they are different, return the corresponding result. Otherwise, continue with the next parts.

If one version has fewer parts than the other, the missing parts are treated as 0. If all corresponding parts are equal, the two version numbers are considered equal.

Consider the String: v1 = "1.0.1", v2 = "1"

  • Extract the first parts: 1 and 1. Since they are equal, move to the next parts.
  • Extract the second parts: 0 and 0 (the missing second part in v2 is treated as 0). They are equal.
  • Extract the third parts: 1 and 0 (the missing third part in v2 is treated as 0).
  • Since 1 > 0, v1 is greater than v2.

Therefore, the output is: 1

C++
#include <bits/stdc++.h>
using namespace std;

int versionCompare(string v1, string v2)
{
    int i = 0, j = 0;
    int n = v1.size(), m = v2.size();

    while (i < n || j < m)
    {
        int num1 = 0, num2 = 0;

        // Extract number from v1
        while (i < n && v1[i] != '.')
        {
            num1 = num1 * 10 + (v1[i] - '0');
            i++;
        }

        // Extract number from v2
        while (j < m && v2[j] != '.')
        {
            num2 = num2 * 10 + (v2[j] - '0');
            j++;
        }

        // Compare corresponding parts
        if (num1 < num2)
            return -1;
        if (num1 > num2)
            return 1;

        // Move past '.'
        i++;
        j++;
    }

    return 0;
}

int main()
{
    string v1 = "1.0.1", v2 = "1";
    cout << versionCompare(v1, v2) << "\n";
}
Java
class GFG {

    static int versionCompare(String v1, String v2)
    {
        int i = 0, j = 0;
        int n = v1.length(), m = v2.length();

        while (i < n || j < m)
        {
            int num1 = 0, num2 = 0;

            // Extract number from v1
            while (i < n && v1.charAt(i) != '.')
            {
                num1 = num1 * 10 + (v1.charAt(i) - '0');
                i++;
            }

            // Extract number from v2
            while (j < m && v2.charAt(j) != '.')
            {
                num2 = num2 * 10 + (v2.charAt(j) - '0');
                j++;
            }

            // Compare corresponding parts
            if (num1 < num2)
                return -1;
            if (num1 > num2)
                return 1;

            // Move past '.'
            i++;
            j++;
        }

        return 0;
    }

    public static void main(String[] args)
    {
        String v1 = "1.0.1", v2 = "1";
        System.out.println(versionCompare(v1, v2));
    }
}
Python
def versionCompare(v1, v2):
    i = 0
    j = 0
    n = len(v1)
    m = len(v2)

    while i < n or j < m:

        num1 = 0
        num2 = 0

        # Extract number from v1
        while i < n and v1[i] != '.':
            num1 = num1 * 10 + (ord(v1[i]) - ord('0'))
            i += 1

        # Extract number from v2
        while j < m and v2[j] != '.':
            num2 = num2 * 10 + (ord(v2[j]) - ord('0'))
            j += 1

        # Compare corresponding parts
        if num1 < num2:
            return -1
        if num1 > num2:
            return 1

        # Move past '.'
        i += 1
        j += 1

    return 0


if __name__ == "__main__":
    v1 = "1.0.1"
    v2 = "1"
    print(versionCompare(v1, v2))
C#
using System;

class GFG
{
    static int versionCompare(string v1, string v2)
    {
        int i = 0, j = 0;
        int n = v1.Length, m = v2.Length;

        while (i < n || j < m)
        {
            int num1 = 0, num2 = 0;

            // Extract number from v1
            while (i < n && v1[i] != '.')
            {
                num1 = num1 * 10 + (v1[i] - '0');
                i++;
            }

            // Extract number from v2
            while (j < m && v2[j] != '.')
            {
                num2 = num2 * 10 + (v2[j] - '0');
                j++;
            }

            // Compare corresponding parts
            if (num1 < num2)
                return -1;
            if (num1 > num2)
                return 1;

            // Move past '.'
            i++;
            j++;
        }

        return 0;
    }

    static void Main()
    {
        string v1 = "1.0.1", v2 = "1";
        Console.WriteLine(versionCompare(v1, v2));
    }
}
JavaScript
function versionCompare(v1, v2)
{
    let i = 0, j = 0;
    let n = v1.length, m = v2.length;

    while (i < n || j < m)
    {
        let num1 = 0, num2 = 0;

        // Extract number from v1
        while (i < n && v1[i] != '.')
        {
            num1 = num1 * 10 + (v1.charCodeAt(i) - 48);
            i++;
        }

        // Extract number from v2
        while (j < m && v2[j] != '.')
        {
            num2 = num2 * 10 + (v2.charCodeAt(j) - 48);
            j++;
        }

        // Compare corresponding parts
        if (num1 < num2)
            return -1;
        if (num1 > num2)
            return 1;

        // Move past '.'
        i++;
        j++;
    }

    return 0;
}

// Driver code
let v1 = "1.0.1";
let v2 = "1";
console.log(versionCompare(v1, v2));

Output
1
Comment