Drill

ProblemsTypeScript › validation

Compare two version strings

hardvalidationTypeScript

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

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

Solve it in the editor →

Where you start

function compareVersions(first: string, second: string): number {
  
}

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 TypeScript
function compareVersions(first: string, second: string): number {
  const a = first.split('.');
  const b = second.split('.');
  const n = Math.max(a.length, b.length);
  for (let i = 0; i < n; i++) {
    const x = i < a.length ? parseInt(a[i], 10) : 0;
    const y = i < b.length ? parseInt(b[i], 10) : 0;
    if (x !== y) return x < y ? -1 : 1;
  }
  return 0;
}

The same problem in another language

More validation problems in TypeScript