Roman to Integer - Leetcode Solution


💡 Step-by-Step Thought Process

  1. Understand the problem: Convert a Roman numeral string s to its integer value.
  2. Create a dictionary d mapping Roman numerals to their values: I=1, V=5, X=10, L=50, C=100, D=500, M=1000.
  3. Initialize a variable summ to 0 to store the total value and an index i to 0.
  4. While i is less than the length n of s:
    • If i < n-1 and the value of s[i] is less than s[i+1], subtract s[i]’s value from s[i+1]’s value, add the result to summ, and increment i by 2.
    • Otherwise, add s[i]’s value to summ and increment i by 1.
  5. Return summ as the integer value.

Code Solution


                

                

                

                

Detailed Explanation

Detailed Explanation: Roman to Integer

The Roman to Integer problem asks you to take a string written in Roman numerals and convert it into an integer value. Roman numerals were used in ancient Rome and are composed of letters representing certain base values. This task involves interpreting those characters correctly and handling specific patterns where subtraction is used instead of addition.

Understanding Roman Numerals

Roman numerals use seven different symbols:

  • I = 1
  • V = 5
  • X = 10
  • L = 50
  • C = 100
  • D = 500
  • M = 1000

Normally, these symbols are added from left to right. For example, "VI" means 5 + 1 = 6. However, if a smaller symbol appears before a larger one, it is subtracted. For example, "IV" means 5 - 1 = 4.

How the Algorithm Works

The solution involves scanning the input string from left to right while checking each character and the one after it (if it exists). We use a dictionary to map each Roman numeral to its integer value. Then, during the scan:

  • If the current character represents a value smaller than the next one, we subtract it.
  • Otherwise, we simply add the current character's value.

Example Walkthrough

Consider the input "MCMXCIV". We can break it down like this:

M  = 1000
CM = 900  (100 before 1000, so subtract)
XC = 90   (10 before 100, subtract)
IV = 4    (1 before 5, subtract)
Total = 1000 + 900 + 90 + 4 = 1994
  

Pseudocode

map = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 }
sum = 0
i = 0

while i < s.length:
if i + 1 < s.length and map[s[i]] < map[s[i+1]]:
    sum += map[s[i+1]] - map[s[i]]
    i += 2
else:
    sum += map[s[i]]
    i += 1

return sum
  

Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the input string.
  • Space Complexity: O(1), since the Roman numeral map is constant in size.

Summary

To convert a Roman numeral to an integer, we loop through the string while using a simple rule: subtract if the current numeral is smaller than the next; otherwise, add it. This approach covers all valid Roman numeral strings and runs efficiently in linear time.

Get Personalized Support at AlgoMap Bootcamp 💡