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: "1.01" vs "1.001.1"version1 = "1.01"version2 = "1.001.1"110"1""01"→1missing→0111"1""001"→1"1"1 = 1 ✓1 = 1 ✓0 < 1 ✗Result: -1 (version1 < version2)Leading zeros ignored, missing revisions treated as 0
Understanding the Visualization
1
Input
Two version strings with dot-separated revisions
2
Parse
Extract and convert revisions to integers, ignoring leading zeros
3
Compare
Compare revisions left-to-right, treating missing as 0
Key Takeaway
🎯 Key Insight: Parse revisions numerically while handling leading zeros and missing parts
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