LeetCode #165 Medium

Compare Version Numbers

Compare dotted version strings numerically per chunk: return −1, 0, or 1. "1.01" == "1.001", "1.0" == "1".

stringtwo-pointers
Open on LeetCode ↗
02

Intuition

💡

Split on dots and compare chunk-by-chunk as integers — int() eats leading zeros for free. Different lengths? Missing chunks count as 0, so pad the shorter side conceptually.

03

Approach

1

Chunks, not characters

"1.10" > "1.9" numerically though it's smaller lexicographically — so convert each chunk with int().

2

Walk to the longer length

Iterate max(len(a), len(b)) chunks, treating absent ones as 0 — that's how "1.0" equals "1".

3

First difference decides

Return on the first unequal pair; equal all the way → 0.

04

Solution & live demo

python
1class Solution:
2 def compareVersion(self, version1, version2):
3 a = [int(x) for x in version1.split(".")]
4 b = [int(x) for x in version2.split(".")]
5 for i in range(max(len(a), len(b))):
6 x = a[i] if i < len(a) else 0
7 y = b[i] if i < len(b) else 0
8 if x != y:
9 return 1 if x > y else -1
10 return 0
05

Edge cases

Leading zeros, "1.01" vs "1.001"

int() normalizes both to 1 → equal.

Trailing zero chunks, "1.0.0" vs "1"

Missing chunks read as 0 → equal.

06

Complexity

Time
O(n + m)
Space
O(n + m)
Split + one comparison pass.