Compare Version Numbers
Description
doc
Solutions
First Idea
const trimZero = (acc, cur) => (!acc.length && cur === 0 ? acc : [cur, ...acc])
const toVersions = (v) =>
v
.split('.')
.map((v) => parseInt(v))
.reduceRight(trimZero, [])
const compare = (a, b) => (a === b ? 0 : a > b ? 1 : -1)
/**
* @param {string} version1
* @param {string} version2
* @return {number}
*/
var compareVersion = function (version1, version2) {
const vers1 = toVersions(version1)
const vers2 = toVersions(version2)
const min = vers1.length < vers2.length ? vers1.length : vers2.length
for (let i = 0; i < min; i++) {
const v1 = vers1[i]
const v2 = vers2[i]
if (v1 !== v2) {
return compare(v1, v2)
}
}
return compare(vers1.length, vers2.length)
}
- Time Complexity: O(n)
- Space Complexity: O(n)