Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Compare dotted version strings numerically part by part (missing parts count as 0); return 1, 0 or −1.

Problem: Compare dotted version strings numerically part by part (missing parts count as 0); return 1, 0 or −1.
def cmp_ver(a, b):
    x = list(map(int, a.split("."))); y = list(map(int, b.split(".")))
    n = max(len(x), len(y)); x += [0] * (n - len(x)); y += [0] * (n - len(y))
    return (x > y) - (x < y)
print(cmp_ver("1.10", "1.9"), cmp_ver("2.0.0", "2"), cmp_ver("3.01.2", "3.1.10"))
What is printed?
  1. A. 1 0 -1
  2. B. -1 0 -1
  3. C. 1 1 -1
  4. D. 1 0 1

Correct answer: A. 1 0 -1

Parts are integers, so 10 > 9 (string comparison would say "10" < "9") and "01" equals 1. Padding makes "2" equal to "2.0.0". Then [3, 1, 2] < [3, 1, 10] by list comparison → −1. O(n).

More Coding Interview Problems questions

Exams that ask this topic