InterviewPrepKit

Home / Coding / Math & Geometry

Roman to Integer

easy Original β†—
Solving tips
  • Recognize this as a local-exception scan: numerals are additive except when a smaller symbol sits directly left of a larger one, which signals subtraction.
  • Key insight: add each symbol's value, but subtract it when val[s[i]] < val[s[i+1]]; no need to hardcode the six subtractive pairs.
  • Target O(n) time and O(1) space (the 7-entry value map is fixed size).
  • Common pitfall: use strict < not <= (equal neighbors like II are additive), and always add the last symbol which has no right neighbor.

Problem

Roman numerals use seven symbols with fixed values: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. Numbers are written by placing symbols from largest to smallest and adding their values β€” except for six subtractive cases where a smaller symbol precedes a larger one and is subtracted: IV=4, IX=9, XL=40, XC=90, CD=400, CM=900. Given a valid Roman numeral string, return its integer value.

Examples

  • "III" β†’ 3 β€” 1 + 1 + 1.
  • "LVIII" β†’ 58 β€” 50 + 5 + 1 + 1 + 1.
  • "MCMXCIV" β†’ 1994 β€” M(1000) + CM(900) + XC(90) + IV(4).

Constraints

  • 1 <= len(s) <= 15
  • s is a valid Roman numeral in the range [1, 3999].

Think about it first

Hint 1 Map each symbol to its value. Almost every symbol simply adds its value to a running total β€” the subtractive pairs are the only exception.
Hint 2 A symbol is subtracted exactly when its value is smaller than the value of the symbol immediately to its right (e.g. the `I` in `IV`). Otherwise it is added.
Hint 3 Scan left to right comparing each symbol with its right neighbor β€” subtract when strictly smaller, add otherwise. (Scanning right to left works too: compare each symbol with the previous, larger-so-far value.)
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.