Skip to content
Problem 12 · LeetCode 12(opens in a new tab)

Integer to Roman

MediumGreedy

Roman numerals are built from seven letters. From largest to smallest: M is 1000, D is 500, C is 100, L is 50, X is 10, V is 5 and I is 1. A number is written from its largest place to its smallest, and each place is spelled with these letters.

A digit of 4 or 9 in any place uses a two-letter pair where a smaller letter comes before a bigger one: IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900. Those six pairs are the only ones allowed. I, X, C and M may repeat up to three times in a row; V, L and D never repeat.

Given an integer num, return its Roman numeral as a string.

Example 1

Input:  num = 2024
Output: "MMXXIV"
Why:    2000 = MM, 20 = XX, 4 = IV
2 more examples and the constraints

Example 2

Input:  num = 49
Output: "XLIX"
Why:    40 = XL and 9 = IX; IL is not allowed

Example 3

Input:  num = 3888
Output: "MMMDCCCLXXXVIII"
Why:    no 4 or 9 digit, so every place is additive

Constraints

  • 1 ≤ num ≤ 3,999

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. One table per placeO(1)
  2. Greedy, largest symbol firstO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeSteps to convert 3,888Verdict
One table per placeO(1)
Passes; 33 strings to type
Greedy, largest symbol firstO(1)
Best; short and hard to get wrong

Both are constant time because num ≤ 3,999. The greedy loop takes a few more steps but has far less to memorize.

Edge cases to test

  • Smallest input. 1 is just "I".
  • Largest input. 3,999 is "MMMCMXCIX", with a subtractive pair in three places.
  • Zeros in the middle. 2024 has no hundreds; the answer must not hold a stray C or an empty marker.
  • Longest answer. 3,888 needs 15 letters: "MMMDCCCLXXXVIII".
  • A 4 or 9 digit. 49 is "XLIX", not "IL". Pairs only work inside one place.

Common mistakes

  • Leaving the six pairs out of the list, which gives "IIII" for 4 and "VIIII" for 9.
  • Putting the values out of order, for example 500 before 900, so 900 comes out as "DCCCC".
  • Writing 49 as "IL" or 99 as "IC". Only the six listed pairs exist.

How to talk through it

  1. 1Clarify. Confirm the range is 1 to 3,999 and that only the six listed subtractive pairs are allowed.
  2. 2Spot the coins. Say that Roman numerals are a set of denominations, spelled largest first.
  3. 3Fold in the pairs. Explain that adding 900, 400, 90, 40, 9 and 4 to the list removes every special case.
  4. 4Code the greedy loop. Two parallel lists, an outer loop over them, an inner while that subtracts.
  5. 5Test out loud. Run 49, 2024 and 3,999 and check each subtractive pair.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?