Taro Logo

Roman to Integer

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+27
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.8K views
Topics:
Strings

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

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

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

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

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].

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the Roman numeral string s that we need to handle?
  2. Can I assume the input string is always a valid Roman numeral, or do I need to include validation logic for malformed inputs?
  3. What should the function return if the input string is empty or null?
  4. Are we guaranteed that the input will only contain standard uppercase Roman numeral characters (I, V, X, L, C, D, M), or could lowercase characters or invalid symbols be present?
  5. What integer data type should the function return, and should we worry about potential integer overflow for extremely large Roman numerals?

Brute Force Solution

Approach

Imagine you are given a long string of Roman numeral symbols and you need to calculate its total value by exhaustively examining every possible combination of adjacent symbols. The brute force approach involves breaking down the entire string into all possible overlapping pairs and single letters, testing various ways to group them, and manually evaluating every conceivable combination until the correct total is tallied.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the entire sequence of Roman numeral symbols from left to right.
  2. Exhaust every possible way to group the symbols, considering both single symbols standing alone and pairs of adjacent symbols sitting side by side.
  3. For each possible grouping you consider, check if the first symbol in a pair is smaller than the second symbol, which represents a subtraction case.
  4. If it is a subtraction case, calculate the value of that specific pair by taking the difference between the two symbols.
  5. Otherwise, calculate the value by simply adding the values of the symbols together.
  6. Test all other alternative groupings and combinations across the entire string to see what values they produce.
  7. Sum up the values from your chosen grouping and keep track of this total while you verify it against other possible interpretations of the symbol string.

Code Implementation

def roman_to_integer(roman_string):
    symbol_values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}

    # We map every single symbol and adjacent pair to exhaustively evaluate all possible groupings
    all_possible_groupings = []

    string_index = 0
    while string_index < len(roman_string):
        if string_index + 1 < len(roman_string):
            pair_string = roman_string[string_index:string_index+2]
            all_possible_groupings.append(pair_string)
            string_index += 2
        else:
            single_string = roman_string[string_index]
            all_possible_groupings.append(single_string)
            string_index += 1

    accumulated_total = 0

    # We test each evaluated grouping to determine if subtraction or addition rules apply
    for current_group in all_possible_groupings:
        if len(current_group) == 2:
            first_value = symbol_values[current_group[0]]
            second_value = symbol_values[current_group[1]]
            if first_value < second_value:
                accumulated_total += (second_value - first_value)
            else:
                accumulated_total += (first_value + second_value)
        else:
            accumulated_total += symbol_values[current_group]

    # We return the exhaustive sum matching the required brute force interpretation logic
    return accumulated_total

Big(O) Analysis

Time Complexity
O(2ⁿ) – To exhaustively test every conceivable combination of adjacent symbols and overlapping pairs, the algorithm recursively branches to evaluate multiple grouping interpretations for the input string of length n. At each character position, the algorithm explores branching paths for both single characters and subtraction pairs, resulting in a binary-like expansion of choices across the entire sequence. This combinatorial exploration of all grouping permutations generates roughly 2ⁿ possible evaluation paths. Therefore, the total operations scale exponentially with the input size, which simplifies to Big O of 2ⁿ.
Space Complexity
O(1) – To calculate the total value of the Roman numeral string of length N, the algorithm only uses a few primitive variables like a running sum and a pointer to iterate through the characters. These fixed-size integer and character variables consume a constant amount of auxiliary memory regardless of how large the input string grows. There are no dynamic data structures, hash maps, or recursion stacks utilized during the evaluation of the symbol combinations. Therefore, the extra memory used by the algorithm remains constant, resulting in an optimal space complexity of O(1).

Optimal Solution

Approach

Instead of reading the Roman numeral from left to right and constantly second-guessing yourself, the optimal approach works backwards from right to left. By comparing each symbol to the one immediately to its right, you can instantly tell whether to add or subtract its value.

Here's how the algorithm would work step-by-step:

  1. Begin at the very end of the Roman numeral, looking at the last symbol.
  2. Write down the numeric value of that starting symbol as your current running total.
  3. Move one symbol to the left and check its value compared to the symbol immediately to its right.
  4. If the symbol you just landed on is worth less than the one to its right, subtract its value from your running total.
  5. If the symbol you just landed on is worth greater than or equal to the one to its right, add its value to your running total.
  6. Continue stepping backward through the entire sequence one symbol at a time, applying the same addition or subtraction rule.
  7. Once you reach the very first symbol and process it, your running total will contain the final correct number.

Code Implementation

def roman_to_integer(roman_numeral_string):
    roman_value_mapping = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    
    # Begin at the very end of the string to evaluate the last symbol first.
    last_character_index = len(roman_numeral_string) - 1
    running_total = roman_value_mapping[roman_numeral_string[last_character_index]]
    previous_symbol_value = running_total
    
    for character_index in range(len(roman_numeral_string) - 2, -1, -1):
        current_symbol_value = roman_value_mapping[roman_numeral_string[character_index]]
        
        # If a smaller value precedes a larger one, subtract it per Roman rules.
        if current_symbol_value < previous_symbol_value:
            running_total -= current_symbol_value
        else:
            # Otherwise, add the value when symbols are in descending or equal order.
            running_total += current_symbol_value
            
        previous_symbol_value = current_symbol_value
        
    return running_total

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the number of characters in the Roman numeral string. The algorithm uses a single loop to iterate backward from the last character to the first character exactly once. In each iteration, it performs a constant-time hash map lookup and a simple arithmetic comparison. This means the total operations scale linearly as n increases, which simplifies to O(n).
Space Complexity
O(1) – To implement this right-to-left evaluation, the algorithm only needs a few primitive variables to maintain the running total and track the previous value. These few variables occupy a constant amount of memory regardless of the length of the Roman numeral string. There are no auxiliary data structures, arrays, or recursive call stacks created that scale with the input. Therefore, the extra auxiliary space required remains strictly constant as the input size N grows.

Edge Cases

Empty string input
How to Handle:
Return zero immediately as an empty Roman numeral represents the value zero.
Single character string like I, V, or M
How to Handle:
The loop executes once and correctly returns the direct integer value mapped to that single character.
Maximum length valid Roman numeral string
How to Handle:
Iterate through the string in linear time O(n) which scales efficiently for any standard constraint size.
All identical characters like III or XXX
How to Handle:
Always add the values since no smaller value precedes a larger value to trigger subtraction.
Subtractive notation combinations like IV, IX, XL, XC, CD, CM
How to Handle:
Subtract the current character value from the total if its value is less than the next character value.
Mixed additive and subtractive sequences like MCMXCIV
How to Handle:
The lookahead comparison correctly handles alternating addition and subtraction rules at each step.
Inputs containing invalid characters not in the Roman numeral set
How to Handle:
A robust solution should throw an exception or return an error indicator when an unmapped character is encountered.
Integer overflow beyond standard limits
How to Handle:
Standard Roman numerals generally do not exceed 3999, which fits safely within standard integer types without overflow.
0/75 completed