27. Compare Version Numbers
27. Compare Version Numbers
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:
1ifversion1is greater thanversion2-1ifversion1is less thanversion20if 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 stringversion2: a version string
Output Format
- An integer:
1,-1, or0
Examples
Example 1:
version1 = "1.01"
version2 = "1.001"0Example 2:
version1 = "1.0"
version2 = "1.0.0"0Example 3:
version1 = "0.1"
version2 = "1.1"-1Example 4:
version1 = "1.0.1"
version2 = "1"1Constraints
1 <= version1.length, version2.length <= 500version1 and version2 contain only digits and dotsRevisions fit within 32-bit signed integer rangeNo 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