DSA patterns

Roman to Integer

easyArrays and hashing

Problem statement

Convert a Roman numeral string s into an integer. The symbols and their values are:

TEXT
I = 1 V = 5 X = 10 L = 50
C = 100 D = 500 M = 1000

Symbols are normally written from largest to smallest and added up. The exception: when a smaller symbol sits directly before a larger one, it is subtracted instead. Only six such pairs are allowed: IV (4), IX (9), XL (40), XC (90), CD (400) and CM (900). You can assume s is a valid numeral between 1 and 3999.

Examples

Example 1

Input: s = "XLIV"

Output: 44

Explanation: XL is 40 and IV is 4.

Example 2

Input: s = "MMXXVI"

Output: 2026

Explanation: 1000 + 1000 + 10 + 10 + 5 + 1.

Hints

Approach

Walk the string once. For each symbol, peek at the next one. If the next symbol is larger, this one is part of a subtractive pair, so subtract it. Otherwise add it.

  1. Set total = 0.
  2. For each index i, let v be the value of s[i].
  3. If there is a next symbol and its value is greater than v, subtract v. Otherwise add v.
  4. Return total.

For XLIV: X (10) is before L (50), so subtract 10. L is added, giving 40. I (1) is before V (5), so subtract 1. V is added, giving 44.

ComplexityTime O(n)Space O(1)
Python
class Solution:
def romanToInt(self, s: str) -> int:
values = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
total = 0
for i, ch in enumerate(s):
v = values[ch]
if i + 1 < len(s) and v < values[s[i + 1]]:
total -= v
else:
total += v
return total

Follow-up questions

  • Write the reverse: convert an integer from 1 to 3999 into a Roman numeral.
  • Parse a duration string like 2h45m10s into total seconds.

Frequently asked questions

The value table has seven fixed entries, and since the input is at most 3999, the string is at most 15 characters. In interviews, still describe the time as O(n) in the string length.

No. It assumes valid input, so something like IIV would still produce a number. Validation would need extra rules about which pairs and repeats are allowed.

It is a small parsing exercise: read symbols, look up values, and handle one context rule. That is the same shape as parsing size suffixes like 512Mi and 2G, or duration strings like 1h30m, which you meet in Kubernetes and config tooling.