Integer to Roman
Problem
Given an integer num, convert it to a Roman numeral string representing the same value.
- 1 ≤ num ≤ 3999
Example
num = 1994"MCMXCIV"The algorithm decomposes 1994 by greedily subtracting the largest Roman numeral values possible. It starts with 1000 (M), subtracts it once leaving 994. Then it subtracts 900 (CM), leaving 94. Next, it subtracts 90 (XC), leaving 4. Finally, it subtracts 4 (IV). Concatenating these symbols in order yields "MCMXCIV".
Approach
Straightforward Solution
One might attempt to build the numeral by checking each symbol and subtracting it once if possible, but this would require complex conditional logic and multiple passes, making the code verbose and error-prone.
Core Observation
Roman numerals are constructed by concatenating symbols from largest to smallest values, using subtractive pairs for specific numbers. This structure allows a greedy approach where the largest possible symbol is repeatedly used until the number is reduced to zero.
Path to Optimal
The key insight is to predefine a list of Roman numeral symbols paired with their integer values, ordered from largest to smallest, including subtractive pairs. Then, iterate through this list, greedily subtracting the symbol's value as many times as it fits into the remaining number. This approach simplifies the logic and ensures correctness by construction.
Optimal Approach
Use a predefined ordered list of (value, symbol) pairs representing all Roman numeral building blocks, including subtractive forms. For each pair, compute how many times the value fits into the current number, append the corresponding symbol that many times, and reduce the number accordingly. Concatenate all appended symbols to form the final Roman numeral string.
Time
O(1)
The algorithm iterates over a fixed list of 13 Roman numeral pairs regardless of input size, performing a constant number of operations.
Space
O(1)
The output string length is bounded by the maximum Roman numeral length for 3999, and the auxiliary space for the symbol list is fixed and independent of input.
Pattern Spotlight
Greedy Algorithms (Greedy Decomposition)
When converting numbers to a representation with hierarchical symbols, a greedy approach that repeatedly subtracts the largest valid symbol ensures correctness and simplicity, as Roman numerals are designed to be constructed from largest to smallest symbols.
Solution
| 1 | class Solution: |
| 2 | def intToRoman(self, num: int) -> str: |
| 3 | roman_pairs = [ |
| 4 | (1000, "M"), |
| 5 | (900, "CM"), |
| 6 | (500, "D"), |
| 7 | (400, "CD"), |
| 8 | (100, "C"), |
| 9 | (90, "XC"), |
| 10 | (50, "L"), |
| 11 | (40, "XL"), |
| 12 | (10, "X"), |
| 13 | (9, "IX"), |
| 14 | (5, "V"), |
| 15 | (4, "IV"), |
| 16 | (1, "I"), |
| 17 | ] |
| 18 | |
| 19 | roman_parts = [] |
| 20 | |
| 21 | for value, symbol in roman_pairs: |
| 22 | count = num // value |
| 23 | |
| 24 | if count > 0: |
| 25 | roman_parts.append(symbol * count) |
| 26 | num -= value * count |
| 27 | |
| 28 | return "".join(roman_parts) |
Step-by-Step Solution
Define Ordered Roman Numeral Symbol-Value Pairs Including Subtractive Notation
| 3 | roman_pairs = [ |
| 4 | (1000, "M"), |
| 5 | (900, "CM"), |
| 6 | (500, "D"), |
| 7 | (400, "CD"), |
| 8 | (100, "C"), |
| 9 | (90, "XC"), |
| 10 | (50, "L"), |
| 11 | (40, "XL"), |
| 12 | (10, "X"), |
| 13 | (9, "IX"), |
| 14 | (5, "V"), |
| 15 | (4, "IV"), |
| 16 | (1, "I"), |
| 17 | ] |
Objective
To establish a fixed ordered list of Roman numeral symbols paired with their integer values, including subtractive pairs, to enable greedy decomposition.
Key Insight
Roman numerals use specific subtractive pairs (e.g., 900 as CM, 4 as IV) that must be handled explicitly to produce valid numerals. By including these pairs in descending order alongside standard symbols, the algorithm can uniformly apply a greedy subtraction without special cases.
Interview Quick-Check
Core Logic
The ordered list includes both standard and subtractive Roman numeral pairs, enabling a single pass greedy approach.
Common Pitfalls & Bugs
Omitting subtractive pairs leads to invalid or non-minimal Roman numerals.
Accumulate Roman Numeral Symbols by Greedy Division and Subtraction
| 19 | roman_parts = [] |
| 21 | for value, symbol in roman_pairs: |
| 22 | count = num // value |
| 24 | if count > 0: |
| 25 | roman_parts.append(symbol * count) |
| 26 | num -= value * count |
Objective
To iteratively build the Roman numeral string by subtracting the largest possible symbol values from the number and appending corresponding symbols.
Key Insight
Dividing the number by each symbol's value yields how many times that symbol fits into the number. Appending the symbol that many times and reducing the number accordingly ensures the numeral is constructed from largest to smallest parts, preserving correctness and minimal length.
Interview Quick-Check
Core Logic
For each symbol, compute how many times it fits into the current number, append that many symbols, and reduce the number accordingly.
State & Boundaries
The loop terminates when all symbols are processed, ensuring the entire number is converted.
Common Pitfalls & Bugs
Failing to update the number after appending symbols leads to infinite loops or incorrect output.
Return the Concatenated Roman Numeral String
| 28 | return "".join(roman_parts) |
Objective
To produce the final Roman numeral string by joining all accumulated symbol parts.
Key Insight
Joining the list of symbol strings into a single string produces the correct Roman numeral representation without additional formatting or separators.
Interview Quick-Check
Core Logic
Joining the list of symbols into a string returns the final Roman numeral.
Line Analysis
This solution has 8 Critical lines interviewers watch for.
(900, "CM"),
Add the subtractive pair (900, 'CM') to the list.
Including subtractive pairs like 900 (CM) is essential to produce valid Roman numerals and avoid invalid repetitions.
(400, "CD"),
Add the subtractive pair (400, 'CD') to the list.
Subtractive notation for 400 ensures minimal and valid Roman numeral representation.
(90, "XC"),
Add the subtractive pair (90, 'XC') to the list.
Subtractive notation for 90 is required for valid numeral formation.
(40, "XL"),
Add the subtractive pair (40, 'XL') to the list.
Subtractive notation for 40 ensures minimal representation.
(9, "IX"),
Add the subtractive pair (9, 'IX') to the list.
Subtractive notation for 9 is essential for valid Roman numerals.
(4, "IV"),
Add the subtractive pair (4, 'IV') to the list.
Subtractive notation for 4 ensures minimal and valid representation.
roman_parts.append(symbol * count)
Append the current symbol repeated count times to the parts list.
Appending the symbol count times accumulates the correct Roman numeral representation for this value segment.
num -= value * count
Reduce num by the total value accounted for by appended symbols.
Updating num ensures the algorithm progresses towards termination by removing the processed portion.
roman_pairs = [
Define the list of Roman numeral value-symbol pairs in descending order.
This ordered list includes all standard and subtractive Roman numeral pairs, enabling a uniform greedy approach without special case logic.
for value, symbol in roman_pairs:
Iterate over each (value, symbol) pair in descending order.
Processing pairs from largest to smallest ensures the greedy approach correctly builds the numeral from highest to lowest values.
count = num // value
Calculate how many times the current value fits into num.
Integer division determines the count of the current symbol needed to represent part of the number.
(1000, "M"),
Add the pair (1000, 'M') to the list.
The largest Roman numeral symbol, representing 1000, must be first to ensure greedy subtraction starts from the highest value.
(1, "I"),
Add the pair (1, 'I') to the list.
Smallest Roman numeral symbol, used to complete the decomposition.
return "".join(roman_parts)
Join all accumulated Roman numeral parts into a single string and return it.
Concatenating the parts produces the final Roman numeral string representing the original number.
(500, "D"),
Add the pair (500, 'D') to the list.
Standard Roman numeral symbol for 500, necessary for correct decomposition.
(100, "C"),
Add the pair (100, 'C') to the list.
Standard symbol for 100, part of the decomposition hierarchy.
(50, "L"),
Add the pair (50, 'L') to the list.
Standard symbol for 50, necessary for decomposition.
(10, "X"),
Add the pair (10, 'X') to the list.
Standard symbol for 10, part of the decomposition.
(5, "V"),
Add the pair (5, 'V') to the list.
Standard symbol for 5, necessary for decomposition.
if count > 0:
Check if the current symbol fits at least once.
Appending symbols only when count > 0 avoids unnecessary operations and ensures correctness.
roman_parts = []
Initialize an empty list to accumulate Roman numeral parts.
This list collects symbols as the number is decomposed, enabling efficient concatenation at the end.
]
Close the list of Roman numeral pairs.
Completes the definition of the ordered symbol-value pairs for the algorithm.
Test Your Understanding
Why does greedily subtracting the largest Roman numeral values first guarantee a correct Roman numeral representation?
Because Roman numerals are constructed by concatenating symbols from largest to smallest values, and the subtractive notation is explicitly included in the predefined symbol list, greedily subtracting the largest values ensures the numeral is both valid and minimal.
Related Problems
Greedy pattern
Don't just read it. Drill it.
Reconstruct Integer to Roman from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Integer to Roman drill