algoadvance

Clarifying Questions

  1. Input Constraints:
    • What is the range of the input Roman numerals? Typically, Roman numeral values range from 1 to 3999.
  2. Input Format:
    • Can we assume the input is always a valid Roman numeral string containing characters like ‘I’, ‘V’, ‘X’, ‘L’, ‘C’, ‘D’, ‘M’?

Assuming the input is within these constraints, we can proceed to the next steps.

Strategy

  1. Mapping Roman Numerals to Integers:
    • Create a dictionary to map single Roman numeral characters to their respective integer values.
  2. Iterate through the String:
    • Traverse the string and for each character, check its value.
    • Normally add its value to the result. However, there is a special case:
      • If a smaller or equal value numeral comes before a larger numeral (like IV for 4), you need to subtract the smaller value.
  3. Handling Subtractions:
    • Compare each numeral with the next one. If the current numeral is smaller than the next numeral, subtract its value from the result; otherwise, add it.

Code

def romanToInt(s: str) -> int:
    # Mapping of Roman numerals to their integer values.
    roman_to_int = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }
    
    total = 0
    prev_value = 0
    
    # Process each character in the Roman numeral string from right to left
    for char in reversed(s):
        current_value = roman_to_int[char]

        # If the current value is at least the previous value, add it
        if current_value >= prev_value:
            total += current_value
        else:
            # If the current value is less than the previous value, subtract it
            total -= current_value
        
        # Update the previous value
        prev_value = current_value
    
    return total

# Example usage:
print(romanToInt("III"))    # Output: 3
print(romanToInt("IV"))     # Output: 4
print(romanToInt("IX"))     # Output: 9
print(romanToInt("LVIII"))  # Output: 58
print(romanToInt("MCMXCIV"))# Output: 1994

Time Complexity

Is there any specific part of the problem you would like to delve into further, or any clarification needed on the strategy or code?

Try our interview co-pilot at AlgoAdvance.com