Explorer
Data Structures & Algorithms

Convert a Roman numeral string to an integer.

Problem Statement

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Given a roman numeral, convert it to an integer.

Examples

Input: s = "III"

Output: 3

Explanation: Converting the Roman numeral values yields integer 3.

Input: s = "LVIII"

Output: 58

Explanation: Converting the Roman numeral values yields integer 58.

Input: s = "MCMXCIV"

Output: 1994

Explanation: Converting the Roman numeral values yields integer 1994.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Map Roman symbols I, V, X, L, C, D, M to their numeric equivalents. šŸ’” Hint 2: If a smaller symbol appears before a larger symbol (e.g. IV, IX, XL, XC, CD, CM), subtract its value. šŸ’” Hint 3: Otherwise, add its value to the running total.

Editorial & Approach

Problem Overview & Intuition

In Roman numerals, smaller values preceding larger values indicate subtraction (e.g., IV = 4, IX = 9). Otherwise, values are additive. Comparing values[s[i]] with values[s[i+1]] solves the conversion in a single linear pass.

Step-by-Step Approach

  1. Create symbol map for I=1, V=5, X=10, L=50, C=100, D=500, M=1000.
  2. Iterate i from 0 to s.length - 1.
  3. If values[s[i]] < values[s[i + 1]], subtract values[s[i]] from total.
  4. Else add values[s[i]] to total.
  5. Return total.

Optimal Implementation (JavaScript)

function romanToInt(s) {
  const values = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
  let total = 0;
  for (let i = 0; i < s.length; i++) {
    const current = values[s[i]];
    const next = values[s[i + 1]] || 0;
    if (current < next) {
      total -= current;
    } else {
      total += current;
    }
  }
  return total;
}

Complexity Analysis

Time Complexity O(N) — length of Roman numeral string (<= 15 characters).
Space Complexity O(1) — constant size dictionary.

Edge Cases & Corner Traps Handled

  • Single symbol: "I" -> 1, "M" -> 1000.
  • Subtractive combinations: "IV", "IX", "XL", "XC", "CD", "CM".

Roman to Integer

Medium
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Given a roman numeral, convert it to an integer.
Example Scenarios
1Example 1
Input: s = "III"
Output: 3
Explanation:

Converting the Roman numeral values yields integer 3.

2Example 2
Input: s = "LVIII"
Output: 58
Explanation:

Converting the Roman numeral values yields integer 58.

3Example 3
Input: s = "MCMXCIV"
Output: 1994
Explanation:

Converting the Roman numeral values yields integer 1994.

Editor
Loading Editor...
s =
"III"
Output:Click "Run" above to execute and verify your code here.
3