Magicsheet logo

Compare Version Numbers

Medium
48.5%
Updated 6/1/2025

Compare Version Numbers

What is this problem about?

The Compare Version Numbers interview question asks you to compare two version strings (like "1.01" and "1.001"). Versions are divided into "revisions" by dots. You should compare revisions from left to right. A revision's value is its integer interpretation, meaning leading zeros are ignored ("01" equals "1"). If one version has more revisions than the other, the missing revisions are treated as 0.

Why is this asked in interviews?

Apple and Amazon ask the Compare Version Numbers coding problem to test your string parsing and "clean code" skills. It’s a simulation problem that requires careful handling of edge cases, such as different lengths and large numbers of dots. It evaluates if you can handle input without over-complicating the logic with complex regex.

Algorithmic pattern used

The most effective String interview pattern here is Splitting and Two Pointers.

  1. Split both strings by the . character into lists of strings.
  2. Iterate through both lists simultaneously using a single loop that runs up to the length of the longer list.
  3. In each iteration, get the integer value of the revision. If the index is out of bounds for a list, use 0.
  4. Compare the integers. If v1 > v2 return 1, if v1 < v2 return -1.
  5. If the loop finishes without returning, return 0.

Example explanation

v1: "1.0.1", v2: "1"

  1. Split: v1 = ["1", "0", "1"], v2 = ["1"].
  2. Iteration 1: Compare 1 and 1. Equal.
  3. Iteration 2: v1 is 0, v2 is out of bounds (use 0). Equal.
  4. Iteration 3: v1 is 1, v2 is out of bounds (use 0). 1 > 0. Return 1.

Common mistakes candidates make

  • Dot splitting issues: Forgetting that . is a special character in many regex/split functions and needs to be escaped.
  • Leading Zeros: Trying to handle leading zeros with string comparison instead of converting the string to an integer.
  • Different Lengths: Not handling the case where "1.0" should equal "1.0.0".

Interview preparation tip

The "convert to integer" approach automatically handles leading zeros and empty strings (if you use a default of 0). This makes the code much cleaner than manually stripping zeros.

Similar Questions