NLeetCode Solutions
ProblemsPatternsStatistics
© 2026 Created by Trịnh Minh Nhật
GitHubLeetCode
Related posts
  • 49. Group AnagramsMedium
  • 242. Valid AnagramEasy
  • 1. Two SumEasy
  • 7. Reverse IntegerMedium
  • 9. Palindrome NumberEasy

13. Roman to Integer

Easy
Hash TableMathString
Companies:
UberYahooFacebookMicrosoftBloomberg
Answered: Feb 22, 2026
View on LeetCode

Problem Description

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. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

Examples

Example 1

Input: s = "III"
Output: 3
Explanation:
III = 3.

Example 2

Input: s = "LVIII"
Output: 58
Explanation:
L = 50, V= 5, III = 3.

Example 3

Input: s = "MCMXCIV"
Output: 1994
Explanation:
M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints

  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M')
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

💡 Hints (1)


Solutions

Complexity Analysis

Time Complexity:O(n)

The algorithm iterates through the string once, so the time complexity is linear in the length of the input string.

Space Complexity:O(1)

The space complexity is constant because the size of the roman_dict is fixed and does not depend on the input size.

[Explain your approach here - describe the algorithm, intuition, and key insights]

Complexity Analysis

Time Complexity:O(n)

The algorithm iterates through the string once, so the time complexity is linear in the length of the input string.

Space Complexity:O(1)

The space complexity is constant because the size of the roman_dict is fixed and does not depend on the input size.

In this approach, we iterate through the string from front to back. For each character, we compare its value with the value of the next character. If the current character's value is less than the next character's value, it means we need to subtract the current character's value from the result (this accounts for cases like "IV" or "IX"). Otherwise, we simply add the current character's value to the result.

Complexity Analysis

Time Complexity:O(n)

The algorithm iterates through the string once, so the time complexity is linear in the length of the input string.

Space Complexity:O(1)

The space complexity is constant because the size of the roman_dict is fixed and does not depend on the input size.

In this approach, we use a while loop to iterate through the string. We check if the current character is less than the next character. If it is, we add the difference of the next character and the current character to the result and skip the next character by incrementing i by 2. If it is not, we simply add the value of the current character to the result and move to the next character by incrementing i by 1.

Conclusion

ApproachRatingTime ComplexitySpace ComplexityAdvantagesDisadvantages
Iterating from Back to Front
O(n)O(n)O(n)O(1)O(1)O(1)Intuitive subtraction logic when reading right-to-leftRequires explicit checks for each subtraction case
Iterating from Front to Back
O(n)O(n)O(n)O(1)O(1)O(1)Cleanest and most concise logic — simply compare current vs next valueNone
Iterating from Front to Back using a While Loop
O(n)O(n)O(n)O(1)O(1)O(1)Skips two characters at once for subtraction pairs, slightly fewer iterationsSlightly more complex loop control with manual index management

The optimal approach for this problem is Solution 2: Iterating from Front to Back, which achieves O(n)O(n)O(n) time complexity and O(1)O(1)O(1) space complexity. It uses the simplest logic: if the current value is less than the next value, subtract it. otherwise, add it. This makes the code concise and easy to understand.


Previous9. Palindrome Number
Next14. Longest Common Prefix
Related posts
  • 49. Group AnagramsMedium
  • 242. Valid AnagramEasy
  • 1. Two SumEasy
  • 7. Reverse IntegerMedium
  • 9. Palindrome NumberEasy
On this page
29 lines
1class Solution:
2 def romanToInt(self, s: str) -> int:
3 if not (1 <= len(s) <= 15):
4 raise ValueError("Input string length must be between 1 and 15.")
5
6 roman_dict = {
7 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000
8 }
9
10 # Validate that all characters in the input string are valid Roman numeral characters
11 if not set(s).issubset(roman_dict.keys()):
12 raise ValueError("Input string contains invalid Roman numeral characters.")
13
14 result = 0
15
16 # Iterate through the string from back to front
17 for i in range(len(s) - 1, -1, -1):
18 if i == len(s) - 1:
19 result += roman_dict[s[i]]
20 elif ( # Check for the special cases where subtraction is needed
21 (s[i] == "I" and s[i + 1] in ["V", "X"])
22 or (s[i] == "X" and s[i + 1] in ["L", "C"])
23 or (s[i] == "C" and s[i + 1] in ["D", "M"])
24 ):
25 result -= roman_dict[s[i]]
26 else:
27 result += roman_dict[s[i]]
28
29 return result
24 lines
1class Solution:
2 def romanToInt(self, s: str) -> int:
3 if not (1 <= len(s) <= 15):
4 raise ValueError("Input string length must be between 1 and 15.")
5
6 roman_dict = {
7 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000
8 }
9
10 # Validate that all characters in the input string are valid Roman numeral characters
11 if not set(s).issubset(roman_dict.keys()):
12 raise ValueError("Input string contains invalid Roman numeral characters.")
13
14 result = 0
15
16 # Iterate through the string and apply the Roman numeral rules
17 for i in range(len(s)):
18 # If the current numeral is less than the next numeral, subtract it from the result
19 if i < len(s) - 1 and roman_dict[s[i]] < roman_dict[s[i + 1]]:
20 result -= roman_dict[s[i]]
21 else:
22 result += roman_dict[s[i]]
23
24 return result
27 lines
1class Solution:
2 def romanToInt(self, s: str) -> int:
3 if not (1 <= len(s) <= 15):
4 raise ValueError("Input string length must be between 1 and 15.")
5
6 roman_dict = {
7 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000
8 }
9
10 # Validate that all characters in the input string are valid Roman numeral characters
11 if not set(s).issubset(roman_dict.keys()):
12 raise ValueError("Input string contains invalid Roman numeral characters.")
13
14 result = 0
15 i = 0
16
17 # Iterate through the string from left to right
18 while (i < len(s)):
19 # Check if the current character is less than the next character
20 if (i < len(s) - 1) and (roman_dict[s[i]] < roman_dict[s[i + 1]]):
21 result += roman_dict[s[i + 1]] - roman_dict[s[i]]
22 i += 2
23 else:
24 result += roman_dict[s[i]]
25 i += 1
26
27 return result