Roman to Integer (LeetCode 13): Solution and Explanation
Convert a Roman numeral string to its integer value. The seven symbols I, V, X, L, C, D and M stand for 1, 5, 10, 50, 100, 500 and 1000, and six special pairs such as IV for 4 or CM for 900 use subtraction instead of addition.
Watch it run step by step
Try your own input and write the code →Intuition
The straightforward reading is to add up every symbol's value. That is right for numerals like III or LVIII, which are written from largest to smallest, but it breaks on the subtractive pairs. IV would come out as 6 instead of 4.
One fix is to list all six pairs (IV, IX, XL, XC, CD, CM) explicitly, check for a two-character match first at each position, and otherwise fall back to a single symbol. That works, but it needs a second lookup table and careful index handling.
There is a simpler rule hiding underneath. In a valid numeral, symbols normally appear in non-increasing order of value. The only time a smaller symbol appears directly before a larger one is in a subtractive pair, and in that case the smaller one should count as negative. So for each position, compare the symbol with the one after it: subtract it if the next is larger, add it otherwise.
With that rule, a single left-to-right pass with one lookup per character is enough, and the six special cases never have to be named. You can also scan right to left, keeping the previous value and subtracting whenever the current symbol is smaller, which is the same idea seen from the other end.
Approach: Single pass with a look-ahead rule
- Build a map from each Roman symbol to its value.
- Start with
result = 0. - For each index
i, look at the value ofs[i]and, if there is a next character, the value ofs[i + 1]. - If the current value is smaller than the next one, subtract it from
result. - Otherwise add it. The last character always falls into this branch because it has no successor.
- Return
resultafter the loop.
Step-by-step example
s = "MCMXCIV"
- M (1000) is followed by C (100), which is smaller, so 1000 is added and
result = 1000. - C (100) is followed by M (1000), which is larger, so 100 is subtracted, giving 900. Then M is followed by X and adds 1000, giving 1900.
- X (10) is followed by C (100), so 10 is subtracted, giving 1890. C is followed by I and adds 100, giving 1990.
- I (1) is followed by V (5), so 1 is subtracted, giving 1989. V is last and adds 5, so the function returns 1994.
Code: Python, Java, C++
1class Solution:
2 def romanToInt(self, s: str) -> int:
3 roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
4 result = 0
5
6 for i in range(len(s)):
7 if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]:
8 result -= roman[s[i]]
9 else:
10 result += roman[s[i]]
11
12 return result1class Solution {
2 public int romanToInt(String s) {
3 int[] values = new int[128];
4 values['I'] = 1; values['V'] = 5; values['X'] = 10;
5 values['L'] = 50; values['C'] = 100; values['D'] = 500; values['M'] = 1000;
6
7 int result = 0;
8 for (int i = 0; i < s.length(); i++) {
9 if (i + 1 < s.length() && values[s.charAt(i)] < values[s.charAt(i + 1)]) {
10 result -= values[s.charAt(i)];
11 } else {
12 result += values[s.charAt(i)];
13 }
14 }
15 return result;
16 }
17}1class Solution {
2public:
3 int romanToInt(string s) {
4 unordered_map<char, int> roman = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
5 int result = 0;
6
7 for (int i = 0; i < s.size(); i++) {
8 if (i + 1 < s.size() && roman[s[i]] < roman[s[i + 1]]) {
9 result -= roman[s[i]];
10 } else {
11 result += roman[s[i]];
12 }
13 }
14 return result;
15 }
16};Time and space complexity
O(n)
Each character is visited once with two constant-time dictionary lookups, and the input is at most 15 characters long.
O(1)
The symbol map has a fixed seven entries regardless of the input, and only one running total is kept.
Other approaches
Explicit pair table (time O(n), space O(1))
Check whether the two characters starting at i form one of the six subtractive pairs; if so, add the pair's value and skip two characters, otherwise add the single symbol. It is very literal and easy to verify against the rules, at the cost of a larger table.
Right-to-left scan (time O(n), space O(1))
Walk from the end, tracking the largest value seen so far, and subtract any symbol smaller than the previous one while adding the rest. It avoids the bounds check on i + 1.
Common mistakes
- Forgetting the bounds check on
i + 1and reading past the end of the string on the last character. - Using
<=instead of<in the comparison. Repeated symbols like II or XX must both be added, not subtracted. - Adding the full pair value and the individual symbol values, which double counts subtractive pairs such as IX.
- Assuming the input might be invalid and adding complex validation. The problem guarantees a valid numeral, so the simple rule is enough.
Frequently asked questions
How does subtraction work in Roman numerals?
When a smaller symbol appears directly before a larger one, it is subtracted from it: IV is 4, IX is 9, XL is 40, XC is 90, CD is 400 and CM is 900. Everywhere else, values are simply added.
Why compare each symbol with the next one?
In a valid numeral, the only time a smaller value precedes a larger one is a subtractive pair. Comparing neighbors detects every such pair without listing them explicitly.
What is the time complexity of Roman to Integer?
It is O(n) for a string of length n, with O(1) extra space for the fixed symbol table. Since valid numerals in range are at most 15 characters, it is effectively constant.
How do you convert an integer back to Roman numerals?
Go through value and symbol pairs from largest to smallest, including the six subtractive pairs, and greedily append each symbol while its value still fits into the remaining number.