LeetCode 13: Roman to Integer — Python Solution

LeetCode 13: Roman to Integer is an Easy array / string problem. This Python walkthrough develops a look-ahead parsing solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

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

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, add a symbol unless it is smaller than the following symbol, in which case subtract it. The invariant worth writing beside the code is: The running total equals the value of every fully resolved symbol in the prefix.

Step-by-step algorithm

  1. Identify the input state consumed by romanToInt(s) and initialize the data required by the look-ahead parsing pattern.
  2. Add a symbol unless it is smaller than the following symbol, in which case subtract it.
  3. After each update, verify the page’s central invariant: The running total equals the value of every fully resolved symbol in the prefix.
  4. Finish only after the boundary behavior is covered: The final symbol is always added; subtractive pairs are resolved by the look-ahead rule.

Python solution

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

Reading the implementation

The main entry point is romanToInt(s). The named working state includes values, total, value; those variables make the look-ahead parsing state visible instead of hiding it in incidental control flow.

A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, add a symbol unless it is smaller than the following symbol, in which case subtract it.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Add a symbol unless it is smaller than the following symbol, in which case subtract it. Each update records the current item without invalidating earlier decisions; consequently, the running total equals the value of every fully resolved symbol in the prefix.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

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

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().romanToInt("MCMXCIV") == 1994

Common mistakes and edge cases

  • Problem-specific boundary: The final symbol is always added; subtractive pairs are resolved by the look-ahead rule.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that the running total equals the value of every fully resolved symbol in the prefix.

Interview review checklist

  • Explain why look-ahead parsing matches the structure of this input.
  • State the invariant in one sentence before tracing code: The running total equals the value of every fully resolved symbol in the prefix.
  • Derive O(n) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: The final symbol is always added; subtractive pairs are resolved by the look-ahead rule.

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