Roman to Integer — LeetCode 13 Python Solution
- Problem
- #13
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is written as II in Roman numeral, just two ones added together.
Example
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
Python solution
class Solution:
def romanToInt(self, s: str) -> int:
d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
return sum((-1 if d[a] < d[b] else 1) * d[a] for a, b in pairwise(s)) + d[s[-1]]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(m) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 13. Roman to Integer is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 13. Roman to Integer?
- LeetCode 13. Roman to Integer is rated Easy on LeetCode.
- What is the time complexity of LeetCode 13. Roman to Integer?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 13. Roman to Integer?
- The Python solution on this page uses O(m) auxiliary space.
- What topics does LeetCode 13. Roman to Integer cover?
- LeetCode 13. Roman to Integer is tagged Hash Table, Math and String on LeetCode.