#165

Compare Version Numbers

Medium
Two PointersStringTwo PointersString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses two pointers to traverse both version strings simultaneously. This method is efficient as it avoids unnecessary comparisons and directly handles missing revisions.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two pointers for each version string.
  2. 2Step 2: Use a loop to compare segments of both versions until both pointers reach the end.
  3. 3Step 3: For each segment, convert to integer and compare, treating missing segments as 0.
solution.py24 lines
1# Full working Python code
2version1 = '1.2'
3version2 = '1.10'
4
5p1, p2 = 0, 0
6while p1 < len(version1) or p2 < len(version2):
7    v1_revision = 0
8    v2_revision = 0
9    while p1 < len(version1) and version1[p1] != '.':
10        v1_revision = v1_revision * 10 + int(version1[p1])
11        p1 += 1
12    while p2 < len(version2) and version2[p2] != '.':
13        v2_revision = v2_revision * 10 + int(version2[p2])
14        p2 += 1
15    if v1_revision < v2_revision:
16        print(-1)
17        break
18    elif v1_revision > v2_revision:
19        print(1)
20        break
21    p1 += 1
22    p2 += 1
23else:
24    print(0)

Complexity note: The complexity is O(n) because we traverse each version string only once, making it efficient for longer strings.

  • 1Version segments are compared as integers, ignoring leading zeros.
  • 2Missing segments are treated as zero, allowing for flexible versioning.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.