Solution for interview question: Roman to Integer

1. Understanding the Problem

  • You are given a Roman numeral, and you need to convert it to an integer.
  • Roman numerals are made up of symbols (I, V, X, L, C, D, M) with respective values.
  • The numeral can range from 1 to 3999, and subtraction cases (like IV for 4) must be handled.

2. List Roman Numerals and Values

  • Roman numerals are represented by seven different symbols with specific values:
Symbol    Value 
 I         1
 V         5
 X         10
 L         50
 C         100
 D         500
 M         1000
  • Subtraction cases include:
    • I before V (5) and X (10) to make 4 and 9.
    • X before L (50) and C (100) to make 40 and 90.
    • C before D (500) and M (1000) to make 400 and 900.

3. Create a Mapping for Roman Numerals

  • Use a dictionary to map Roman numeral symbols to their corresponding integer values.
  • This will allow for constant-time lookups during conversion.
def roman_to_integer(s: str) -> int:
    roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    return 0

4. Iterate Through the String

  • To process the Roman numeral, iterate through the string from left to right.
  • For each character, look up its corresponding value using the dictionary.
def roman_to_integer(s: str) -> int:
    roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    total = 0
    for char in s:
        value = roman_map[char]
    return total

5. Handle Subtraction Cases

  • Roman numerals use subtraction in specific cases (like IV = 4).
  • If a smaller value comes before a larger one, subtract the smaller value instead of adding it.
def roman_to_integer(s: str) -> int:
    roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    total = 0
    prev_value = 0
    for char in s:
        value = roman_map[char]
        if value > prev_value:
            total += value - 2 * prev_value  # Subtract twice the previous value
        else:
            total += value
        prev_value = value  # Update the previous value
    return total

6. Return the Final Sum

  • After processing all characters in the Roman numeral string, return the accumulated total value, which represents the integer conversion.
def roman_to_integer(s: str) -> int:
    roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    total = 0
    prev_value = 0
    for char in s:
        value = roman_map[char]
        if value > prev_value:
            total += value - 2 * prev_value
        else:
            total += value
        prev_value = value
    return total

7. Handle Edge Cases

  • Make sure that input Roman numerals are valid and within the range (1-3999).
  • Since the problem guarantees this, we don't need extra validation, but this could be added in a more general implementation.