Roman to Integer

Pattern: String parsing

easy

Add each symbol's value, except when a smaller symbol comes right before a bigger one, as in IV or CM; then subtract it. One look ahead per symbol decides.

The problem

Convert a Roman numeral to a whole number. The symbols are I 1, V 5, X 10, L 50, C 100, D 500 and M 1000. Usually they are written largest first and added, but six pairs subtract: IV 4, IX 9, XL 40, XC 90, CD 400 and CM 900. For example, "III" gives 3, "LVIII" gives 58 and "MCMXCIV" gives 1994.

The function name romanToInt matches LeetCode. Use the link above for the exact statement and limits. The input is always a valid numeral from 1 to 3999.

Think first

  • In "IV" and "VI", the same symbols give different values. What decides it?
  • Can you decide each symbol's sign by looking only at the next one?
  • Do you need a separate rule for each of the six subtractive pairs?

Hints

    Brute force, and why it fails

    Replace each of the six pairs with a marker first, then add everything: works, but is longer and easy to get wrong. The look-ahead rule covers all six pairs at once. Both are O(n).

    The key insight

    All six special cases follow one rule: smaller before bigger means subtract. Looking one symbol ahead is enough to apply it.

    Dry run

    M0 
    C1 
    M2 
    X3 
    C4 
    I5 
    V6 
    total0

    s = MCMXCIV. Values are M 1000, C 100, X 10, I 1, V 5.

    Step 1 of 4

    The plan

    total = 0
    for i from 0 to n - 1:
        v = value(s[i])
        if i + 1 < n and v < value(s[i + 1]): total = total - v
        else: total = total + v
    return total
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass with a fixed table of seven values.

    Edge cases

    • One symbol: its value.
    • The largest numeral, "MMMCMXCIX": 3999.
    • Repeated symbols, as in "III": just add.
    I've built my logic, show the code

    Java

    class Solution {
        public int romanToInt(String s) {
            int total = 0;
            for (int i = 0; i < s.length(); i++) {
                int v = value(s.charAt(i));
                if (i + 1 < s.length() && v < value(s.charAt(i + 1))) total -= v;   // a smaller symbol before a bigger one
                else total += v;
            }
            return total;
        }
    
        private int value(char c) {
            switch (c) {
                case 'I': return 1;
                case 'V': return 5;
                case 'X': return 10;
                case 'L': return 50;
                case 'C': return 100;
                case 'D': return 500;
                default: return 1000;                // 'M'
            }
        }
    }

    C++

    class Solution {
    public:
        int romanToInt(string s) {
            int total = 0;
            for (size_t i = 0; i < s.size(); i++) {
                int v = value(s[i]);
                if (i + 1 < s.size() && v < value(s[i + 1])) total -= v;   // a smaller symbol before a bigger one
                else total += v;
            }
            return total;
        }
    
        int value(char c) {
            switch (c) {
                case 'I': return 1;
                case 'V': return 5;
                case 'X': return 10;
                case 'L': return 50;
                case 'C': return 100;
                case 'D': return 500;
                default: return 1000;                // 'M'
            }
        }
    };

    Python

    class Solution:
        VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    
        def romanToInt(self, s: str) -> int:
            total = 0
            for i, c in enumerate(s):
                v = self.VALUES[c]
                if i + 1 < len(s) and v < self.VALUES[s[i + 1]]:
                    total -= v                       # a smaller symbol before a bigger one
                else:
                    total += v
            return total

    Common mistakes

    • Looking past the end of the string for the last symbol.
    • Subtracting when the next symbol is equal, as in "II".
    • Handling only some of the six subtractive pairs with special cases.

    Similar problems