Algorithm Day108 - Roman to Integer
📌 Problem
Convert a Roman numeral to an integer. Input is guaranteed to be within the range corresponding to standard Roman numerals (typically 1..3999).
Roman numerals are represented by the symbols:I(1), V(5), X(10), L(50), C(100), D(500), M(1000).
Some symbols may be placed before larger symbols to indicate subtraction, e.g., IV = 4, IX = 9.
💬 Examples
Example 1
1 | Input: s = "III" |
Example 2
1 | Input: s = "IV" |
Example 3
1 | Input: s = "MCMXCIV" |
💡 Intuition (Greedy / Left-to-right)
Scan from left to right, adding values. If a smaller-value symbol appears before a larger one, subtract the smaller; otherwise add it. A simple approach: for each character, compare its value with the next character (if any) to decide add or subtract.
🔢 Java Code (Map + Greedy)
1 | import java.util.*; |
⏱ Complexity Analysis
- Time: O(n) — single pass over the string.
- Space: O(1) — constant-size map and a few variables.
✍️ Summary
- Use a mapping from Roman symbols to integers.
- Subtract when a smaller symbol precedes a larger one; otherwise add.
- Simple, linear-time solution ideal for interviews.