PPractick

DSA interview question

Roman to Integer

Medium · Algorithms · Topics: string, hash map, math

The problem

A museum's catalogue lists exhibit years in Roman numerals, like MCMXCIV, and the search system needs them as integers. Roman numerals mostly add up symbol values (VIII = 5 + 1 + 1 + 1), with one twist: a smaller symbol before a larger one is subtracted, as in IV = 4, IX = 9 and CM = 900. So the conversion is a single left-to-right pass, subtracting a symbol when the next one is larger and adding it otherwise.

Example: "MCMXCIV" → 1994 (M + CM + XC + IV = 1000 + 900 + 90 + 4).

Function signature

int romanToInt(const string& s);  // valid Roman numeral in [1, 3999]

Test cases

Input sOutputExplanation
"III"3
"LVIII"58L + V + III = 50 + 5 + 3
"MCMXCIV"1994M + CM + XC + IV
"IV"4Subtractive form
"IX"9
"MMMCMXCIX"3999The largest standard numeral

(Confirm: the input is a valid standard numeral using I, V, X, L, C, D, M; subtractive pairs are IV, IX, XL, XC, CD and CM.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the input guaranteed to be valid?
  2. What range? (Standard numerals go up to 3999.)
  3. Uppercase only?

Follow-ups to expect

  1. "How do you detect the subtractive cases?"
  2. "Why does comparing with the next symbol work for all six subtractive pairs?"
  3. "How do you convert an integer to Roman?"
  4. "How would you validate the input?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in