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.
Production-Ready Systems with LLMs and Agents
A live Maven cohort, 5 October to 2 November: eight 90-minute sessions where you build LLM and agent systems that survive real traffic, real cost and real failure. Tuesdays and Thursdays, 7:30 to 9:00pm London.
Cohort 2 starts 5 October. Eight live sessions, $1,500.
View the live cohortKeep reading
- The Algorithms Worth Knowing in Code Review: Cutting Big O Without Being Clever
- Tracking Down the Mystery: Finding the Unique Delivery ID
- Elusive Least Occurring Number in an Array
- Solving the Height of a Binary Tree Puzzle
- Harry Potter Discounts: A Code Challenge Algorithm
- Implementing a Task Heap Service in TypeScript