Roman numerals use seven letters, each worth a fixed amount. From the top: M is 1000, D is 500, C is 100, L is 50, X is 10, V is 5 and I is 1. Letters are normally written from the largest value down, and their values simply add up, so CCXII is 100 + 100 + 10 + 1 + 1 = 212.
There is one twist. Six two-letter pairs put a smaller letter in front of a larger one, and then the smaller one is taken away: IV = 4, IX = 9, XL = 40, XC = 90, CD = 400 and CM = 900.
Given a valid Roman numeral as the string s, return the whole number it stands for.
Example 1
Input: s = "CDXLIV" Output: 444 Why: CD = 400, XL = 40, IV = 4
2 more examples and the constraints
Example 2
Input: s = "DCCLXII" Output: 762 Why: 500 + 200 + 50 + 10 + 2, no pairs at all
Example 3
Input: s = "XC" Output: 90 Why: X comes before the larger C, so 100 − 10
Constraints
- 1 ≤ length of s ≤ 15
- s uses only the seven letters M, D, C, L, X, V and I
- s is a valid Roman numeral for a value from 1 to 3,999
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Look up pairs firstO(n)
- Compare with the next symbolO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 15-letter numeral | Verdict |
|---|---|---|---|
| Look up pairs first | O(n) | Correct and clear; more to write | |
| Compare with the next symbol | O(n) | Best; one rule covers all six pairs |
n = number of letters in s. Both are linear; the second does fewer lookups and needs one table.
Edge cases to test
- A single letter.
Iis 1 andMis 1000; there is no next letter to compare with. - Pair at the end.
LXIVends withIV: the last letter is always added, the one before it subtracted. - Pairs back to back.
XLIXis 40 + 9 = 49. Each letter only looks at its own neighbour. - The largest value.
MMMCMXCIXis 3,999, the top of the range. - Repeated letters.
CCCXXXIIIhas no pairs; equal neighbours are added, not subtracted.
Common mistakes
- Subtracting when the next letter is equal, not strictly larger, which turns
IIinto 0. - Reading
s[i + 1]on the last letter without checking that it exists. - Subtracting the small letter twice: once for the pair and again when adding the larger one in full.
How to talk through it
- 1Clarify. Is the input always a valid numeral? Upper case only? What is the largest value?
- 2State the rules. Letters add up, except six pairs where a smaller letter before a larger one is subtracted.
- 3Give the direct version. Check for a pair at each position, else take one letter. It is O(n) and easy to verify.
- 4Simplify the rule. All six pairs are a smaller letter before a larger one, so one comparison with the next letter replaces the pair table.
- 5Test out loud. Run
I,XC,XLIXandMMMCMXCIXbefore saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?