The Roman Converter
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Given a Roman numeral string using symbols I=1, V=5, X=10, L=50, C=100, D=500, M=1000, return its integer value. When a smaller symbol precedes a larger one (IV, IX, XL, XC, CD, CM), subtract it from the larger one.
Roman numerals decoded.
Example
Input:
s = "MCMXCIV"
Output:
1994
Worked solution and explanation
Why this problem exists in real interviews
This tests pattern recognition with lookup tables and the subtraction rule in Roman numerals. It checks whether candidates can handle the exception case (IV, IX, XL, etc.) elegantly within a left-to-right scan.
Break down the requirements
Step 1: Build a symbol-to-value mapping
Map each Roman numeral character to its integer value: I=1, V=5, X=10, L=50, C=100, D=500, M=1000.
Step 2: Scan left to right
For each character, look up its value and add it to the total.
Step 3: Handle the subtraction rule
If the current value is less than the next value, subtract it instead of adding. This handles cases like IV (4) and IX (9).
The solution
def roman_to_int(s):
values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
for i in range(len(s)):
current = values[s[i]]
if i + 1 < len(s) and current < values[s[i + 1]]:
total -= current
else:
total += current
return totalCommon follow-up questions
- How would you convert an integer back to a Roman numeral? (Tests the reverse mapping with greedy subtraction of the largest possible values.)
- What if the input contained invalid characters? (Tests input validation before processing.)
- What if Roman numerals used a different notation for subtraction? (Tests parameterizing the subtraction rule.)