Compare Version Numbers — LeetCode 165 Python Solution
MediumTwo PointersString
- Problem
- #165
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'.
Python solution
Python
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 0Complexity
| Measure | Complexity |
|---|---|
| Time | O(\max(m, n)) |
| Space | O(1), where m and n are the lengths of the two strings auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 165. Compare Version Numbers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 165. Compare Version Numbers?
- LeetCode 165. Compare Version Numbers is rated Medium on LeetCode.
- What is the time complexity of LeetCode 165. Compare Version Numbers?
- The Python solution on this page runs in O(\max(m, n)).
- What is the space complexity of LeetCode 165. Compare Version Numbers?
- The Python solution on this page uses O(1), where m and n are the lengths of the two strings auxiliary space.
- What topics does LeetCode 165. Compare Version Numbers cover?
- LeetCode 165. Compare Version Numbers is tagged Two Pointers and String on LeetCode.