Drill

ProblemsGo › validation

Compare two version strings

hardvalidationParsingStringsArraysGo

A deploy tool decides whether the version on the server is behind the one being released.

compareVersions(first: string, second: string) → int

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func compareVersions(first string, second string) int {
	
}

Worked examples

CallResult
compareVersions("1.2.10", "1.10.2")-1
compareVersions("1.2", "1.2.0")0
compareVersions("2.0", "1.9.9")1
compareVersions("1.0.0", "1.0.0")0

Hint

Walk both to the length of the longer one, reading a missing part as zero.

Reference solution in Go
func compareVersions(first string, second string) int {
	a := strings.Split(first, ".")
	b := strings.Split(second, ".")
	n := len(a)
	if len(b) > n {
		n = len(b)
	}
	for i := 0; i < n; i++ {
		x, y := 0, 0
		if i < len(a) {
			x, _ = strconv.Atoi(a[i])
		}
		if i < len(b) {
			y, _ = strconv.Atoi(b[i])
		}
		if x != y {
			if x < y {
				return -1
			}
			return 1
		}
	}
	return 0
}

The same problem in another language

More validation problems in Go