Skip to content
LEETFLIX

Easy · roman scan. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 13. Roman to Integer. The copyrighted prompt is on LeetCode. This page is a working roman scan for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

s =
III

Output

3

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Add, unless a smaller digit precedes a larger one

Scan left to right. If cur < next, subtract cur (the IV / IX / XL … rule). Otherwise add it.

Standard Roman is additive. The six subtractive pairs are exactly “a smaller value sitting before a larger one.”

Algorithm

  1. Map each letter to its value.
  2. For each digit, add it, or subtract it when the next one is larger.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def romanToInt(self, s: str) -> int:        val = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}        total = 0        for i, ch in enumerate(s):            cur = val[ch]            nxt = val[s[i + 1]] if i + 1 < len(s) else 0            total += -cur if cur < nxt else cur        return total
Watch this run

03

Interactive walkthrough

Playing “Add, unless a smaller digit precedes a larger one”. Edit the input, hit Run, then scrub.

Approach: Add, unless a smaller digit precedes a larger one

Loading animation…