algoadvance

You are given two version numbers, version1 and version2, represented as strings. A version number consists of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being the highest significance. For example, 2.5.33 and 0.1 are valid version numbers.

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that 1.0 is considered the same as 1, and 1.0.0 is considered the same as 1.

Return the following:

Clarifying Questions

  1. Can we assume that the input strings are always valid version numbers?
    • Yes, you can assume the input strings are valid version strings.
  2. Are there any constraints on the length of the version strings?
    • No, you can assume the length of the version strings is reasonable and fits within the problem constraints.

Strategy

  1. Split both version1 and version2 by the '.' delimiter to extract individual revisions as strings.
  2. Convert these revisions to integers to handle the comparison correctly.
  3. Compare corresponding revisions in a loop:
    • If one version has fewer revisions, treat the missing revisions as 0.
  4. Use a loop to compare the revisions.
  5. Return -1, 1, or 0 based on the comparison results.

Code

def compareVersion(version1: str, version2: str) -> int:
    # Split the version strings into lists of integers
    v1 = list(map(int, version1.split('.')))
    v2 = list(map(int, version2.split('.')))

    # Determine the maximum length of the version lists
    max_length = max(len(v1), len(v2))

    # Compare corresponding revisions
    for i in range(max_length):
        revision1 = v1[i] if i < len(v1) else 0
        revision2 = v2[i] if i < len(v2) else 0

        if revision1 < revision2:
            return -1
        elif revision1 > revision2:
            return 1

    # If all corresponding revisions are equal
    return 0

Time Complexity

This implementation efficiently compares version numbers by parsing and comparing each revision numerically.

Try our interview co-pilot at AlgoAdvance.com