Magicsheet logo

Roman to Integer

Easy
79.9%
Updated 6/1/2025

Roman to Integer

What is this problem about?

The Roman to Integer interview question asks you to convert a Roman numeral string (using symbols I, V, X, L, C, D, M) to its corresponding integer value. Roman numerals follow specific additive and subtractive rules: when a smaller value symbol appears before a larger one (e.g., IV = 4, IX = 9), it is subtracted rather than added. Your task is to parse the string and compute the correct integer result.

Why is this asked in interviews?

This problem is asked at Apple, Uber, Goldman Sachs, Microsoft, Meta, Amazon, LinkedIn, Google, Bloomberg, Adobe, and dozens more companies because it tests string parsing, lookup tables (hash maps), and the ability to handle rules with exceptions. Roman numeral conversion is a classic example of translating a domain-specific language into a numeric value — directly applicable to parsing DSLs, financial notation, and document numbering systems.

Algorithmic pattern used

The pattern is left-to-right scan with a value lookup map. Build a map of Roman symbols to values: {I:1, V:5, X:10, L:50, C:100, D:500, M:1000}. Iterate through the string. If the current symbol's value is less than the next symbol's value (subtractive case), subtract the current value from the total. Otherwise, add it. Process the last character as always additive.

Example explanation

Input: "MCMXCIV"

  • M: 1000. Next=C(100). 1000 > 100 → add. Total=1000.
  • C: 100. Next=M(1000). 100 < 1000 → subtract. Total=900.
  • M: 1000. Next=X(10). 1000 > 10 → add. Total=1900.
  • X: 10. Next=C(100). 10 < 100 → subtract. Total=1890.
  • C: 100. Next=I(1). 100 > 1 → add. Total=1990.
  • I: 1. Next=V(5). 1 < 5 → subtract. Total=1989.
  • V: 5. Last char → add. Total=1994.

Result: 1994.

Common mistakes candidates make

  • Handling only specific subtractive cases (IV, IX, XL, etc.) explicitly instead of using the general rule.
  • Off-by-one when accessing the next character — always check bounds.
  • Not handling the last character separately — it is always additive.
  • Using ord() arithmetic instead of a proper lookup map, making the code fragile.

Interview preparation tip

For the Roman to Integer coding problem, the math and hash table interview pattern is elegant: build the symbol-to-value map, scan left to right, subtract when current < next. This one-pass O(n) solution handles all subtractive cases uniformly. Interviewers at Goldman Sachs and Capital One sometimes ask the reverse (Integer to Roman) as a follow-up — know that direction too. Practice both on a few examples (XIV, XLII, CMXCIX) to build confidence.

Similar Questions