
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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int compareVersion(char * version1, char * version2){
6 char *v1 = strdup(version1);
7 char *v2 = strdup(version2);
8 char *part1;
9 char *part2;
10 int num1, num2;
11
12 part1 = strtok(v1, ".");
13 part2 = strtok(v2, ".");
14
15 while(part1 != NULL || part2 != NULL) {
16 num1 = part1 ? atoi(part1) : 0;
17 num2 = part2 ? atoi(part2) : 0;
18
19 if(num1 < num2) return -1;
20 if(num1 > num2) return 1;
21
22 part1 = part1 ? strtok(NULL, ".") : NULL;
23 part2 = part2 ? strtok(NULL, ".") : NULL;
24 }
25
26 return 0;
27}The C solution uses strtok to split the version strings by dot character. Each component is converted to an integer using atoi. We then compare corresponding components, returning -1 or 1 if one is smaller or greater, respectively. The loop continues until all components are compared.
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
This Python approach aligns with using manual parsing, moving through each string character-by-character to logically assemble each integer for a direct comparison of non-preprocessed data.