Taro Logo

Compare Version Numbers

#11 Most AskedMedium
0 views
Topics:
StringsTwo Pointers

Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros.

To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0.

Return the following:

  • If version1 < version2, return -1.
  • If version1 > version2, return 1.
  • Otherwise, return 0.

Example 1:

Input: version1 = "1.2", version2 = "1.10"

Output: -1

Explanation:

version1's second revision is "2" and version2's second revision is "10": 2 < 10, so version1 < version2.

Example 2:

Input: version1 = "1.01", version2 = "1.001"

Output: 0

Explanation:

Ignoring leading zeroes, both "01" and "001" represent the same integer "1".

Example 3:

Input: version1 = "1.0", version2 = "1.0.0.0"

Output: 0

Explanation:

version1 has less revisions, which means every missing revision are treated as "0".

Constraints:

  • 1 <= version1.length, version2.length <= 500
  • version1 and version2 only contain digits and '.'.
  • version1 and version2 are valid version numbers.
  • All the given revisions in version1 and version2 can be stored in a 32-bit integer.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum number of revisions or the maximum length of a version string we can expect?
  2. Can we assume that the version strings are always well-formatted containing only digits and dots, or could there be invalid characters, trailing dots, or consecutive dots?
  3. How should we handle version strings of different lengths (e.g., comparing "1.0" and "1.0.1")? Are missing revisions implicitly treated as 0?
  4. Can revision numbers exceed the standard 32-bit or 64-bit integer limits, requiring us to handle them as arbitrarily large integers or strings?
  5. What should be returned if the two version strings are completely identical?

Brute Force Solution

Approach

Imagine you need to figure out which of two version numbers is newer by reading them both from left to right. The brute force strategy involves breaking down both version numbers into all their individual sections and matching them up step by step until a difference is spotted.

Here's how the algorithm would work step-by-step:

  1. Start by taking the first version number and splitting it into pieces wherever there is a dot.
  2. Do the exact same thing for the second version number, splitting it into pieces at every dot.
  3. Line up the corresponding pieces from both versions next to each other, starting from the very first piece on the left.
  4. If one version runs out of pieces, pretend that it has extra pieces with a value of zero so both versions have the same number of pieces to compare.
  5. Look at the first pair of pieces, convert them into plain numbers, and see which one is larger.
  6. If the numbers in this first pair are different, immediately stop and declare the version with the larger number as the newer one.
  7. If the numbers in the first pair are equal, move on to the next pair of pieces to the right and repeat the comparison.
  8. If you check every single pair of pieces all the way to the end and find that every single one matches, conclude that both version numbers are completely identical.

Code Implementation

def compareVersion(version1: str, version2: str) -> int:
    
    version_pieces_one = version1.split(".")
    version_pieces_two = version2.split(".")
    
    max_length = max(len(version_pieces_one), len(version_pieces_two))
    
    # We pad the shorter version with zeros so both lists have identical lengths for safe comparison
    for index in range(max_length):
        
        current_piece_one = int(version_pieces_one[index]) if index < len(version_pieces_one) else 0
        current_piece_two = int(version_pieces_two[index]) if index < len(version_pieces_two) else 0
        
        # Immediate return is required because the leftmost differing version piece dictates precedence
        if current_piece_one > current_piece_two:
            return 1
            
        if current_piece_one < current_piece_two:
            return -1
            
    # Reaching this return statement proves every single corresponding piece matched without any difference
    return 0

Big(O) Analysis

Time Complexity
O(n + m) – Let n be the length of the first version string and m be the length of the second version string. We iterate through both strings to split them by dots into individual sections, taking time proportional to their lengths. Next, we loop through the corresponding pairs of sections, converting and comparing them until we find a difference or exhaust the longer version. Since we process each character and section at most once, the total operations scale linearly with the sum of the input sizes, resulting in O(n + m).
Space Complexity
O(N) – To compare the version numbers, we split both input strings into pieces wherever there is a dot, as described in steps one and two. This creates two temporary arrays of substrings whose total size is proportional to the combined lengths of the input strings, which we denote as N. Although we parse these pieces as numbers on the fly, the auxiliary string arrays dominate the memory usage. Therefore, the extra memory grows linearly with the input size, resulting in a space complexity of O(N).

Optimal Solution

Approach

To compare two version numbers fairly, we break them down into smaller pieces separated by dots and examine them section by section from left to right. If any section is larger than the corresponding section in the other version, we immediately know which one is newer, and if all sections match, the versions are identical.

Here's how the algorithm would work step-by-step:

  1. Line up the two version numbers side by side so you can compare them piece by piece, starting from the very first section on the far left.
  2. Isolate the first section of both version numbers, ignoring any leading zeros so that values like zero-one and one are treated as the same.
  3. Convert these isolated sections into numerical values to understand their true mathematical worth.
  4. Compare the two numbers to see which one is larger. If the top one is bigger, the first version is newer. If the bottom one is bigger, the second version is newer.
  5. If the two numbers happen to be equal, move your attention to the next section to the right for both version numbers.
  6. If one version runs out of sections while the other still has sections remaining, treat the missing sections as having a value of zero.
  7. Repeat this process moving steadily from left to right through every section until you find a difference or run out of sections entirely, which means both versions are equal.

Code Implementation

def compare_version_numbers(version_string_one, version_string_two):
    sections_list_one = version_string_one.split('.')
    sections_list_two = version_string_two.split('.')
    max_sections_length = max(len(sections_list_one), len(sections_list_two))
    
    for section_index in range(max_sections_length):
        # Missing sections default to zero to ensure fair alignment between versions of unequal lengths.
        current_value_one = int(sections_list_one[section_index]) if section_index < len(sections_list_one) else 0
        
        current_value_two = int(sections_list_two[section_index]) if section_index < len(sections_list_two) else 0
        
        # Mathematical comparison determines relative newness immediately upon finding the first differing section.
        if current_value_one > current_value_two:
            return 1
            
        if current_value_one < current_value_two:
            return -1
            
    # Identical values across all parsed sections mean both version numbers represent the exact same release.
    return 0

Big(O) Analysis

Time Complexity
O(N) – Let N be the total length of the longer version string. We iterate through both version strings simultaneously by using pointers or splitting by the dot delimiter to process each revision section from left to right. Inside this traversal, parsing each numerical section takes time proportional to the number of digits in that section. Since every character in the version strings is examined a constant number of times, the total operations scale linearly with N, which simplifies to O(N).
Space Complexity
O(N) – To compare the version numbers, we split both input strings into segments separated by dots. This creates temporary arrays of revision values for each version string. Assuming N represents the total length of the version strings, these split operations allocate auxiliary string and integer arrays proportional to the number of segments. Therefore, the extra memory scales linearly with the input size N, resulting in an overall space complexity of O(N).

Edge Cases

Versions with differing lengths of revision blocks like 1.01 and 1
How to Handle:
Treat missing revisions as zero during the left-to-right comparison loop.
Revisions containing multiple leading zeros like 1.0003 and 1.3
How to Handle:
Parse each revision substring into a standard integer to naturally strip leading zeros.
Extremely long version strings with many dot-separated revisions
How to Handle:
Use a two-pointer string traversal approach instead of allocating heavy memory arrays for splitting.
Version strings with trailing dots like 1.0. or 1..1
How to Handle:
Treat empty segments between consecutive or trailing dots as a value of zero.
Version numbers with extremely large revision integers exceeding standard limits
How to Handle:
Accumulate parsed values using 64-bit integer types to prevent arithmetic overflow.
Completely identical version strings such as 7.5.2 and 7.5.2
How to Handle:
Traverse both strings fully, find all revisions equal, and return zero at the end.
0/12 completed