Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Last active September 24, 2025 21:40
Show Gist options
  • Select an option

  • Save Ifihan/51c483fa0901db86f63a39ef7a6872c6 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/51c483fa0901db86f63a39ef7a6872c6 to your computer and use it in GitHub Desktop.
Compare Version Numbers

Question

Approach

I solve this by splitting both version strings into lists of integers, padding the shorter one with zeros, and then comparing element by element.

Implementation

class Solution:
    def compareVersion(self, version1: str, version2: str) -> int:
        v1 = list(map(int, version1.split('.')))
        v2 = list(map(int, version2.split('.')))
        
        length = max(len(v1), len(v2))
        v1.extend([0] * (length - len(v1)))
        v2.extend([0] * (length - len(v2)))
        
        for a, b in zip(v1, v2):
            if a < b:
                return -1
            elif a > b:
                return 1
        return 0

Complexities

  • Time: O(n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment