LeetCode #13 Easy

Roman to Integer

Roman to Integer is LeetCode 13 (Easy). You are given a Roman numeral s and must return its value. The seven symbols are I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000.

  • Adding: symbols are normally written from largest to smallest, and their values add up: XII is 12.
  • Subtracting: six pairs put a smaller symbol before a larger one to mean the difference: IV 4, IX 9, XL 40, XC 90, CD 400, CM 900.

The input is always a valid numeral between 1 and 3999, at most 15 symbols long.

Constraints
  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].
stringhash-tablemath
Open on LeetCode ↗
02

Intuition

You do not need to search for the six pairs. They all have the same shape: a smaller symbol directly before a larger one. So compare each symbol with the one after it:

  • Smaller than the next: it is the front of a pair, so subtract it.
  • Otherwise: add it. The last symbol has nothing after it and is always added.

Subtracting the front and then adding the larger symbol gives the pair's value: for IX that is −1 + 10 = 9.

How to spot this pattern

When a symbol's meaning depends only on its neighbour, one left-to-right pass that looks at s[i + 1] replaces a list of special cases. Here the neighbour decides whether a symbol counts as plus or minus.

03

Approach

Try it first

Before reading on, write MCMXCIV as a sum of seven signed numbers, one per symbol, and check that it adds up to 1994. Aim for O(n) time.

1

Map symbols to values

Store the seven values in a dictionary (a switch works too). The input is guaranteed to be a valid numeral, so there is nothing to validate.

2

Add or subtract each symbol

Walk the string from left to right. If there is a next symbol and the current value is strictly smaller than it, subtract the current value; otherwise add it.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def romanToInt(self, s: str) -> int:
▶3 value = {"I": 1, "V": 5, "X": 10, "L": 50,
▶4 "C": 100, "D": 500, "M": 1000}
▶5 total = 0
▶6 for i in range(len(s)):
▶7 if i + 1 < len(s) and value[s[i]] < value[s[i + 1]]:
▶8 total -= value[s[i]]
▶9 else:
▶10 total += value[s[i]]
▶11 return total
saddsI1I1I1total0add each symbol; subtract if a larger one follows
sIII
total0
Start. Each symbol is compared with the one right after it. A smaller symbol before a larger one is the front of a pair like IV or CM, so it is subtracted; every other symbol is added.
saddsI1+1I1I1checkI=Ithisnexttotal1I = I: add 1
symbolIvalue 1
total1
I equals the next symbol, and equal symbols simply add up. That is why the test is <, not <=: add 1.
saddsI1+1I1+1I1checkI=Ithisnexttotal2I = I: add 1
symbolIvalue 1
total2
I equals the next symbol, and equal symbols simply add up. That is why the test is <, not <=: add 1.
saddsI1+1I1+1I1+1checkI→endthisnexttotal3last symbol: add 1
symbolIvalue 1
total3
I is the last symbol. Nothing follows it, so it can never be subtracted: add 1.
saddsI1+1I1+1I1+1total3return 3
answer3
Answer 3. The total is the sum of the row above: 1 + 1 + 1.
05

Common pitfalls

Reading past the last symbol

✗ Wrong
if value[s[i]] < value[s[i + 1]]:
✓ Right
if i + 1 < len(s) and value[s[i]] < value[s[i + 1]]:

For the last symbol s[i + 1] does not exist, so Python raises IndexError and C++ reads past the string. The last symbol is never subtracted, so check that a next symbol exists first.

Using <= instead of <

✗ Wrong
if value[s[i]] <= value[s[i + 1]]:
✓ Right
if value[s[i]] < value[s[i + 1]]:

Equal symbols add: III is 3. With <= the first two Is are subtracted and III comes out as −1 − 1 + 1 = −1.

06

Complexity

Time
O(n)
Space
O(1)
One pass over the n symbols (at most 15), with one comparison each. The table always has seven entries.
07

Roman to Integer FAQ

Can it be solved from right to left?

Yes. Walk backwards and remember the value of the symbol to the right. Add the current symbol if it is at least that value, subtract it if it is smaller. It makes the same decisions as the left-to-right pass, but never looks ahead, so there is no end-of-string check.

What is the difference between Roman to Integer and Integer to Roman?

Roman to Integer (LeetCode 13) reads a numeral and returns its value, so the six pairs are found by comparing neighbours. Integer to Roman (LeetCode 12) goes the other way: it puts the pairs into the value table (900 = CM, 400 = CD, ...) and greedily takes the largest value that still fits.