Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Compare Version Strings
00:00
5 left

Compare Version Strings

MediumPython

Problem

Zalando services may receive version identifiers with different numbers of components or leading zeros. Implement a comparator that determines the numeric ordering of two dotted version strings.

Formal Specification

Write compare_versions(version1, version2), where both inputs are strings containing one or more nonnegative integer components separated by periods. Compare components from left to right. A missing component is treated as numeric zero, so "1.2" equals "1.2.0". Leading zeros do not affect a component's value.

Return:

  • -1 if version1 is numerically smaller
  • 0 if both versions are numerically equal
  • 1 if version1 is numerically greater

Do not compare the complete strings lexicographically. Components may be too long for fixed-width integer types, so compare normalized components by length and then lexicographically.

Examples

Example 1

Input: version1 = "1.02", version2 = "1.05"
Output: -1

The first components are equal, and 02 is numerically smaller than 05.

Example 2

Input: version1 = "7.5.7.4", version2 = "7.5.3"
Output: 1

The first differing component is 7 versus 3, so the first version is greater.

Example 3

Input: version1 = "1.0.1", version2 = "1.001"
Output: -1

The second components are 0 and 1, so the first version is smaller.

Constraints

  • 1 <= len(version1), len(version2) <= 10^4
  • Each version contains at most 10^3 components
  • Each component contains at least one digit
  • Components contain only digits from 0 to 9
  • Inputs contain no leading or trailing periods

Constraints

  • 1 <= len(version1), len(version2) <= 10^4
  • Each version contains at most 10^3 components
  • Each component contains at least one digit
  • Components contain only digits from 0 to 9
  • Inputs contain no leading or trailing periods

Function Signature

def compare_versions(version1, version2):
Interviewer

Your question is Compare Version Strings. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.