[
string
]
Leetcode 0165. Compare Version Numbers
https://leetcode.com/problems/compare-version-numbers
In python it is more like easy than medium problem, there is not a lot of cases we need to handle.
- First step is to split our strings using
.
and change type from string to int. - Now, if we have lists of different length, let us add zeros to the end of short list.
- Finally, we need to compare
s1
ands2
as lists. There is notcmp()
function in python3, but we can use(s1 > s2) - (s1 < s2)
trick: ifs1 > s2
then we have1-0 = 1
, ifs1 = s2
, then we have0-0 = 0
, if we haves1< s2
, then0-1 = -1
.
Complexity: time complexity is O(n+m)
, where n
and m
are lengths of our strings, space complexity O(n+m)
as well.
class Solution:
def compareVersion(self, version1, version2):
s1 = [int(i) for i in version1.split(".")]
s2 = [int(i) for i in version2.split(".")]
l1, l2 = len(s1), len(s2)
if l1 < l2: s1 += [0]*(l2-l1)
else: s2 += [0]*(l1 - l2)
return (s1 > s2) - (s1 < s2)
If you like the solution, you can upvote it on leetcode discussion section: Problem 0165