Roman To Integer
Algorithm/HashTable
Intuition
The task is to convert a Roman numeral string into its corresponding integer value. The key to solving this problem efficiently is to traverse the input string and compare each symbol with the next to determine whether to add or subtract its value.
Approach
Below is the step-by-step breakdown of the approach:
- Create a Hash Map:
- Store Roman numeral symbols as keys and their corresponding integer values as values for constant-time lookups.
- Traverse the String:
- Iterate through the string from left to right.
- For each symbol
s[i]
, compare it with the next symbols[i + 1]
:- If
s[i]
is smaller thans[i + 1]
, subtract its value from the result (e.g.,"IV"
). - Otherwise, add its value to the result.
- If
- Return the Result:
- Once the traversal is complete, the accumulated result will be the integer value of the Roman numeral. Return the result.
Complexity
- Time complexity: , we traverse the input string once, where
n
is the length of the string. - Space complexity: , the hash map is of fixed size, and no additional space is required.