↓Skip to main content
  1. LeetCode/

LeetCode 165: Compare Version Numbers

·1 min· ·
LeetCode Medium Two-Pointers String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-19

  • Submissions: Accepted (first try)

Approach
#

Split on . and convert each revision to int (dropping leading zeros), then compare with one pointer per version (Two Pointers Template 2). Missing revisions of the shorter version count as 0, so 1.0 equals 1.

My Solution
#

class Solution:
    def compareVersion(self, version1: str, version2: str) -> int:
        a = list(map(int, version1.split(".")))
        b = list(map(int, version2.split(".")))
        for i in range(max(len(a), len(b))):
            x = a[i] if i < len(a) else 0
            y = b[i] if i < len(b) else 0
            if x != y:
                return 1 if x > y else -1
        return 0

Complexity
#

Time O(n + m), space O(n + m).

Mistakes to Avoid
#

  • Compare as integers: "01" equals "1".
  • Pad missing revisions with 0 instead of assuming the longer version is larger.

Interview Explanation
#

I split on dots, convert each revision to an integer, and compare them in order, treating missing revisions as 0; the first difference decides. Time O(n + m).

Related

LeetCode 151: Reverse Words in a String
·1 min
LeetCode Medium Two-Pointers String
LeetCode 151 note: split() with no argument treats runs of spaces as one separator and drops leading and trailing spaces; reverse and join with single spaces
LeetCode 647: Palindromic Substrings
·1 min
LeetCode Medium Two-Pointers String Dynamic-Programming
LeetCode 647 note: expand around centers, counting one palindromic substring for each successful expansion
LeetCode 5: Longest Palindromic Substring
·2 mins
LeetCode Medium Two-Pointers String Dynamic-Programming Manacher
LeetCode 5 note: expand around centers, using each position as an odd and an even center; with interval DP, iterate i from large to small
LeetCode 142: Linked List Cycle II
·2 mins
LeetCode Medium Hash-Table Linked-List Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 142 note: after fast and slow meet, send one back to head and step both one at a time; they meet again at the cycle entry
LeetCode 61: Rotate List
·1 min
LeetCode Medium Linked-List Two-Pointers
LeetCode 61 note: count the length and close a ring, take k %= n, walk n - k - 1 steps from the head to the new tail, and break there
LeetCode 942: DI String Match
·1 min
LeetCode Easy Array Two-Pointers String Greedy
LeetCode 942 note: two pointers hold the smallest and largest unused values; place the smallest on I and the largest on D