Skip to main contentprofolio

165 — Compare Version Numbers

Compare two version numbers version1 and version2 and return 1 if version1 > version2, -1 if version1 < version2, otherwise 0.

Problem

Given two version numbers, version1 and version2, compare them.

  • If version1 > version2 return 1.
  • If version1 < version2 return -1.
  • Otherwise return 0.

Version numbers consist of one or more revisions joined by .. Each revision is an integer without leading zeros. Extra trailing zeros are ignored.

Example 1:

Input: version1 = "1.01", version2 = "1.001"
Output: 0
Explanation: Both versions represent 1.1.

Example 2:

Input: version1 = "1.0", version2 = "1.0.0"
Output: 0

Example 3:

Input: version1 = "0.1", version2 = "1.1"
Output: -1

Approach

  1. Split each version string by . into an array of numbers.
  2. Compare corresponding elements from left to right.
  3. If all corresponding elements are equal, the longer version is checked for extra non-zero elements.
  4. Return 1, -1, or 0 accordingly.

Complexity

  • Time Complexity: O(n + m), where n and m are the number of revisions in version1 and version2.
  • Space Complexity: O(n + m) for storing the split arrays.

JavaScript Solution

Java Solution


Insight

Remember to ignore leading zeros and extra trailing zeros in versions. This ensures correct comparison even when version strings have different lengths.


Source: