DSA AnimatorDSA animations
Roman to Integer LC #13 Easy String Parsing · HashMap
Problem

Given a Roman numeral string s, convert it to an integer. Roman numerals use I=1, V=5, X=10, L=50, C=100, D=500, M=1000. When a smaller value precedes a larger one, it is subtracted (e.g. IV=4, IX=9, CM=900).

Example 1
Input: s = "MCMXCIV"
Output: 1994
Explanation: M=1000, CM=900, XC=90, IV=4 → 1994
Example 2
Input: s = "LVIII"
Output: 58
Explanation: L=50, V=5, III=3 → 58
Constraints: 1 ≤ s.length ≤ 15 | s contains only I, V, X, L, C, D, M | 1 ≤ answer ≤ 3999
Try Examples
Custom:
Approach
Scan left → right, comparing each char's value with the next
If cur < next → subtract (subtractive rule e.g. IV, CM). Else → add. Single pass O(n).
Roman String
Value Reference
Comparison & Action
s[i] = cur
—
?
s[i+1] = nxt
—
→
Running Total
0
Variables
i
—
cur
—
nxt
—
action
—
res
0
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Build map: I=1, V=5, X=10, L=50, C=100, D=500, M=1000
2
For each index i: get cur = map[s[i]]
3
Get nxt = map[s[i+1]] or 0 if last char
4
If cur < nxt → res -= cur (subtractive: IV, IX, CM…)
5
Else → res += cur (standard addition)
6
Return res after scanning all chars
Time
O(n)
Space
O(1)
Why This Works

Roman numerals subtract when a smaller symbol precedes a larger one (IV, IX, XL, XC, CD, CM). The simple rule: compare cur with nxt. If cur < nxt → subtract; else → add. A single left-to-right pass handles all cases correctly in O(n).

How to solve Roman to Integer

LeetCode 13 · Easy · Strings · Pattern: Lookahead

Why the obvious approach is slow

Listing every special pair, like C M or X C, as its own case works, but it is easy to miss one. One simple rule covers all of them.

The key idea

Look at each symbol and the one right after it. If the current value is smaller than the next value, subtract it. Otherwise, add it.

Remember

A smaller symbol before a larger one is subtracted. Comparing with the next symbol handles every special case at once.

Run the animation above on your own input, or watch the 1:27 video explanation of Roman to Integer with a dry run and Java code.

More Strings problems