Roman to Integer

(#13), Easy

Category: String, Hash Table, Math

Problem Statement

Given a Roman numeral, convert it to an integer. 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 Roman numerals are usually written largest to smallest from left to right. However, in a few special cases, we subtract values — such as IV = 4 or IX = 9. You are given a string representing a Roman numeral. Convert it to the corresponding integer.

Examples

Input: s = "III"

Output: 3

Explanation: "III" = 1 + 1 + 1 = 3

Input: s = "LVIII"

Output: 58

Explanation: "L" = 50, "V" = 5, "III" = 3 → Total = 58

Input: s = "MCMXCIV"

Output: 1994

Explanation: "M" = 1000, "CM" = 900, "XC" = 90, "IV" = 4 → Total = 1994

Approach

Map-Based Iteration with Subtractive Pair Check

  • Create a map with values for single Roman symbols and subtractive pairs.
  • Initialize `intVal = 0` and start iterating over the string with index `i`.
  • Check if `s[i] + s[i+1]` forms a valid subtractive pair present in the map.
  • - If yes: add its value and move `i` forward by 2.
  • - Else: add value of single character `s[i]` and increment `i` by 1.
  • Repeat until end of string and return the final `intVal`.
// 🔹 JavaScript Implementation
var romanToInt = function (s) {
  const map = new Map([
    ["I", 1], ["V", 5], ["X", 10], ["L", 50],
    ["C", 100], ["D", 500], ["M", 1000],
    ["IV", 4], ["IX", 9], ["XL", 40], ["XC", 90],
    ["CD", 400], ["CM", 900]
  ]);

  let intVal = 0;
  for (let i = 0; i < s.length; ) {
    if (i + 1 < s.length && map.has(s[i] + s[i + 1])) {
      intVal += map.get(s[i] + s[i + 1]);
      i += 2;
    } else {
      intVal += map.get(s[i]);
      i++;
    }
  }
  return intVal;
};

console.log(romanToInt("III"));      // 3
console.log(romanToInt("LVIII"));    // 58
console.log(romanToInt("MCMXCIV"));  // 1994

Complexity

Time: O(n)

Space: O(1)

Watch Explanation

📊 Presentation (PPT)

📥 Download PPT

📎 Resources