Compare Version Numbers - Problem

Given two version strings version1 and version2, compare them.

A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros.

To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0.

Return the following:

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

Input & Output

Example 1 — Basic Comparison
$ Input: version1 = "1.01", version2 = "1.001"
Output: 0
💡 Note: Both versions have revisions [1, 1] after removing leading zeros from "01" and "001", so they are equal
Example 2 — Missing Revision
$ Input: version1 = "1.0", version2 = "1.0.0"
Output: 0
💡 Note: version1 has revisions [1, 0] and version2 has [1, 0, 0]. Missing revisions are treated as 0, so they are equal
Example 3 — Clear Difference
$ Input: version1 = "0.1", version2 = "1.1"
Output: -1
💡 Note: First revision: 0 < 1, so version1 is smaller than version2

Constraints

  • 1 ≤ version1.length, version2.length ≤ 500
  • version1 and version2 only contain digits and '.'
  • version1 and version2 are valid version numbers
  • All the given revisions in version1 and version2 can be stored in a 32-bit integer

Visualization

Tap to expand
Compare Version Numbers INPUT version1 = "1.01" "1 . 01" Split by '.': 1 01 version2 = "1.001" "1 . 001" Split by '.': 1 001 ALGORITHM STEPS 1 Split Strings Split by '.' delimiter 2 Convert to Integer Remove leading zeros "01" --> 1 "001" --> 1 3 Compare Revisions Left to right order Rev v1 v2 [0] 1 1 [1] 1 1 4 Return Result All equal = return 0 FINAL RESULT Comparison Summary: [1, 1] = [1, 1] Both versions are EQUAL Output: 0 Return 0 because version1 == version2 -1: v1<v2 | 0: v1=v2 | 1: v1>v2 Key Insight: Leading zeros don't affect integer value: "01" and "001" both convert to 1. Compare revision by revision using integer conversion. Treat missing revisions as 0. TutorialsPoint - Compare Version Numbers | Optimal Solution
Asked in
Apple 15 Microsoft 12 Amazon 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen