Problem 165

Abstract / Summary

Compare two version numbers by splitting them into parts and checking each part from left to right to see which is greater.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0165.py

class Solution:
    def explode(self, s):
        parts = s.split(".")
        return [int(x) for x in parts]

    def compareVersion(self, version1: str, version2: str) -> int:
        a = self.explode(version1)
        b = self.explode(version2)

        while len(a) < len(b):
            a.append(0)
        while len(b) < len(a):
            b.append(0)

        for i in range(len(a)):
            if a[i] < b[i]:
                return -1
            if a[i] > b[i]:
                return +1

        return 0
21 lines | 539 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 47% (1+ million submissions).

Typical patterns to solve this problem:
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class with two methods that together compare two version strings. The first method, explode, transforms a dotted version string into a list of integer components. The second method, compareVersion, normalizes the two component lists to the same length, then walks through them element-by-element to decide which version is greater, equal, or smaller.

Key Steps

Splitting a version string into numeric parts

def explode(self, s):
    parts = s.split(".")
    return [int(x) for x in parts]

The method receives a string such as "1.2.10", splits it on the period character, and immediately converts each substring to an integer. By using a list comprehension the conversion happens in a single pass, producing a compact list like [1, 2, 10]. Converting to int removes any leading zeros, so "01" and "1" are treated identically.

Aligning the length of the two component lists

while len(a) < len(b):
    a.append(0)
while len(b) < len(a):
    b.append(0)

After obtaining the two integer lists, the code ensures they share the same length. If one list is shorter, zeros are appended until both lengths match. This padding treats missing trailing components as zero, which matches the conventional interpretation of version numbers (e.g., "1.0" equals "1").

Element-wise comparison with early exit

for i in range(len(a)):
    if a[i] < b[i]:
        return -1
    if a[i] > b[i]:
        return +1
return 0

A simple for loop iterates over the aligned lists. At each index the corresponding integers are compared. The moment a difference is found, the method returns -1 or +1 immediately, avoiding any further work. If the loop finishes without finding a discrepancy, the versions are considered equal and 0 is returned.

Edge Cases Handled

The algorithm gracefully handles version strings that contain a different number of components. By padding the shorter list with zeros, cases such as "2.1" versus "2.1.0.0" are resolved as equal. Because each component is converted to an integer, leading zeros do not affect the outcome; "1.02" and "1.2" compare as identical. The early-return logic also means that once a decisive component is encountered, later components-whether present or absent-do not influence the result.

Performance Optimizations

The use of a list comprehension in explode reduces the overhead of a separate loop for conversion, creating the integer list in a tight, C-level construct. Padding is performed with append, which operates in amortized constant time, and only the necessary number of zeros are added. The comparison loop benefits from an early-exit strategy: as soon as a mismatching component is detected, the function returns, preventing unnecessary iteration over the remaining elements. This approach keeps the runtime proportional to the length of the common prefix of the two version strings.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there are two lego towers made of blocks stacked on top of each other. The code looks at two different secret codes made of numbers separated by little dots.

First, it takes each code and breaks it apart into a pile of small number blocks. If one pile has fewer blocks than the other, the code adds empty zero blocks until both piles are exactly the same height so they are fair to look at.

Now the code picks up the top block from each pile and checks which one is bigger. If the blocks are the same size, it moves down to the next pair of blocks. It keeps looking deeper into the piles until it finds a block that is different. If the second pile has a bigger block, it knows the second version is newer. If the first pile has a bigger block, it knows the first version is newer. If it finishes looking at every single block and everything matches, it decides that the two versions are exactly the same.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.27 | σ = 0.71

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust C# Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
gaosq0604 Python
gouthampradhan Java
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
qiyuangong Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
withaarzoo C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
gaosq0604 Python
gouthampradhan Java
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
qiyuangong Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
withaarzoo C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
49 links | 33 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Leetcode 165: Compare Version Numbers with stringstream | StringTokenizer | codestorywithMIK'
codestorywithMIK 24 mins
Leetcode 165: Compare Version Numbers with stringstream | StringTokenizer | codestorywithMIK
YouTube video 'Compare Version Numbers | Leetcode 165 | Strings | Day-25'
Ayushi Sharma 15 mins
Compare Version Numbers | Leetcode 165 | Strings | Day-25
YouTube video 'compare version numbers leetcode | leetcode 165 | string'
Naresh Gupta 9 mins
compare version numbers leetcode | leetcode 165 | string
YouTube video '165. Compare Version Numbers | 3 Ways | Split String Custom Function | 2 Pointers'
Aryan Mittal 14 mins
165. Compare Version Numbers | 3 Ways | Split String Custom Function | 2 Pointers
YouTube video '165. Compare Version Numbers | leetcode daily challenge | DSA | Hindi | shashwat'
ShashCode 21 mins
165. Compare Version Numbers | leetcode daily challenge | DSA | Hindi | shashwat
YouTube video 'Leetcode - Compare Version Numbers (Python)'
Timothy H Chang 6 mins
Leetcode - Compare Version Numbers (Python)
YouTube video 'Compare Version Numbers  | September leetcode challenge Day 9 | Leetcode 165'
Coding Decoded 12 mins
Compare Version Numbers | September leetcode challenge Day 9 | Leetcode 165
YouTube video 'Compare Version Numbers | Leet code 165 | Theory explained + Python code'
Sai Anish Malla 8 mins
Compare Version Numbers | Leet code 165 | Theory explained + Python code
YouTube video '165. Compare Version Numbers | Leetcode Daily - Python'
Leetcode Daily 7 mins
165. Compare Version Numbers | Leetcode Daily - Python
YouTube video 'Daily Leetcode #2002: Sep 23, 2025 - 165. Compare Version Numbers'
Programming Live with Larry 7 mins
Daily Leetcode #2002: Sep 23, 2025 - 165. Compare Version Numbers
YouTube video 'Compare Version Numbers | LeetCode 165 | Coders Camp'
Coders Camp 7 mins
Compare Version Numbers | LeetCode 165 | Coders Camp
YouTube video 'Daily Leetcode #1494: May 03, 2024 - 165. Compare Version Numbers'
Programming Live with Larry 6 mins
Daily Leetcode #1494: May 03, 2024 - 165. Compare Version Numbers
YouTube video 'Compare Version Numbers (LeetCode 165) (Two Pointer Approach)'
CodeWithARB 16 mins
Compare Version Numbers (LeetCode 165) (Two Pointer Approach)
YouTube video 'LeetCode 165: Compare Version Numbers | Java Solution | Two-Pointer Approach'
Code Scribbler 5 mins
LeetCode 165: Compare Version Numbers | Java Solution | Two-Pointer Approach
YouTube video 'Compare Version Numbers | LeetCode 165 | Two Pointers | String | MAANG'
Code Harmony 21 mins
Compare Version Numbers | LeetCode 165 | Two Pointers | String | MAANG
YouTube video 'Compare Version Numbers | LeetCode 165 | Covered All Edge Cases'
Sanyam IIT Guwahati 15 mins
Compare Version Numbers | LeetCode 165 | Covered All Edge Cases
YouTube video 'Compare Version Numbers |leetcode 165|165. Compare Version Numbers |leetcode potd | Two Pointer'
Code Thoughts 10 mins
Compare Version Numbers |leetcode 165|165. Compare Version Numbers |leetcode potd | Two Pointer
YouTube video 'Daily Leetcode #162: Sep 09, 2020 - 165. Compare Version Numbers'
Programming Live with Larry 8 mins
Daily Leetcode #162: Sep 09, 2020 - 165. Compare Version Numbers
YouTube video '165. Compare Version Numbers | Simple Greedy | Leetcode Daily Challenge'
Eye on AI and DSA 15 mins
165. Compare Version Numbers | Simple Greedy | Leetcode Daily Challenge
YouTube video 'Compare Version Numbers | LeetCode 165 - Python'
impoldev 7 mins
Compare Version Numbers | LeetCode 165 - Python
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality