0165. Compare Version Numbers
leetcode
Problem:
The problem "Compare Version Numbers" requires comparing two version numbers `a` and `b` and returning:
- `1` if `a` is greater,
- `-1` if `b` is greater,
- `0` if both are equal.
Each version number string comprises numbers separated by dots (e.g., "1.0.1", "7.5.2.4"). We will compare each numerical segment from left to right. If any segment differs, the comparison result is determined.
Solution Description:
To implement the solution, we need to:
- Split the version numbers by the dot.
- Iterate through the numbers segment by segment.
- Compare corresponding segments as integers.
- Return `1`, `-1`, or `0` based on the first non-equal segment. If all compared segments are equal, return `0`.
Time Complexity: O(n) where n is the number of segments in the longer version number. Space Complexity: O(n) for storing the split segments.
Example:
Consider two version numbers "1.0.1" and "1". Splitting them gives ["1", "0", "1"] and ["1"].
- Compare "1" with "1" -> equal.
- Compare "0" with no corresponding part in "1" (assumed 0) -> segment in "1.0.1" is greater.
Thus, "1.0.1" > "1" and should return `1`.
Setup:
We'll use a skeleton code and a series of test cases for implementation. This includes the main comparison logic and console logs for validation.
Test Execution:
Multiple test cases including edge cases and different lengths of versions will be covered.
// Dummy function for template purposes.
/**
* Compares two version numbers.
* @param {string} version1
* @param {string} version2
* @return {number} -1 if version1 < version2, 1 if version1 > version2, else 0
*/
function compareVersion(version1, version2) {
const log = typeof NestedInteger !== 'undefined' ? () => {} : console.log;
const table = typeof NestedInteger!== 'undefined' ? () => {} : console.table;
const vLeftGreater = 1;
const vEqual = 0;
const vRightGreater = -1;
const leftTokens = version1.split('.').map(n => Number(n));
const rightTokens = version2.split('.').map(n => Number(n));
const maxLen = Math.max(leftTokens.length, rightTokens.length);
for (let i = 0; i < maxLen; i++) {
const left = i < leftTokens.length ? leftTokens[i] : 0;
const right = i < rightTokens.length ? rightTokens[i] : 0;
if (left > right) {
return vLeftGreater;
} else if (left < right) {
return vRightGreater;
}
}
// Dummy result for now.
return vEqual;
}
// Test cases
const testCases = [
{ version1: "1.01", version2: "1.001", expected: 0 },
{ version1: "1.0", version2: "1.0.0", expected: 0 },
{ version1: "0.1", version2: "1.1", expected: -1 },
{ version1: "1.0.1", version2: "1", expected: 1 },
{ version1: "7.5.2.4", version2: "7.5.3", expected: -1 }
];
testCases.forEach((test, index) => {
const result = compareVersion(test.version1, test.version2);
console.log(`Test Case ${index + 1}: ${result === test.expected ? 'Passed' : `Failed (Expected: ${test.expected}, Got: ${result})`}`);
});