Roman to Integer Algorithm
Seven symbols. That's the entire Roman numeral system: I (1), V (5), X (10), L (50), C (100), D (500), M (1000).
10 Mar 2024

Seven symbols. That's the entire Roman numeral system: I (1), V (5), X (10), L (50), C (100), D (500), M (1000).
The rule is simple: usually you add values left to right. But when a smaller value appears before a larger one, you subtract it. IV = 4, not 6. IX = 9, not 11.
The intuition
Walk the string right to left. If the current symbol is smaller than the one after it, subtract. Otherwise, add. That one rule handles every case.
Why right to left? It's cleaner. You always compare the current value against the previous one you processed. No need for lookahead.
function romanToInt(s) {
const values = {
'I': 1, 'V': 5, 'X': 10, 'L': 50,
'C': 100, 'D': 500, 'M': 1000
};
let result = 0;
let prev = 0;
for (let i = s.length - 1; i >= 0; i--) {
const current = values[s[i]];
if (current < prev) {
result -= current;
} else {
result += current;
}
prev = current;
}
return result;
}
Complexity
- Time: O(n) — one pass through the string.
- Space: O(1) — the lookup map is fixed-size.
Why this is a good interview question
It tests whether you can spot the subtraction rule and encode it cleanly. Most candidates write a left-to-right solution with messy lookahead. Going right to left is the elegant move — it turns a two-condition check into a single comparison.