13. Roman to Integer
Intuition
The key insight is that Roman numerals are typically written from largest to smallest value, but there are special cases where a smaller value precedes a larger value (like IV for 4). In these cases, we need to subtract the smaller value from the larger one.
Approach
- Create a mapping of Roman numerals to their integer values
- Start from the end of the string and work backwards
- For each character:
- If the current value is less than the next value, subtract it from the result
- Otherwise, add it to the result
- Return the final result
Complexity
- Time complexity: O(n)
- Space complexity: O(1)
Keywords
- Hash Map
- String
- Math