LeetCode #12 Medium

Integer to Roman

Integer to Roman is LeetCode 12 (Medium). Given an integer num from 1 to 3999, return it written in Roman numerals.

  • The seven symbols are I 1, V 5, X 10, L 50, C 100, D 500 and M 1000.
  • Symbols are written from largest to smallest and their values are added.
  • Six values use subtraction instead: IV 4, IX 9, XL 40, XC 90, CD 400 and CM 900.
  • I, X, C and M can repeat at most three times in a row; V, L and D never repeat.

Because num stops at 3999, M is the largest symbol you ever need.

Constraints
  • 1 <= num <= 3999
stringmathgreedy
Open on LeetCode ↗
02

Intuition

The six subtractive forms are the only awkward part, so treat them as symbols of their own. Add them to the seven real symbols and you get a table of 13 values: 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1.

Now walk that table from largest to smallest and take each value as many times as it still fits, subtracting it every time. Nothing checks for a 4 or a 9. When 94 is left, 90 is tried before 50, so XC is written and LXXXX never appears.

This is the same move as giving change with the biggest coin first, and here it always produces the one correct numeral.

How to spot this pattern

Writing an amount using a fixed set of denominations, biggest first, is a greedy walk over a sorted table. Converting an integer to Roman numerals, giving change, and formatting a duration as hours, minutes and seconds all have that shape.

03

Approach

Try it first

Before reading on, write 4, 9, 40, 90, 400 and 900 in Roman numerals and look at what they have in common. Then think of a way to produce them without writing an if for each one.

1

Build the value table

List the 13 value and symbol pairs from 1000 down to 1, with each subtractive pair sitting just above the symbol it replaces: 900 before 500, 4 before 5. The loop takes the first value that fits, so this order decides which form gets written.

2

Take each value while it fits

For each pair, while num is at least the value, append the symbol and subtract the value. A value can fit up to three times, which is how 3000 becomes MMM.

3

Move to the next smaller value

Once num drops below the value, step to the next pair. Every later pair is smaller, so a symbol is never needed again after you pass it, and the numeral comes out in largest-to-smallest order.

4

Join the pieces

After the last pair, num is 0, because the final value is 1 and it fits any positive remainder. Join the collected symbols into one string and return it.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def intToRoman(self, num: int) -> str:
▶3 table = [
▶4 (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
▶5 (100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
▶6 (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"),
▶7 ]
▶8 result = []
▶9 for value, symbol in table:
▶10 while num >= value:
▶11 num -= value
▶12 result.append(symbol)
▶13 return "".join(result)
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num58resultstart with 58 and an empty result
num58left to write
result""
The table holds the seven symbols plus the six subtractive pairs, sorted from 1000 down to 1. The loop walks it left to right and takes each card as many times as it fits.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num58<1000result58 < 1000 → move past M
value1000M
num58
58 is smaller than 1000, so M does not fit. Every card after it is smaller, so M can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num58<900result58 < 900 → move past CM
value900CM
num58
58 is smaller than 900, so CM does not fit. Every card after it is smaller, so CM can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num58<500result58 < 500 → move past D
value500D
num58
58 is smaller than 500, so D does not fit. Every card after it is smaller, so D can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num58<400result58 < 400 → move past CD
value400CD
num58
58 is smaller than 400, so CD does not fit. Every card after it is smaller, so CD can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num58<100result58 < 100 → move past C
value100C
num58
58 is smaller than 100, so C does not fit. Every card after it is smaller, so C can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num58<90result58 < 90 → move past XC
value90XC
num58
58 is smaller than 90, so XC does not fit. Every card after it is smaller, so XC can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num58−50=8resultLL fits → write it, 8 left
value50L
num8
result"L"
58 is at least 50, so write L and subtract: 8 is left.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num8<50resultL8 < 50 → move past L
value50L
num8
8 is smaller than 50, so L does not fit. Every card after it is smaller, so L can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num8<40resultL8 < 40 → move past XL
value40XL
num8
8 is smaller than 40, so XL does not fit. Every card after it is smaller, so XL can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num8<10resultL8 < 10 → move past X
value10X
num8
8 is smaller than 10, so X does not fit. Every card after it is smaller, so X can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num8<9resultL8 < 9 → move past IX
value9IX
num8
8 is smaller than 9, so IX does not fit. Every card after it is smaller, so IX can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num8−5=3resultLVV fits → write it, 3 left
value5V
num3
result"LV"
8 is at least 5, so write V and subtract: 3 is left.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num3<5resultLV3 < 5 → move past V
value5V
num3
3 is smaller than 5, so V does not fit. Every card after it is smaller, so V can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num3<4resultLV3 < 4 → move past IV
value4IV
num3
3 is smaller than 4, so IV does not fit. Every card after it is smaller, so IV can never be needed again and the numeral stays largest to smallest.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num3−1=2resultLVII fits → write it, 2 left
value1I
num2
result"LVI"
3 is at least 1, so write I and subtract: 2 is left. 2 is still at least 1, so the same card is tried again.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num2−1=1resultLVIII fits → write it, 1 left
value1I
num1
result"LVII"
2 is at least 1, so write I and subtract: 1 is left. 1 is still at least 1, so the same card is tried again.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num1−1=0resultLVIIII fits → write it, 0 left
value1I
num0
result"LVIII"
1 is at least 1, so write I and subtract: 0 is left.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num0<1resultLVIII0 < 1 → move past I
value1I
num0
0 is smaller than 1, so I does not fit. Nothing is left to write; the loop still checks the remaining cards, and none of them fit.
tableM1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1num0resultLVIIItable used up → return LVIII
num0
result"LVIII"
The last card is 1, which fits any positive number, so num always ends at 0. Joining the pieces gives LVIII.
05

Lookup by decimal digit

Each decimal digit converts on its own, so precompute the Roman form of every digit for each place. num // 100 % 10 picks out the hundreds digit, and the matching string is read straight from the hundreds list. Index 0 holds an empty string, which is how a zero digit writes nothing.

▶1class Solution:
▶2 def intToRoman(self, num: int) -> str:
▶3 thousands = ["", "M", "MM", "MMM"]
▶4 hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
▶5 tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
▶6 ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
▶7 return (
▶8 thousands[num // 1000]
▶9 + hundreds[num // 100 % 10]
▶10 + tens[num // 10 % 10]
▶11 + ones[num % 10]
▶12 )
06

Common pitfalls

Leaving the subtractive pairs out of the table

✗ Wrong
table = [(1000, "M"), (500, "D"), (100, "C"), (50, "L"),
         (10, "X"), (5, "V"), (1, "I")]
✓ Right
table = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), ...]

With only the seven symbols, 4 comes out as "IIII" and 9 as "VIIII". The values add up, but the answer is wrong, and patching it with if checks for each digit is where most bugs creep in.

Using if instead of while

✗ Wrong
if num >= value:
    num -= value
    result.append(symbol)
✓ Right
while num >= value:
    num -= value
    result.append(symbol)

An if takes each value at most once, so 3 returns "I" and 2000 returns "M". Any digit made of repeated symbols needs the loop.

Putting a subtractive pair after the symbol it replaces

✗ Wrong
table = [(1000, "M"), (500, "D"), (900, "CM"), ...]
✓ Right
table = [(1000, "M"), (900, "CM"), (500, "D"), ...]

For 900, D is tried first and fits, leaving 400, so the answer is "DCD". The table must be sorted strictly by value.

07

Edge cases

A zero digit, as in 2005 or 3090

Roman numerals have no zero. Every value for that place is too big for what is left, so the loop writes nothing for it: 2005 is MMV.

The largest input, 3999

It needs MMM plus three subtractive pairs: MMMCMXCIX. No symbol above M exists in the table, and none is needed below 4000.

08

Complexity

Time
O(1)
Space
O(1)
The table always has 13 entries, and no answer is longer than 15 symbols (3888 is MMMDCCCLXXXVIII). The work never grows past that, whatever num is.
09

Integer to Roman FAQ

Why is 999 not written as IM?

Subtraction only reaches one or two steps up: I goes before V or X, X before L or C, and C before D or M. So 999 is 900 + 90 + 9, which is CMXCIX. The table follows this rule for free, since it has no entry for 999.

Why does greedy work here when it fails for some coin change problems?

With coins 1, 3 and 4, greedy pays 6 as 4 + 1 + 1 instead of 3 + 3. Roman numerals avoid that trap because each decimal place is written on its own. Within a place the table holds 9, 5, 4 and 1 times that place, and taking the biggest that fits builds every digit exactly as the standard form does: 8 is 5 + 1 + 1 + 1, 9 is 9. A place never adds up to more than the next place's smallest value, so greedy never borrows across places.