Skip to content
Problem 165 · LeetCode 165(opens in a new tab)

Compare Version Numbers

MediumStrings

A version string is made of revisions separated by dots, like "4.0.12". Each revision is a whole number; leading zeros do not change it, so "007" and "7" are the same revision.

Compare version1 and version2 revision by revision from the left. When one string has fewer revisions, its missing ones count as 0. Return −1 if version1 is smaller, 1 if it is larger, and 0 if the two are equal.

Example 1

Input:  version1 = "2.5", version2 = "2.12"
Output: -1
Why:    first revisions tie; then 5 < 12
2 more examples and the constraints

Example 2

Input:  version1 = "3.04", version2 = "3.4.0"
Output: 0
Why:    04 is 4, and the missing third revision is 0

Example 3

Input:  version1 = "1.0.1", version2 = "1"
Output: 1
Why:    version2 reads as 1.0.0, and 1 > 0 in the third place

Constraints

  • 1 ≤ length of version1, version2 ≤ 500
  • Both strings hold only digits and dots, and are valid version strings
  • Every revision fits in a 32-bit integer

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split on dots and compare numbersO(n + m)
  2. Two pointers, parse as you goO(n + m)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for two 500-character versionsVerdict
Split on dots and compare numbersO(n + m)
Passes; builds two lists
Two pointers, parse as you goO(n + m)
Best; no extra memory

n and m = lengths of version1 and version2.

Edge cases to test

  • Leading zeros. "1.01" and "1.1" are equal.
  • Trailing zero revisions. "6" and "6.0.0" are equal: 0 is what a missing revision counts as.
  • Different lengths that differ. "1.0.1" is bigger than "1", because the third revision 1 beats a missing 0.
  • Numbers, not text. "2.12" is bigger than "2.5", even though "1" sorts before "5" as text.

Common mistakes

  • Comparing revisions as strings, so "12" looks smaller than "5".
  • Stopping at the end of the shorter string, so "1" and "1.0.1" look equal.
  • Splitting on "." as a regex in Java, which matches every character; use "\\.".

How to talk through it

  1. 1Clarify. Do leading zeros matter? Is "1" equal to "1.0"? Does every revision fit in an int?
  2. 2Give the split. Split on dots, convert to numbers, pad the shorter list with 0 and compare.
  3. 3Drop the lists. Two pointers can parse one revision at a time from each string.
  4. 4Handle the ends. A finished string keeps giving 0 until the other one ends too.
  5. 5Test out loud. Run "2.5" vs "2.12", "3.04" vs "3.4.0" and "1.0.1" vs "1".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?