Skip to main content Link Search Menu Expand Document (external link)

Roman to Integer (Difficulty: Easy)

  • This is an easy question. However, the important takeaway is that slicing string s = s[2:] is much slower than index manipulating
    This is because left parts of string need to be taken down by garbage collection. Otherwise, it will cause memory leak.
class Solution:
    def romanToInt(self, s: str) -> int:
        symbol_value = {
            "I": 1, "IV": 4, "V": 5, "IX": 9,
            "X": 10, "XL": 40, "L": 50, "XC": 90,
            "C": 100, "CD": 400, "D": 500, "CM": 900,
            "M": 1000
        }
        
        num = 0
        i = 0
        while i < len(s):
            c2 = s[i:i+2]
            if c2 in symbol_value:
                num += symbol_value[c2]
                i += 2
                # s = s[2:]  this operation is slower than index-based method
                # b/c this requires memory operations such as garbage collection
            else:
                c1 = s[i]
                num += symbol_value[c1]
                i += 1
                # s = s[1:]  
        
        return num