15% off all plans & roadmaps Use code

See plans

Integer to Roman

Updated

TL;DR: Convert an integer from 1 to 3999 into a Roman numeral. Walk a table of 13 value-symbol pairs from largest to smallest and take each pair as many times as it fits.

Problem

Roman numerals use seven symbols: I, V, X, L, C, D and M.

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

A numeral adds symbol values together. For example, 2 is II, two ones added together. 12 is XII, which is X + II. The number 27 is XXVII, which is XX + V + II.

Numerals are usually written from largest to smallest, reading left to right. The number four is not IIII. It is IV, because the one comes before the five and is subtracted. Nine is written IX for the same reason. Subtraction appears in exactly six cases:

  • I can go before V (5) and X (10) to make 4 and 9.
  • X can go before L (50) and C (100) to make 40 and 90.
  • C can go before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a Roman numeral.

Example 1

Input: num = 3
Output: "III"

Example 2

Input: num = 4
Output: "IV"

Example 3

Input: num = 9
Output: "IX"

Example 4

Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

Example 5

Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints

  • 1 <= num <= 3999

Constraints that matter

  • num is at most 3999, so the longest numeral has 15 characters (for example 3888, which is MMMDCCCLXXXVIII). A table of fixed size and fixed-length work is enough.
  • num is at least 1, so there is no zero and no negative input. Roman numerals have no zero symbol, so you never need an empty numeral for a valid input.
  • Each decimal place of the number maps to one of ten patterns (0 to 9). That lets you index a small table per place instead of building letters from scratch.
  • Every subtractive pair has a fixed value. Including the six pairs in the table removes every special case from the loop.

View on LeetCode

Hints

Hint 1

The clue is the rule that numerals are written largest to smallest.

Hint 2

A beginner usually splits the number into thousands, hundreds, tens and ones, then writes a separate list of cases for each place.

Solution

Intuition

The clue is the rule that numerals are written largest to smallest. Each symbol value is a fixed chunk, and the numeral is the list of chunks that add up to the input. When you must split a number into fixed chunks with the biggest chunk first, the pattern is greedy: take the largest chunk that fits, subtract it, and repeat on the remainder.

It is like making change from a cash drawer. The 13 pairs are the denominations, the result is the list of coins you hand over, and num is the amount still owed.

Subtraction is the only tricky part. Instead of writing a rule for when a smaller symbol comes first, treat IV, IX, XL, XC, CD and CM as chunks with their own values. Then every chunk is a plain value, and the loop never needs a special case.

The greedy choice is safe here because the 13 pairs are exactly the pieces standard notation uses. Taking the largest pair that fits never leaves a remainder that needs a bigger piece. Each step therefore writes the next correct symbols, and the loop ends with a remainder of 0.

Watch the pattern animation

Worked example

Input: num = 3999
Output: "MMMCMXCIX"
Explanation:
The thousands place is 3, so it gives MMM. The hundreds place is 9, which gives CM. The tens place is 9, which gives XC.

The ones place is 9, which gives IX. Joined in order, the pieces form MMMCMXCIX.

Approach 1: Brute force: per-digit tables

A beginner usually splits the number into thousands, hundreds, tens and ones, then writes a separate list of cases for each place. Each list maps one digit to its letters, such as 4 to CD in the hundreds place. The code is correct, but it repeats the same mapping pattern four times, and the cases are easy to mistype.

This version does not walk the value table at all. It handles each place on its own, so the subtractive pairs live in four different lists. The approach still works because a decimal digit has only ten possible patterns at each place.

Steps

  1. Split num into four digits: thousands is num / 1000, hundreds is (num % 1000) / 100, tens is (num % 100) / 10, and ones is num % 10.
  2. Look up the thousands digit in a 4-entry list of "", M, MM, MMM.
  3. Look up the hundreds, tens and ones digits in their own 10-entry lists.
  4. Concatenate the four strings in order and return the result.

Dry run

Split 3999 into thousands = 3, hundreds = 9, tens = 9 and ones = 9.

  • thousands[3] is MMM.
  • hundreds[9] is CM.
  • tens[9] is XC.
  • ones[9] is IX.

Join them in order: MMM + CM + XC + IX gives MMMCMXCIX, which matches the expected output.

Complexity

TimeO(1) here, O(log n) in general
SpaceO(1) auxiliary

Let n be the value of num and d the number of decimal digits, which is at most 4 here. The code does one division or modulo and one list lookup per digit, then three string joins, so the work is proportional to d. Since d is about log10(n), the time is O(log n), which is constant for num up to 3999.

The four lists hold 34 short strings, and the output has at most 15 characters.

PythonTested in our runner

class Solution:
    def intToRoman(self, num: int) -> str:
        thousands = ['', 'M', 'MM', 'MMM']
        hundreds = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']
        tens = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']
        ones = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']
        return thousands[num // 1000] + hundreds[num % 1000 // 100] + tens[num % 100 // 10] + ones[num % 10]

The Integer and Roman Conversion infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Integer and Roman Conversion

Part of String Manipulation Patterns

Approach 2: Greedy over value-symbol pairsOptimalInteger and Roman Conversion

What's slow: the per-digit approach keeps four separate tables, and the six subtractive cases are spread across those tables. Each place must be indexed and joined by hand, so the code grows whenever the rules change.

The insight that fixes it: the whole numeral is one walk over 13 chunks in descending order. Take the largest chunk that fits, subtract it, and repeat. The per-place split disappears, and the subtractive pairs become ordinary entries in the table.

Why it is correct. After the loop finishes with a pair of value v, the remainder is less than v, so no later step needs that pair again. Every pair the loop skips is larger than the remainder at that moment, so it could never fit and skipping it loses nothing. Because the 13 values are exactly the pieces standard notation uses, a remainder below v is always writable with the smaller pairs, so greedy ends at exactly 0.

Steps

  1. Build 13 value-symbol pairs in descending order: 1000 M, 900 CM, 500 D, 400 CD, 100 C, 90 XC, 50 L, 40 XL, 10 X, 9 IX, 5 V, 4 IV, 1 I.
  2. Start with an empty result and the input num.
  3. For each pair in order, while num is at least the value, append the symbol and subtract the value from num.
  4. When the loop ends, num is 0. Return the result.

Dry run

The table below traces num = 3999. Each row is one pair in the table, read from top to bottom.

StepPair (value)num beforeActionnum afterresult
1M (1000)3999take 3 times999MMM
2CM (900)999take once99MMMCM
3D (500)99skip99MMMCM
4CD (400)99skip99MMMCM
5C (100)99skip99MMMCM
6XC (90)99take once9MMMCMXC
7L (50)9skip9MMMCMXC
8XL (40)9skip9MMMCMXC
9X (10)9skip9MMMCMXC
10IX (9)9take once0MMMCMXCIX
11V (5)0skip0MMMCMXCIX
12IV (4)0skip0MMMCMXCIX
13I (1)0skip0MMMCMXCIX

The loop ends with num = 0 and the result MMMCMXCIX.

Complexity

TimeO(1) here, O(log n) in general
SpaceO(1) auxiliary

Let n be the value of num. The outer loop always visits all 13 pairs, so it does 13 checks no matter the input. The inner while loop runs once for each symbol appended, and the output has at most 4 symbols per decimal place, so the total is at most 15 appends for num up to 3999.

That makes the work constant here, and O(log n) in general because the output length grows with the digit count. The extra space is the 13-entry table plus the result, which is the answer itself, so the auxiliary space is O(1).

PythonTested in our runner

class Solution:
    def intToRoman(self, num: int) -> str:
        # Descending order matters: subtractive pairs must sit before their larger neighbours
        value_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
                     (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
                     (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
        result = []
        for value, symbol in value_map:
            # Take this pair as many times as it fits
            while num >= value:
                result.append(symbol)
                num -= value
        return ''.join(result)

Common mistakes

  • Using if num >= value where the loop needs while num >= value. Each symbol is then taken at most once, so 3000 becomes only M. Wrap the append and subtract in a loop.
  • Listing (1, "I") before (4, "IV") in the table. The greedy takes I four times and produces IIII. Keep the table in strictly descending order of value.
  • Leaving out the six subtractive pairs. Without CM, 900 becomes DCCCC, and without IX, 9 becomes VIIII. Add all six pairs to the table.
  • Writing hundreds[num / 100] without the % 10. For 1994, num / 100 is 19, which is out of range for a 10-entry list. Take the digit with (num % 1000) / 100.
  • Storing the greedy table in an unordered container such as C++ unordered_map or Java HashMap. Their iteration order is not the descending order the loop needs. Use an ordered list of pairs instead.

Edge cases

  • num = 1 returns "I", the smallest valid input.
  • num = 4 returns "IV", not "IIII", so the subtractive pair must be in the table.
  • num = 40 returns "XL", which checks the tens subtractive pair on its own.
  • num = 3888 returns "MMMDCCCLXXXVIII", the longest output of 15 characters, with no subtraction.
  • num = 3999 returns "MMMCMXCIX", the largest valid input, where every place uses a subtractive pair except thousands.

Follow-ups interviewers ask

What if num could go above 3999?
Standard notation stops at 3999 because M is the largest symbol. Larger values need extra notation, such as an overline that multiplies a symbol by 1000. Add those pairs to the table in descending order, and the same greedy loop still works. The output then grows with the number of digits.
Can you do it in O(1) extra space?
Yes, the solution already uses O(1) extra space. The table has a fixed size, and the result string is the answer itself, so it is not extra memory. For num up to 3999 the output has at most 15 characters.
How would you convert a Roman numeral back to an integer?
Scan the string from left to right and add each symbol's value. If a symbol is smaller than the symbol after it, subtract its value instead. This covers IV, IX and the other four subtractive pairs, and it is LeetCode 13.

Integer to Roman FAQ

What is the time complexity of Integer to Roman?

For num up to 3999 the time is O(1), because the table has 13 entries and the output has at most 15 symbols. In general the time is O(log n), since the output has at most 4 symbols per decimal place. The per-digit version also runs in O(log n).

Why use a greedy approach for Integer to Roman?

The standard numeral is built by taking the largest chunk that fits, then repeating on the remainder. Each choice is final, so the loop never has to undo work. Because the table includes the subtractive pairs, no lookahead is needed.

Can Integer to Roman be solved in O(1) extra space?

Yes. The table size is fixed, and the result string is the answer itself. The extra memory does not depend on num, and the output is at most 15 characters for num up to 3999.

Why does 4 become IV and not IIII?

Standard Roman notation writes 4, 9, 40, 90, 400 and 900 with subtraction. The form IIII is not used in the standard system. A table that includes the pair IV produces the correct form directly.

Why does the table order matter in Python, Java and C++?

The greedy loop must visit values from largest to smallest. A Python list keeps its order, but C++ unordered_map and Java HashMap do not guarantee any order. Store the pairs in an ordered list in every language.

Asked at

See which companies ask this — Pro

Practise it