Roman to Integer
Conditional Traversal / Hash Map LookupSolved Nov 7, 2025
Asked at 12 companies
7 recent
- IBM
- tcs
- Bloomberg
- Microsoft
- Meta
- Amazon
- AMD
- Yahoo
- Warnermedia
+2 moreShow fewer
- Virtusa
- Tinkoff
Community-reported · source · updated 2026-11-18. ● asked in the last 6 months.
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 110 pointsSolved (Easy) 0/20Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Watch the concept video if the pattern is new to you.
Step 2
Try it on paper
5–10 minutes, no code yet
ProblemProblem statementGiven a Roman numeral represented by the characters I, V, X, L, C, D, and M, convert it to an integer. The complexity lies in handling the subtraction rule where a smaller value precedes a larger one (e.g., IV = 4, CM = 900).ReadHide
Problem Description
Given a Roman numeral represented by the characters I, V, X, L, C, D, and M, convert it to an integer. The complexity lies in handling the subtraction rule where a smaller value precedes a larger one (e.g., IV = 4, CM = 900).
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Iterate through the string from left to right. If the current symbol's value is less than the next symbol's value, subtract it; otherwise, add it.
Approaches
1. Left-to-Right Conditional Traversal (Optimal) - O(N) ⭐
Idea: Process the string in a single pass. The crucial logic is to look ahead:
- Use a Hash Map to store the integer value for each Roman symbol (I=1, V=5, etc.).
- Iterate from
i=0up toN-2. - If
Value(S[i]) < Value(S[i+1]), subtractValue(S[i])from the total. - Otherwise, add
Value(S[i])to the total. - Always add the value of the final character
S[N-1].
2. Right-to-Left Traversal (Alternative Optimal) - O(N)
Idea: This is often considered cleaner. Start the iteration from the rightmost character.
- Initialize the total with the value of the last character.
- Iterate backward (
i=N-2down to 0). - If
Value(S[i]) < Value(S[i+1]), subtractValue(S[i])(subtraction case). - Otherwise, add
Value(S[i])(addition case).
Time: O(N)
Space: O(1) (The Hash Map size is constant, 7 entries).
Solution code
import sys
class Solution:
# O(N) Time, O(1) Space - Right-to-Left Traversal (Cleanest Optimal)
def romanToInt_optimal(self, s: str) -> int:
roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
# Start with the value of the last character
total += roman_map[s[-1]]
# Iterate from the second-to-last character backward
for i in range(len(s) - 2, -1, -1):
current_val = roman_map[s[i]]
prev_val = roman_map[s[i+1]]
if current_val < prev_val:
total -= current_val
else:
total += current_val
return total
# Brute Force: O(N) Time, O(1) Space - Left-to-Right Check
def romanToInt_brute(self, s: str) -> int:
roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
N = len(s)
for i in range(N):
current_val = roman_map[s[i]]
if i < N - 1:
next_val = roman_map[s[i+1]]
# Check for the subtraction case (IV, IX, XL, etc.)
if current_val < next_val:
total -= current_val
continue # Skip addition, subtract and move to next char
# Default case: add the value
total += current_val
return total
def solve(self):
try:
s = sys.stdin.readline().strip()
except:
return
result = self.romanToInt_optimal(s)
print(result)
if __name__ == "__main__":
Solution().solve()Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
- Community solutions on LeetCode ↗ for many more versions, in many languages. Read them after you've solved it.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language