Integer to Roman
LeetCode 12 · Medium · solution, intuition & step-by-step walkthrough
Greedy over values including subtractive pairs.
This is how I solved Integer to Roman (LeetCode 12), a medium problem from the Sorting + Simple Greedy pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Roman numerals are greedy: always write the largest symbol that still fits. Including the six subtractive pairs (CM, CD, XC, XL, IX, IV) in the table makes the greedy rule produce the correct form.
Approach
- 1
Table of 13 values from 1000 down to 1.
- 2
While num > 0, append each symbol as many times as it fits.
- 3
Subtract its value each time.
How I solved it
Greedy tablePythonO(1) time
class Solution:
def intToRoman(self, num: int) -> str:
nums = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
symbols = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
ans = ""
while num>0:
for index,cur_num in enumerate(nums):
while cur_num<=num:
ans+=symbols[index]
num=num-cur_num
if cur_num>num:
break;
return ans
Integer to Roman — FAQ
What is the intuition behind Integer to Roman?
Roman numerals are greedy: always write the largest symbol that still fits. Including the six subtractive pairs (CM, CD, XC, XL, IX, IV) in the table makes the greedy rule produce the correct form.
How do you solve Integer to Roman (LeetCode 12)?
1. Table of 13 values from 1000 down to 1. 2. While num > 0, append each symbol as many times as it fits. 3. Subtract its value each time.
What is the time and space complexity of Integer to Roman?
Time: O(1). Space: O(1). (Accepted approach: Greedy table.)
What are common mistakes in Integer to Roman?
Without CM, XC, IV, etc. you'd produce 'VIIII'.