#13
Roman to Integer
EasyHash TableMathStringHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Hash Map)★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a hash map to store the values of Roman numerals and iterates through the string in a single pass. By checking the current numeral against the next one, we can efficiently decide whether to add or subtract its value.
⚙️
Algorithm
4 steps- 1Step 1: Create a mapping of Roman numeral characters to their integer values using a hash map.
- 2Step 2: Initialize a variable to hold the total value.
- 3Step 3: Iterate through the string from the end to the beginning.
- 4Step 4: For each character, check if the current value is less than the previous value. If it is, subtract it from the total; otherwise, add it.
solution.py15 lines
1# Full working Python code with comments
2
3def roman_to_integer(s: str) -> int:
4 roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
5 total = 0
6 prev_value = 0
7 for char in reversed(s):
8 value = roman_map[char]
9 if value < prev_value:
10 total -= value # Subtract if current value is less than previous
11 else:
12 total += value # Add otherwise
13 prev_value = value
14 return total
15ℹ
Complexity note: The time complexity is O(n) because we iterate through the string once. The space complexity is O(n) due to the hash map storing the Roman numeral values.
- 1The key observation is that Roman numerals follow a specific pattern where smaller values before larger values indicate subtraction. Recognizing this pattern allows for efficient conversion.
- 2Another important insight is that using a hash map for value lookups reduces the time complexity significantly, making the solution optimal.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.