Compare Version Numbers — LeetCode 165 Python Solution

MediumTwo PointersString
Problem
#165
Reading time
3 min

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 0

Complexity

MeasureComplexity
TimeO(\max(m, n))
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview