DSA AnimatorREVISION VIDEOS
← Back to problems
New

Roman to Integer — LeetCode 13 video explanation

Convert a Roman numeral into an integer. Normally the symbols are added from left to right, like V I I for 7. But a smaller symbol placed before a larger one is subtracted, like I V for 4.

Loading videos…

DSA Animator › DSA Revision › Strings › Roman to Integer

Key moments in the Roman to Integer video

0:03Problem0:15Example0:23Brute force0:32Key idea0:40Dry run1:06Code1:18Takeaway

What you will learn

Remember: a smaller symbol before a larger one is subtracted. Comparing with the next symbol handles every special case at once. The video solves Roman to Integer (LeetCode 13, Easy) with the Lookahead pattern from the Strings topic, and you can replay every step in the interactive Roman to Integer animation.

Roman to Integer video transcript

Problem

Convert a Roman numeral into an integer. Normally the symbols are added from left to right, like V I I for 7. But a smaller symbol placed before a larger one is subtracted, like I V for 4.

Example

M, C, M, X, C, I, V is 1994. That is 1000, plus 900, plus 90, plus 4.

Brute force

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.

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.

Dry run

M is 1000, and the next symbol is smaller, so add 1000. C is 100, but the next symbol is M, which is bigger, so subtract 100, giving 900. M adds 1000, for 1900. X is smaller than the C after it, so subtract 10, giving 1890. C adds 100, for 1990. I is smaller than V, so subtract 1, then V adds 5. The total is 1994.

Code

In code, map each symbol to its value. For each index, compare its value with the value after it. Subtract when it is smaller, otherwise add. One pass, so it's O of n time and O of 1 space.

Takeaway

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

More Strings revision videos

← All 185 DSA revision videos