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.
Example 1:
Input:version1 = "1.2", version2 = "1.10"
Output:-1
Explanation:
version1's second revision is "2" and version2's second revision is "10": 2 < 10, so version1 < version2.
Example 2:
Input:version1 = "1.01", version2 = "1.001"
Output:0
Explanation:
Ignoring leading zeroes, both "01" and "001" represent the same integer "1".
Example 3:
Input:version1 = "1.0", version2 = "1.0.0.0"
Output:0
Explanation:
version1 has less revisions, which means every missing revision are treated as "0".
Constraints:
1 <= version1.length, version2.length <= 500
version1 and version2 only contain digits and '.'.
version1 and version2are valid version numbers.
All the given revisions in version1 and version2 can be stored in a 32-bit integer.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers
Example 1
"1.2"
"1.10"
Example 2
"1.01"
"1.001"
Example 3
"1.0"
"1.0.0.0"
Step 02
Core Insight
What unlocks the optimal approach
You can use two pointers for each version string to traverse them together while comparing the corresponding segments.
Utilize the substring method to extract each version segment delimited by '.'. Ensure you're extracting the segments correctly by adjusting the start and end indices accordingly.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #165: Compare Version Numbers
class Solution {
public int compareVersion(String version1, String version2) {
int m = version1.length(), n = version2.length();
for (int i = 0, j = 0; i < m || j < n; ++i, ++j) {
int a = 0, b = 0;
while (i < m && version1.charAt(i) != '.') {
a = a * 10 + (version1.charAt(i++) - '0');
}
while (j < n && version2.charAt(j) != '.') {
b = b * 10 + (version2.charAt(j++) - '0');
}
if (a != b) {
return a < b ? -1 : 1;
}
}
return 0;
}
}
// Accepted solution for LeetCode #165: Compare Version Numbers
func compareVersion(version1 string, version2 string) int {
m, n := len(version1), len(version2)
for i, j := 0, 0; i < m || j < n; i, j = i+1, j+1 {
var a, b int
for i < m && version1[i] != '.' {
a = a*10 + int(version1[i]-'0')
i++
}
for j < n && version2[j] != '.' {
b = b*10 + int(version2[j]-'0')
j++
}
if a < b {
return -1
}
if a > b {
return 1
}
}
return 0
}
# Accepted solution for LeetCode #165: Compare Version Numbers
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
m, n = len(version1), len(version2)
i = j = 0
while i < m or j < n:
a = b = 0
while i < m and version1[i] != '.':
a = a * 10 + int(version1[i])
i += 1
while j < n and version2[j] != '.':
b = b * 10 + int(version2[j])
j += 1
if a != b:
return -1 if a < b else 1
i, j = i + 1, j + 1
return 0
// Accepted solution for LeetCode #165: Compare Version Numbers
impl Solution {
pub fn compare_version(version1: String, version2: String) -> i32 {
let (bytes1, bytes2) = (version1.as_bytes(), version2.as_bytes());
let (m, n) = (bytes1.len(), bytes2.len());
let (mut i, mut j) = (0, 0);
while i < m || j < n {
let mut a = 0;
let mut b = 0;
while i < m && bytes1[i] != b'.' {
a = a * 10 + (bytes1[i] - b'0') as i32;
i += 1;
}
while j < n && bytes2[j] != b'.' {
b = b * 10 + (bytes2[j] - b'0') as i32;
j += 1;
}
if a != b {
return if a < b { -1 } else { 1 };
}
i += 1;
j += 1;
}
0
}
}
// Accepted solution for LeetCode #165: Compare Version Numbers
function compareVersion(version1: string, version2: string): number {
const [m, n] = [version1.length, version2.length];
let [i, j] = [0, 0];
while (i < m || j < n) {
let [a, b] = [0, 0];
while (i < m && version1[i] !== '.') {
a = a * 10 + +version1[i];
i++;
}
while (j < n && version2[j] !== '.') {
b = b * 10 + +version2[j];
j++;
}
if (a !== b) {
return a < b ? -1 : 1;
}
i++;
j++;
}
return 0;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(\max(m, n)
Space
O(1)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.