Skip to main content
DSA patterns

Roman to Integer

easyArrays and hashingService-Based MNCsStartups

Problem statement

You get a string s that holds a valid Roman numeral, made only of the symbols I, V, X, L, C, D and M. Convert it to the plain integer it represents.

Normally these symbols are written largest to smallest and just added up. The one exception is when a smaller symbol sits directly before a larger one — then it's subtracted instead of added (IV means 4, not 6). You're guaranteed the input is a valid numeral for a number between 1 and 3999, so there's no need to check for malformed input.

Examples

Example 1

Input: s = "III"

Output: 3

Explanation: III is simply 1 + 1 + 1.

Example 2

Input: s = "LVIII"

Output: 58

Explanation: L is 50, V is 5, and III is 3 — added together, 50 + 5 + 3 = 58.

Example 3

Input: s = "MCMXCIV"

Output: 1994

Explanation: M is 1000, CM is 900 (subtractive: 100 before 1000), XC is 90 (subtractive: 10 before 100), and IV is 4 (subtractive: 1 before 5) — 1000 + 900 + 90 + 4 = 1994.

Hints

Hint 1: Start with the plain value of every symbol (I = 1, V = 5, and so on). Just adding those values symbol by symbol already gives the right answer for "III" and "LVIII" — where does that plain-sum idea break down?

Approach

Optimal: Compare each symbol to the next

Intuition

All six subtractive cases share one thing in common: a smaller-value symbol appears immediately before a larger one. Instead of listing the six pairs by name, just compare each symbol's value to the value of the symbol right after it. If the current symbol is smaller than the next one, it must be a subtractive case, so subtract it; otherwise, add it as usual. This one comparison quietly covers IV, IX, XL, XC, CD and CM without ever naming them, which is what makes it faster and simpler than matching pairs explicitly.

Steps

  1. Build a map from each of the seven symbols to its value.
  2. Walk through the string from left to right, looking at one character at a time.
  3. Look up the current symbol's value. If there is a next character and the current value is less than the next symbol's value, subtract the current value from the total.
  4. Otherwise, add the current value to the total.
  5. After the last character, return the total.

Dry run

s = "MCMXCIV" → values: M=1000, C=100, M=1000, X=10, C=100, I=1, V=5

i symbol value next value value < next? action total after
0 M 1000 100 (C) no add 1000 1000
1 C 100 1000 (M) yes subtract 100 900
2 M 1000 10 (X) no add 1000 1900
3 X 10 100 (C) yes subtract 10 1890
4 C 100 1 (I) no add 100 1990
5 I 1 5 (V) yes subtract 1 1989
6 V 5 — (last) — add 5 1994

Return 1994 — matches example 3 exactly.

Edge cases: a single-symbol string like "M" has no "next" character to compare against, so the last-symbol branch always adds it. A numeral with no subtractive pairs, like "III", never finds a smaller value before a larger one, so every symbol is simply added.

Complexity

Time O(n) - Same linear shape as the brute force, but with a single map and a single comparison per character instead of a subtraction-pair lookup.

Space O(1) - Only one lookup map is needed, holding the seven fixed symbol values; its size never changes no matter how long the string is.

class Solution:
    def romanToInt(self, s: str) -> int:
        values = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
        total = 0
        n = len(s)
        for i in range(n):
            cur = values[s[i]]
            if i + 1 < n and cur < values[s[i + 1]]:
                total -= cur
            else:
                total += cur
        return total


if __name__ == "__main__":
    print(Solution().romanToInt("III"))       # 3
    print(Solution().romanToInt("LVIII"))     # 58
    print(Solution().romanToInt("MCMXCIV"))   # 1994
RecapThe whole problem in a few lines, for the night before
  • Spot it: convert a Roman numeral string to a number
  • Idea: add each symbol's value, but subtract it when the next symbol is bigger (IV = 5 - 1)
  • Cost: O(n) time, O(1) space
  • Trap: reading left to right and always adding gives the wrong answer for IV, IX, XL and similar pairs

Interview follow-ups

  • Could you validate that the input is actually a well-formed Roman numeral, instead of assuming it?

    Yes — after converting, convert the resulting integer back to a Roman numeral using the standard greedy symbol-table method, and check that it matches the original string exactly. Any malformed numeral (like "IIII" or "VV") would produce a different canonical string on the round trip, revealing the mismatch. This adds one more O(1)-ish pass (the numbers are capped at 3999) on top of the conversion.

  • How would you convert an integer back into a Roman numeral?

    Walk a fixed, ordered list of value/symbol pairs from largest to smallest, including the subtractive combinations themselves as single entries (1000 → "M", 900 → "CM", 500 → "D", 400 → "CD", …, 1 → "I"). For each pair, while the remaining number is at least that value, append the symbol and subtract the value. This greedy approach always produces the correct numeral because Roman numeral values were designed to work with a greedy largest-first strategy.

Frequently asked questions

Every subtractive pair in Roman numerals follows the exact same rule: a smaller-value symbol placed directly before a larger one means "subtract this." That's true whether it's IV, IX, XL, XC, CD or CM — the rule never changes, only the specific values do. So a single "is this symbol smaller than the next one?" check automatically handles all six cases without the code needing to know their names.

Because it never groups characters into pairs in the first place. It looks at each symbol exactly once and decides to add or subtract it based on a comparison with its neighbor — the "pair" is implicit in the comparison, not something the code has to detect and jump over.

You'd get the wrong answer for any numeral with a subtractive pair. For "IV", plain summing would give 1 + 5 = 6 instead of the correct 4. The whole point of Roman numerals' subtractive notation is that a smaller symbol before a larger one flips from being added to being subtracted.

It's a compact test of parsing a compact, symbolic format into a numeric value using positional context — the same general skill needed to parse version strings, encoded flags, or legacy identifiers where a symbol's meaning depends on what comes next to it, not just the symbol itself.