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
Difficulty
and has an acceptance rate of about 47% (1+ million submissions).
Typical patterns to solve this problem:
- String
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- 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