LeetCode Entry

165. Compare Version Numbers

23.09.2025 medium 2025 kotlin rust

Compare versions x.x.x.x

165. Compare Version Numbers medium blog post substack youtube

1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1121

Problem TLDR

Compare versions x.x.x.x #medium

Intuition

Pad start strings or convert to ints.

Approach

  • 25 characters for pad start
  • pad lists of numbers length to the largest

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


// 23ms
    fun compareVersion(v1: String, v2: String) = listOf(v1, v2)
        .map { it.split('.').map {it.toInt()}}
        .let { (a, b) -> val d = List(abs(a.size - b.size)){0}; (a+d).zip(b+d)}
        .map { (a, b) -> a.compareTo(b) }.firstOrNull { it != 0 } ?: 0


// 0ms
    pub fn compare_version(v: String, w: String) -> i32 {
        v.split('.').zip_longest(w.split('.')).map(|e|e.or("0","0"))
        .map(|(l,r)|l.parse::<i32>().unwrap().cmp(&r.parse::<i32>().unwrap()) as i32)
        .find(|&x| x != 0).unwrap_or(0)
    }