Problem Statement
Roman to Integer
Roman numerals are written with seven letters, and each letter stands for a fixed number: I is 1, V is 5, X is 10, L is 50, C is 100, D is 500, and M is 1000. You are given a string of these letters, and your job is to turn it into a normal number. Most of the time you just add the letters up. The one twist is subtraction: when a smaller letter sits right before a bigger one, the smaller one is taken away instead of added. For example, IV is 4 (5 minus 1) and IX is 9 (10 minus 1).
Signals to notice
Brute force first
Map each symbol, add values left to right — misses subtraction cases. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
If current symbol < next symbol, subtract instead of add. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on s="MCMXCIV"
i=0 s[i]=M(1000), next C(100): 1000<100 false -> add. result=1000 i=1 s[i]=C(100), next M(1000): 100<1000 true -> subtract. result=900 i=2 s[i]=M(1000), next X(10): false -> add. result=1900 i=3 s[i]=X(10), next C(100): 10<100 true -> subtract. result=1890 i=4 s[i]=C(100), next I(1): false -> add. result=1990 i=5 s[i]=I(1), next V(5): 1<5 true -> subtract. result=1989 i=6 s[i]=V(5), no next -> add. result=1994 return 1994
What must stay true
When a smaller value appears before a larger one, subtract it (IV = 4, not 6). If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
val = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000}
result = 0
for i in 0..len(s)-1:
if i+1 < len(s) and val[s[i]] < val[s[i+1]]: result -= val[s[i]]
else: result += val[s[i]]
return resultPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Not handling the subtraction rule — compare each symbol with the next one. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.