AlgoInsight

DSA problem

Roman to Integer

EasyMaths / GeometryPattern: Maths / Geometrytop600AmazonMicrosoftGoogleBloombergApple

Roman numerals are written using seven symbols — I, V, X, L, C, D, and M — whose values are 1, 5, 10, 50, 100, 500, and 1000 respectively. Given a Roman numeral string, convert it to an integer.

In the vast majority of positions the numeral is simply additive: you read left to right and accumulate the values of every symbol. For example, III is 1 + 1 + 1 = 3, and LVIII is 50 + 5 + 1 + 1 + 1 = 58. The interesting wrinkle is subtractive notation, used in six specific cases where a smaller numeral appears just before a larger one — IV, IX, XL, XC, CD, CM — meaning 4, 9, 40, 90, 400, and 900.

A natural way to handle both rules in a single pass is to compare each character with the one that follows it. If the current symbol's value is strictly less than the next symbol's value, we are in a subtractive pair: subtract the current value from the running total. Otherwise add it. The last character has nothing to its right, so it is always added.

This approach scans the string exactly once, performs O(1) work per character, and uses only a small fixed lookup table from symbol to integer. The total time complexity is O(n) where n is the length of the input (at most 15 for valid Roman numerals in the range 1 to 3999), and the extra space is O(1).

Examples

Example 1
Input: s = "III"
Output: 3
Explanation: Three I symbols, each worth 1, are simply added: 1 + 1 + 1 = 3.
Example 2
Input: s = "LVIII"
Output: 58
Explanation: L is 50, V is 5, and three Is contribute 3 more, giving 50 + 5 + 3 = 58.
Example 3
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4. Summing the four pieces yields 1994.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

mathstringhash-table

Browse all DSA problems