Roman to Integer

Easy Simulation

Problem

Given a string s representing a Roman numeral, return its integer equivalent.

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

Example

Input: s = "MCMXCIV"
Output: 1994

The algorithm processes the string from right to left. Starting with 'V' (5), it adds 5 to total. Next, 'I' (1) is less than previous 'V' (5), so it subtracts 1, resulting in total 4. Then 'C' (100) is greater than previous 'I' (1), so it adds 100, total 104. Next 'X' (10) is less than 'C' (100), so subtract 10, total 94. Then 'M' (1000) is greater than 'X' (10), add 1000, total 1094. Next 'C' (100) is less than 'M' (1000), subtract 100, total 994. Finally 'M' (1000) is greater than 'C' (100), add 1000, total 1994. This stepwise addition and subtraction based on relative values correctly converts the Roman numeral.

Approach

Straightforward Solution

A naive approach would scan left to right, checking pairs of characters to decide whether to add or subtract. This requires careful lookahead and can be error-prone.

Core Observation

Roman numerals are generally additive, but when a smaller numeral precedes a larger one, it indicates subtraction. This means the value of each symbol depends on its relative position to the next symbol.

Path to Optimal

Reversing the string and scanning from right to left simplifies the logic: if the current numeral is less than the previous one seen, subtract it; otherwise, add it. This eliminates the need for lookahead and naturally encodes the subtraction rule.

Optimal Approach

Use a hash map to map Roman symbols to their integer values. Iterate over the reversed string, maintaining the previous numeral's value. For each character, compare its value to the previous; if smaller, subtract it from total, else add it. Update previous value accordingly. Return the accumulated total at the end.

Time

O(n)

The algorithm iterates through the input string once, performing constant-time operations per character.

Space

O(1)

The hash map has a fixed size of 7 entries, and only a few integer variables are used, resulting in constant auxiliary space.

Pattern Spotlight

Simulation (Stateful Iteration with Relative Comparison)

When a problem involves interpreting a sequence with context-dependent values, simulate the process by iterating with a state variable that tracks the previous element, enabling local decisions that collectively produce the global result.

Solution

1class Solution:
2 def romanToInt(self, s: str) -> int:
3 roman_value = {
4 "I": 1,
5 "V": 5,
6 "X": 10,
7 "L": 50,
8 "C": 100,
9 "D": 500,
10 "M": 1000,
11 }
12
13 total = 0
14 previous_value = 0
15
16 for char in reversed(s):
17 current_value = roman_value[char]
18
19 if current_value < previous_value:
20 total -= current_value
21 else:
22 total += current_value
23
24 previous_value = current_value
25
26 return total

Step-by-Step Solution

1

Map Roman Symbols to Integer Values

3roman_value = {
4 "I": 1,
5 "V": 5,
6 "X": 10,
7 "L": 50,
8 "C": 100,
9 "D": 500,
10 "M": 1000,
11}

Objective

To create a constant-time lookup for the integer value of each Roman numeral character.

Key Insight

A fixed hash map from Roman symbols to integers enables O(1) access to each symbol's value, which is essential for efficient iteration and comparison. This mapping encodes the fundamental Roman numeral values and is the foundation for the conversion logic.

Interview Quick-Check

Core Logic

The hash map provides direct access to symbol values, enabling the algorithm to quickly determine whether to add or subtract.

Common Pitfalls & Bugs

Forgetting to include all Roman symbols or mistyping values leads to incorrect conversions.

2

Iterate Over the Roman Numeral in Reverse to Accumulate Total

13total = 0
14previous_value = 0
16for char in reversed(s):
17 current_value = roman_value[char]
19 if current_value < previous_value:
20 total -= current_value
21 else:
22 total += current_value
24 previous_value = current_value

Objective

To traverse the string from right to left, deciding whether to add or subtract each numeral's value based on its relation to the previous numeral.

Key Insight

By iterating in reverse, the algorithm compares each numeral's value to the previously processed numeral. If the current value is less than the previous, it must be subtracted; otherwise, it is added. This approach elegantly encodes the Roman numeral subtraction rule without complex lookahead logic.

Interview Quick-Check

Core Logic

The key logic is the comparison between current and previous numeral values to decide addition or subtraction, which correctly interprets Roman numeral rules.

State & Boundaries

Initialize previous_value to 0 to ensure the first numeral is always added.

Common Pitfalls & Bugs

Incorrectly updating previous_value or reversing the string can lead to wrong results.

3

Return the Computed Integer Total

26return total

Objective

To output the final integer value after processing all Roman numerals.

Key Insight

Returning the accumulated total completes the conversion. The total reflects the sum of all additions and subtractions determined by the relative values of the numerals, ensuring correctness.

Interview Quick-Check

Core Logic

Returning the total after the loop provides the final integer representation of the Roman numeral.

Line Analysis

This solution has 1 Critical line interviewers watch for.

Line 19 Critical
if current_value < previous_value:

Check if current value is less than previous value to decide subtraction.

This conditional is the core of the Roman numeral conversion logic, correctly identifying when to subtract a numeral based on its relative value to the previous numeral, enabling accurate interpretation of subtractive notation.

Line 3 Core
roman_value = {

Initialize a hash map mapping Roman numerals to their integer values.

This mapping is essential for constant-time retrieval of each symbol's value, enabling efficient conversion logic.

Line 16 Core
for char in reversed(s):

Iterate over the input string in reverse order.

Reversing the iteration simplifies the subtraction logic by comparing each numeral to the one on its right in the original string.

Line 22 Core
total += current_value

Update previous_value to current_value for next iteration comparison.

Updating previous_value maintains the correct reference for the subtraction decision in the next iteration.

Line 26 Core
return total

Return the final computed integer total.

Returning the accumulated total provides the correct integer representation of the Roman numeral input.

Line 14 Core
previous_value = 0

Initialize previous_value to zero for comparison.

Setting previous_value to zero ensures the first numeral is added, establishing the baseline for subtraction logic.

Line 17 Core
current_value = roman_value[char]

Retrieve the integer value of the current Roman numeral character.

Mapping the character to its integer value is necessary for the addition or subtraction decision.

Line 20 Core
total -= current_value

Subtract current value from total if condition is met.

Subtracting here implements the subtractive notation rule, adjusting the total accordingly.

Line 21 Core
else:

Add current value to total if condition is not met.

Adding here handles the standard additive case for Roman numerals.

Line 13 Standard
total = 0

Initialize total accumulator to zero.

Starting point for summing the converted integer value.

Line 4 Standard
"I": 1,

Map 'I' to 1.

Defines the smallest Roman numeral value, foundational for subtraction logic.

Line 5 Standard
"V": 5,

Map 'V' to 5.

Represents the next Roman numeral value, used in additive and subtractive combinations.

Line 6 Standard
"X": 10,

Map 'X' to 10.

Key numeral for tens place, critical for subtraction cases like 'IX' and 'XL'.

Line 7 Standard
"L": 50,

Map 'L' to 50.

Represents the 50 value, used in larger numeral combinations.

Line 8 Standard
"C": 100,

Map 'C' to 100.

Hundreds place numeral, important for subtractive pairs like 'CD' and 'CM'.

Line 9 Standard
"D": 500,

Map 'D' to 500.

Represents 500, used in additive and subtractive contexts.

Line 10 Standard
"M": 1000,

Map 'M' to 1000.

Largest standard Roman numeral, critical for thousands place.

Line 11 Basic
}

Close the hash map definition.

Completes the mapping structure, enabling lookups in the main loop.

Line 24 Basic
previous_value = current_value

End of the for loop iteration.

Marks the completion of processing for the current character before moving to the next.

Test Your Understanding

Why does iterating from right to left and comparing the current numeral to the previous one simplify the conversion logic?

Because Roman numerals subtract when a smaller value precedes a larger one, scanning from right to left lets us compare each numeral to the one on its right (previous in iteration). If the current is smaller, it should be subtracted; otherwise, added. This approach avoids lookahead and directly encodes the subtraction rule.

Related Problems

Simulation pattern

Don't just read it. Drill it.

Reconstruct Roman to Integer from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Roman to Integer drill

or drill a free problem