Integer to Roman (LeetCode 12): Solution and Explanation

Medium
Hash Table
Math
String
Greedy

Convert an integer between 1 and 3999 into a Roman numeral. Symbols run from largest to smallest and add up, except for the six subtractive pairs IV, IX, XL, XC, CD and CM that stand for 4, 9, 40, 90, 400 and 900.

Intuition

The rules sound fiddly because of the subtractive pairs. A 4 is not IIII but IV, a 90 is not LXXXX but XC, and so on. If you try to handle those as exceptions digit by digit, the code fills up with branches.

The trick is to stop treating the pairs as exceptions. Put them in the table next to the seven plain symbols, giving 13 denominations: 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4 and 1. Now writing a numeral is exactly like paying an amount with coins.

With these denominations, taking the largest coin that still fits always produces the standard numeral. For 1994 the largest block that fits is M (1000), then 994 takes CM (900), 94 takes XC (90) and 4 takes IV. The greedy choice never has to look ahead, because each decimal place is consumed by its own blocks before the next smaller place begins.

Approach: Greedy over 13 denominations

  1. Store the values [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] and their symbols M, CM, D, CD, C, XC, L, XL, X, IX, V, IV, I in matching order.
  2. Walk the denominations from largest to smallest.
  3. While num is at least the current value, append its symbol to the result and subtract the value from num.
  4. When the loop finishes, num is 0 and the joined symbols form the answer.

Step-by-step example

num = 3749
  1. M = 1000 fits three times: append MMM, and num drops 3749 to 2749 to 1749 to 749.
  2. CM = 900 does not fit into 749, so skip it.
  3. D = 500 fits once: append D, num = 249. CD = 400 does not fit.
  4. C = 100 fits twice: append CC, num = 49. XC = 90 and L = 50 do not fit.
  5. XL = 40 fits once: append XL, num = 9. X = 10 does not fit.
  6. IX = 9 fits once: append IX, num = 0. The remaining denominations are skipped and the result is MMMDCCXLIX.

Code: Python, Java, C++

1class Solution:
2    def intToRoman(self, num: int) -> str:
3        values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
4        symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
5        result = []
6        for value, symbol in zip(values, symbols):
7            while num >= value:
8                result.append(symbol)
9                num -= value
10        return "".join(result)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1)

The input is capped at 3999, so the loop checks 13 denominations and appends at most 15 symbols (3888 = MMMDCCCLXXXVIII). The work does not grow with anything.

Space

O(1)

The two fixed tables and a result of at most 15 characters.

Other approaches

Digit lookup tables (time O(1), space O(1))

Precompute the numeral for every digit at every place: thousands ['', 'M', 'MM', 'MMM'], hundreds ['', 'C', 'CC', ..., 'CM'], tens and ones the same way. The answer is thousands[num // 1000] + hundreds[num % 1000 // 100] + tens[num % 100 // 10] + ones[num % 10]. It is branch-free and just as fast, at the cost of writing out 34 strings.

Per-digit rules (time O(1), space O(1))

Handle each decimal digit with explicit cases for 0-3, 4, 5-8 and 9 using the one, five and ten symbols of that place. It mirrors how people learn the numerals, but it is longer and easier to get wrong than the greedy table.

Common mistakes

  • Leaving the subtractive pairs out of the table. The greedy then writes 4 as IIII and 900 as DCCCC.
  • Listing the denominations in the wrong order, for example 500 before 900. 994 would then start with D instead of CM.
  • Using if instead of while for each denomination, which writes 3000 as a single M.
  • Building the result with repeated string concatenation in a language where that is costly. It does not matter at this size, but a builder is the habit to keep.

Frequently asked questions

Why is the greedy choice always correct here?

Each denomination from the table belongs to one decimal place, and within a place the blocks (for example 900, 500, 400, 100) can express every digit with the largest-first rule. Taking the largest block never leaves a remainder that needs a symbol from a bigger place, so no backtracking is ever needed.

Why does the input stop at 3999?

Standard Roman numerals have no symbol above M and M may only repeat three times, so 3999 (MMMCMXCIX) is the largest value they can write.

What is the longest output?

3888, which is MMMDCCCLXXXVIII with 15 symbols. Every place uses its longest form, a five-symbol plus three ones.

How is this different from Roman to Integer?

Roman to Integer reads symbols and subtracts a value when it is smaller than the next one. Integer to Roman goes the other way and avoids that comparison entirely by baking the subtractive pairs into the table.