27. Compare Version Numbers

27. Compare Version Numbers

Medium
52.0%
1.4k
stringmathtwo-pointers
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

You’re interviewing for a backend or data engineering role at a FAANG-level company. The interviewer describes a real product scenario:

A large scale platform runs many microservices and mobile clients that communicate using versioned APIs. To safely roll out features and avoid breaking changes, the platform must compare semantic version strings coming from different services, for example:

  • checking whether a client is on an older build
  • enforcing minimum supported API versions
  • deciding whether to enable a feature flag
  • selecting the correct migration script

Versions are represented as dot-separated integers such as "1.0.7" or "2.15".

The system needs a reliable comparison function that follows standard version comparison rules.

This is a common practice coding problem for DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

Given two version strings version1 and version2, compare them.

Return:

  • 1 if version1 is greater than version2
  • -1 if version1 is less than version2
  • 0 if they are equal

Comparison rules:

  • Split each version by the dot . into revisions
  • Compare revisions from left to right
  • Missing revisions are treated as 0
  • Leading zeros in a revision do not affect its value

Input Format

  • version1: a version string
  • version2: a version string

Output Format

  • An integer: 1, -1, or 0

Examples

Example 1:

Input: version1 = "1.01" version2 = "1.001"
Output: 0
Explanation: Both revisions are numerically equal: 01 equals 1 and 001 equals 1.

Example 2:

Input: version1 = "1.0" version2 = "1.0.0"
Output: 0

Example 3:

Input: version1 = "0.1" version2 = "1.1"
Output: -1

Example 4:

Input: version1 = "1.0.1" version2 = "1"
Output: 1

Constraints

  • 1 <= version1.length, version2.length <= 500
  • version1 and version2 contain only digits and dots
  • Revisions fit within 32-bit signed integer range
  • No invalid version strings are provided

Loading editor...

"1.01", "1.001"
0

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback