Show problems as
Classic problem #165MediumTwo PointersString

Compare Version Numbers

Real-world version: Firmware Revision Order
Tracked in this browser only
Read Compare Version Numbers on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A device reports its firmware revision as a string: one or more chunks of decimal digits joined by single dots, for example "4.11.0".

A chunk is read as a plain decimal integer, so leading zeros inside a chunk carry no meaning and "3.04" names the same revision as "3.4".

Compare the revisions left and right. Line their chunks up starting from the leftmost one. When one revision runs out of chunks before the other, treat each of its missing chunks as 0.

Return -1 when left is the earlier revision, 1 when right is the earlier revision, and 0 when the two strings name the same revision.

Examples

Example 1

Input
left = "2.9", right = "2.10"
Output
-1

The first chunks tie at 2. The second chunks read as 9 and 10, and 9 is the smaller integer, so left is the earlier revision.

Example 2

Input
left = "7.012", right = "7.12"
Output
0

The chunk "012" reads as the integer 12, matching "12", and the first chunks both read as 7, so the two strings name the same revision.

Example 3

Input
left = "5.0.1", right = "5"
Output
1

Padding the right-hand revision gives chunks 5, 0 and 0. The first two pairs tie and the third pair is 1 against 0, so right is the earlier revision.

Example 4

Input
left = "3.0", right = "3"
Output
0

The missing chunk on the right counts as 0, which matches the 0 on the left, so the revisions are the same.

Constraints

  • 1 <= left.length, right.length <= 500
  • left and right contain only digits and '.'.
  • left and right are valid revision strings.
  • Every chunk in left and right fits in a 32-bit signed integer.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def compare_version(left: str, right: str) -> int:
Java
public int compareVersion(String left, String right)