165. Compare Version Numbers
MediumView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Split both version strings by "." and compare corresponding integer components.
Advertisement
Intuition
Split both version strings by "." and compare corresponding integer components. If one version has fewer parts, treat missing parts as 0.
Algorithm
- 1Split v1 and v2 by ".".
- 2Iterate up to max(len1, len2). Parse each part as int (0 if missing).
- 3If part1 < part2 return -1. If part1 > part2 return 1.
- 4Return 0 if all parts equal.
Example Walkthrough
Input: version1 = "1.01", version2 = "1.001"
- 1.Part 0: 1 vs 1 - equal. Part 1: 01->1 vs 001->1 - equal.
- 2.Return 0.
Output: 0
Common Pitfalls
- •Parse as int to strip leading zeros - "01" and "1" are the same version component.
165.cs
C#
// Approach: Split both strings by '.', parse integer segments, compare
// pair-by-pair padding the shorter version with zeros.
// Time: O(n) Space: O(n)
public class Solution
{
public int CompareVersion(string version1, string version2)
{
string[] v1 = version1.Split('.');
string[] v2 = version2.Split('.');
int len = Math.Max(v1.Length, v2.Length);
for (int i = 0; i < len; i++)
{
int val1 = i < v1.Length ? Int32.Parse(v1[i]) : 0;
int val2 = i < v2.Length ? Int32.Parse(v2[i]) : 0;
int compare = val1.CompareTo(val2);
if (compare != 0)
return compare;
}
return 0;
}
}Advertisement
Was this solution helpful?
Related Problems
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)