
Sponsored
Sponsored
This approach involves splitting the version strings into individual components using the dot delimiter. We then convert these components into integers and compare them one by one. If one version string is shorter, we treat the missing components as 0, allowing a fair comparison.
Time Complexity: O(n + m), where n and m are lengths of version1 and version2 respectively.
Space Complexity: O(n + m) for holding the split components.
1class Solution:
2 def compareVersion(self, version1: str, version2: str) -> int:
3 v1 = version1.split('.')
4 v2 = version2.split('.')
5
6 length = max(len(v1), len(v2))
7 for i in range(length):
8 num1 = int(v1[i]) if i < len(v1) else 0
9 num2 = int(v2[i]) if i < len(v2) else 0
10 if num1 < num2:
11 return -1
12 if num1 > num2:
13 return 1
14
15 return 0The Python solution utilizes the split method for breaking down version strings. Each component is converted to an integer for comparison using a loop that handles shorter version strings by assuming missing components as 0.
This approach utilizes two pointers to traverse each version string's components simultaneously. By identifying and isolating numerical values between dots without splitting the string, we optimize for memory usage. Each number is evaluated and compared until a determination is made or the end is reached.
Time Complexity: O(n + m), where n and m are the lengths of version1 and version2.
Space Complexity: O(1), as no significant additional space is used.
1
The C solution employs a method where pointers traverse each version string, constructing numerical values between dots manually. This avoids unnecessary string operations and directly compares values to determine the result.