File: roman-to-integer/solution.py

Date: 2026-06-06

Time: 18:57

roman-to-integer/solution.py

Purpose

This file implements LeetCode problem #13 — Roman to Integer. It owns a single responsibility: converting a valid Roman numeral string (like "MCMXCIV") into its integer equivalent (1994). It's a standalone solution module following the repo's convention of one problem per directory.

Key Components

romantoint(s: str) -> int — The sole public function. Contract: given a string s containing only valid Roman numeral characters representing a value in [1, 3999], returns the corresponding integer.

values dict — Maps the seven Roman numeral symbols to their integer values. Defined locally inside the function (not module-level), so it's reconstructed on each call.

Patterns

The solution uses the subtraction-rule scan pattern: iterate left to right, and at each position decide whether to add or subtract the current symbol's value based on a lookahead comparison with the next symbol.

This is the canonical single-pass approach for this problem. It exploits the fact that in valid Roman numerals, a smaller value preceding a larger value always means subtraction (e.g., IV = 4, XC = 90). In all other cases, values are additive.

The iteration uses index-based range(len(s)) rather than enumerate or zip — slightly more verbose but makes the i + 1 lookahead bounds check explicit.

Dependencies

Imports: None. Pure Python, no standard library usage.

Imported by: The roman-to-integer/test_solution.py file directly. The massive "Imported By" list in the prompt is misleading — those are unrelated test files across the repo, likely an artifact of the analysis tool matching on a shared test runner or import pattern, not actual imports of this function.

Flow

1. Build the values lookup table.

2. Initialize result = 0.

3. For each index i in the string:

4. Return result.

For input "XIV":

Invariants

Error Handling

None. Invalid characters raise KeyError from the values dict lookup. Empty string input returns 0 (the loop body never executes). There's no explicit validation — the function trusts the caller to provide valid input per the LeetCode problem constraints.

Topics to Explore

Beliefs