Roman to Integer - Problem

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

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 string s, convert it to an integer.

Input & Output

Example 1 — Basic Roman Numeral
$ Input: s = "III"
Output: 3
💡 Note: III = 3 (simple addition: 1 + 1 + 1 = 3)
Example 2 — Subtraction Case
$ Input: s = "IV"
Output: 4
💡 Note: IV = 4 (subtraction case: I before V means 5 - 1 = 4)
Example 3 — Mixed Operations
$ Input: s = "MCMXC"
Output: 1990
💡 Note: M = 1000, CM = 900 (1000-100), XC = 90 (100-10), so 1000 + 900 + 90 = 1990

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]

Visualization

Tap to expand
Roman to Integer Conversion INPUT Roman String s: I I I [0] [1] [2] Hash Map: I --> 1 V --> 5 X --> 10 L --> 50 C --> 100 D --> 500 M --> 1000 ALGORITHM STEPS 1 Initialize result = 0, prev = 0 2 Scan Right-to-Left Process from index 2 to 0 3 Compare Values If curr < prev: subtract Else: add to result 4 Update Previous prev = curr value Trace for "III": i=2: I=1, 1>=0 --> +1, res=1 i=1: I=1, 1>=1 --> +1, res=2 i=0: I=1, 1>=1 --> +1, res=3 Final: 3 FINAL RESULT Roman Input: III Integer Output: 3 OK - Verified! I + I + I = 1+1+1 = 3 Key Insight: Processing RIGHT-TO-LEFT allows easy subtraction detection: if current value is LESS than previous, subtract it (e.g., IV = 5-1 = 4). Otherwise, add it. This handles all six subtraction cases elegantly without special case checks. Time: O(n), Space: O(1) with fixed hash map. TutorialsPoint - Roman to Integer | Hash Map Right-to-Left Approach
Asked in
Facebook 35 Amazon 28 Microsoft 22 Google 18
219.7K Views
High Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen