Roman to Integer

Easy

Topics
Hash TableMathString

Given a Roman numeral string s, convert it to an integer. Symbols: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. A smaller symbol before a larger one is subtracted (e.g., IV = 4).

Example 1

III
Values normally add, left to right. The only rule beyond that is that a smaller numeral placed before a larger one is subtracted instead — so comparing each symbol with the next decides its sign, and no special-casing of IV, IX, XL and the rest is needed. III = 3.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "III"
Output: 3

Example 2

LVIII
Input:  s = "LVIII"
Output: 58

Example 3

MCMXCIV
subtracted — smaller before larger
Input:  s = "MCMXCIV"
Output: 1994

Constraints

  • 1 <= s.length <= 15
  • s is a valid Roman numeral in the range [1, 3999].
Editorial — intuition, approach, complexity and pitfalls

Intuition

Roman numerals are additive except for six subtractive pairs — IV, IX, XL, XC, CD, CM. The obvious implementation special-cases those six by peeking at two characters at a time.

There is a cleaner rule that covers all six without naming any of them: a symbol is subtracted exactly when a strictly smaller value precedes a larger one. That is the defining property of the subtractive pairs, so one left-to-right scan with a single lookahead handles every case.

MCMXCIV
M  1000, next C is smaller   -> add      1000
C   100, next M is larger    -> subtract  -100
M  1000, next X is smaller   -> add      1000
X    10, next C is larger    -> subtract   -10
C   100, next I is smaller   -> add       100
I     1, next V is larger    -> subtract    -1
V     5, last character      -> add          5
                                           ----
                                           1994

Approach

  1. Map each symbol to its value.
  2. For each position, subtract its value if the next symbol is strictly larger, else add it.

Dry Run

s = "LVIII"
L 50, next V smaller   -> +50    total 50
V  5, next I smaller   -> +5     total 55
I  1, next I equal     -> +1     total 56
I  1, next I equal     -> +1     total 57
I  1, last             -> +1     total 58

answer 58    note "equal" adds, which is why the
             comparison must be strict

Complexity

  • Time — O(n): one pass, and the input is capped at 15 characters.
  • Space — O(1): the symbol table has seven fixed entries.

Common Pitfalls

  • Using <= instead of < for the lookahead. Equal neighbours like the III in LVIII must add, and <= would subtract them.
  • Reading past the end on the final character. Guard the lookahead with an index check.
  • Hard-coding the six subtractive pairs. It works, but it is more code and it obscures the single rule that generates them.
  • Assuming the input might be malformed. The constraints promise a valid numeral in [1, 3999], so no validation is required — but say so rather than silently relying on it.

Full Solution — all languages

class Solution:
    def romanToInt(self, s):
        val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        total = 0
        for i in range(len(s)):
            if i + 1 < len(s) and val[s[i]] < val[s[i + 1]]:
                total -= val[s[i]]
            else:
                total += val[s[i]]
        return total
SensAI
Beta
Tap the mic to stop voice mode