Leetcode #165: Compare Version Numbers
In this guide, we solve Leetcode #165 Compare Version Numbers in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Two Pointers, String
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Python Solution
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
m, n = len(version1), len(version2)
i = j = 0
while i < m or j < n:
a = b = 0
while i < m and version1[i] != '.':
a = a * 10 + int(version1[i])
i += 1
while j < n and version2[j] != '.':
b = b * 10 + int(version2[j])
j += 1
if a != b:
return -1 if a < b else 1
i, j = i + 1, j + 1
return 0
Complexity
The time complexity is , and the space complexity is , where and are the lengths of the two strings. The space complexity is , where and are the lengths of the two strings.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.