DSA interview question
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).
int romanToInt(const string& s); // valid Roman numeral in [1, 3999]
Input s | Output | Explanation |
|---|---|---|
"III" | 3 | |
"LVIII" | 58 | L + V + III = 50 + 5 + 3 |
"MCMXCIV" | 1994 | M + CM + XC + IV |
"IV" | 4 | Subtractive form |
"IX" | 9 | |
"MMMCMXCIX" | 3999 | The 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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in