Skip to main content
Back to problems
#165
Medium Algorithms

Compare version numbers

Two Pointers String
46.1% acceptance
Jan 12, 2026
3161
2796
Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros. To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0. Return the following: If version1 < version2, return -1. If version1 > version2, return 1. Otherwise, return 0.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn compare_version(version1: String, version2: String) -> i32 {
    let v1: Vec<i32> = version1.split('.').map(|s| s.parse().unwrap()).collect();
    let v2: Vec<i32> = version2.split('.').map(|s| s.parse().unwrap()).collect();
    
    let max_len = v1.len().max(v2.len());
    
    for i in 0..max_len {
      let num1 = if i < v1.len() { v1[i] } else { 0 };
      let num2 = if i < v2.len() { v2[i] } else { 0 };
      
      if num1 > num2 {
        return 1;
      } else if num1 < num2 {
        return -1;
      }
    }
    
    0
  }
}