LeetCode 13: Roman to Integer — Python Solution

Solve LeetCode 13: Roman to Integer in Python with a look-ahead parsing approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyEasy
TopicArray / String
Reusable patternlook-ahead parsing
ComplexityO(n) time and O(1) extra space

What the problem is testing

Add a symbol unless it is smaller than the following symbol, in which case subtract it.

Algorithm

  1. Add a symbol unless it is smaller than the following symbol, in which case subtract it.
  2. Maintain this invariant: The running total equals the value of every fully resolved symbol in the prefix.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

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

Why this is correct

The proof follows the maintained state: The running total equals the value of every fully resolved symbol in the prefix. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n) time and O(1) extra space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

The final symbol is always added; subtractive pairs are resolved by the look-ahead rule.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 42. Trapping Rain Water · Next: 12. Integer to Roman