1. String Split by Dot and Integer Array Comparison
Intuition
1. Split version1 by "\." to get array v1.
2. Split version2 by "\." to get array v2.
3. Loop k from 0 to max(v1.length, v2.length):
- num1 = k < v1.length ? Integer.parseInt(v1[k]) : 0
- num2 = k < v2.length ? Integer.parseInt(v2[k]) : 0
- If num1 != num2, return num1 < num2 ? -1 : 1
4. Return 0 if all revisions match.
When to apply: Quick solution using language string split utilities.
Algorithm
- Split strings by dot separator.
- Iterate up to max chunk count.
- Parse chunks to integer, defaulting missing chunks to 0.
- Return -1, 1, or 0 based on comparison.
String Split by Dot and Integer Array Comparison
2 of 2 questions left todayObservation: Split both version strings on
Observation: Split both version strings on . into token arrays: v1 = ['1', '01'] and v2 = ['1', '001'].
Decision: Parse index 0 tokens to integers: 1 vs 1. Difference is 0.
Invariant: Leading zeros are naturally discarded by integer conversion (01 -> 1).
#include <iostream>#include <string>#include <vector>#include <sstream> class Solution {public: int compareVersion(std::string version1, std::string version2) { std::vector<int> v1, v2; std::string token; std::stringstream ss1(version1); while (std::getline(ss1, token, '.')) { v1.push_back(std::stoi(token)); } std::stringstream ss2(version2); while (std::getline(ss2, token, '.')) { v2.push_back(std::stoi(token)); } int n = std::max(v1.size(), v2.size()); for (int i = 0; i < n; ++i) { int num1 = (i < v1.size()) ? v1[i] : 0; int num2 = (i < v2.size()) ? v2[i] : 0; if (num1 < num2) return -1; if (num1 > num2) return 1; } return 0; }}; int main() { Solution sol; std::cout << sol.compareVersion("1.2", "1.10") << std::endl; // -1 std::cout << sol.compareVersion("1.01", "1.001") << std::endl; // 0 std::cout << sol.compareVersion("1.0", "1.0.0.0") << std::endl; // 0 return 0;}Time & Space Complexity
- Time complexity:
O(N + M)— Splitting and parsing takes linear time in the combined length of the version strings. - Space complexity:
O(N + M)
Why Brute Force Doesn't Scale:
Naive brute force re-examines already processed substrings multiple times.
For N = 105, O(N2) requires 1010 operations (TLE), while O(N) finishes in < 10ms.