EasyNo. 0013
Roman to Integer — LeetCode 13 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Hash Table, Math, String
- On a study list
- Top Interview 150
- 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
- Time
- O(n)
- Space · auxiliary
- O(m)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0012 | Integer to Roman | Medium |
| 0166 | Fraction to Recurring Decimal | Medium |
| 0423 | Reconstruct Original Digits from English | Medium |
| 2019 | The Score of Students Solving Math Expression | Hard |
| 2266 | Count Number of Texts | Medium |
| 2514 | Count Anagrams | Hard |
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.