EasyNo. 0013

Roman to Integer — LeetCode 13 Python Solution

Topics
Hash Table, Math, String
On a study list
Top Interview 150
Reading time
2 min

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

Example
Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

Python solution

PythonSolution
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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.