DSA Factory
Free Strings lessonsStrings · Stage 4 · Parsing · Step 4

Compare piece by piece

Decide which of two version numbers like 1.10 and 1.9 is newer. About 10 minutes.

Text order isn't number order

Your phone says an update from version 1.9 to 1.10 is available. Is 1.10 newer? Compared as text, no: the character 1 comes before 9. Compared as numbers, 10 is bigger than 9, so yes.

So split each version at the dots and turn every part into a real number. A part like "010" is just the number 10: leading zeros don't matter.

Compare as text: and 1.10 looks older than 1.9.
Split at the dots: and compare numbers.
v1 = "1.2", v2 = "1.10"
part 0part 1
v1
1
2
v2
1
10

As text, "1.2" looks bigger, because the character 2 beats 1. That's the trap. Split on the dots and compare numbers.

Move 1 of 3

The first difference decides

Compare the first parts, then the second parts, and so on. The first pair that differs decides which version is newer.

If one version runs out of parts, treat its missing parts as 0. So 1.0 and 1.0.0 are equal, and 2.5.10 is newer than 2.5.9 because the first two parts match and 10 beats 9.

Missing parts: count as 0.
In code
a = [int(p) for p in v1.split(".")]
b = [int(p) for p in v2.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
Quick check

Which is newer, 2.5.10 or 2.5.9?

  1. A2.5.10
  2. B2.5.9
  3. CThey're equal
Show the answer

2.5.10. The first two parts match; 10 > 9 decides.

Your problem

Compare versions

You get two version strings made of whole numbers separated by dots, like "1.10.2". Compare them part by part as numbers, treating missing parts as 0. Return 1 if the first is bigger, −1 if it is smaller, and 0 if they are equal.

Example
v1 = "1.2", v2 = "1.10" → -1

1 ≤ lengths ≤ 500 · every part fits in an int · parts may have leading zeros

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve