Compare Versions


Given two strings which represent different version releases of a software, print -1, 1 or 0 depending on the order of the releases.

If version1 was released after version2 print 1,
If version1 was released before version2 print -1,
otherwise print 0.

Assumptions granted : Strings may only contain digits and the ‘.'(dot) character and must contain atleast 1 character.

The ‘.’ character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not “two and a half” or “half way to version three”, it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 1.13 < 1.13.4

version number such as 1, 01, 1.0 are equivalent.

I would request you to change tabs or minimize your browser and give a good 30-40 minutes before seeing the solution.

This is a basic implementation based question, the only thing to take care about is the sequence of 0’s that may crept in after a dot.

WordPress is not rendering the code properly so kindly check out the code here on github.

Time Complexity   : O(n), where n is the sum of the lengths of the 2 versions.
Space Complexity  : O(n), where n is the sum of the lengths of the 2 versions.

It can also be done with the space complexity of O(1), with the help of substr function, left as an exercise. 

You can follow this blog for more such posts. Comment in your queries, report bugs, discuss! 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.