
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.
1function compareVersion(version1, version2) {
2 const v1 = version1.split('.');
3 const v2 = version2.split('.');
4
5 const length = Math.max(v1.length, v2.length);
6 for (let i = 0; i < length; i++) {
7 const num1 = i < v1.length ? parseInt(v1[i]) : 0;
8 const num2 = i < v2.length ? parseInt(v2[i]) : 0;
9 if (num1 < num2) return -1;
10 if (num1 > num2) return 1;
11 }
12
13 return 0;
14}The JavaScript solution uses the split method to retrieve version components, which are then converted and compared as integers using a loop that accounts for differing lengths by assuming missing components as zero.
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.