Top Interview 150
Converting Roman numerals to integers involves understanding both their additive and subtractive notation rules. Letβs break down LeetCode 13: Roman to Integer and solve it step by step.
π Problem Description
Roman numerals are represented by seven symbols, each with a fixed value.
- Subtractive Rule: When a smaller numeral appears before a larger one, subtract the smaller numeral.
Given a Roman numeral string, return its integer equivalent.
π‘ Examples
Example 1
Input: s = "III"
Output: 3
Explanation: III = 3 (1 + 1 + 1).
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, IV = 4.
1994 = 1000 + 900 + 90 + 4.
π JavaScript Solution
To solve this problem, we use a mapping dictionary
for Roman symbols and traverse the string to calculate the integer.
Implementation
var romanToInt = function(s) {
const romanMap = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
};
let total = 0;
for (let i = 0; i < s.length; i++) {
const current = romanMap[s[i]];
const next = romanMap[s[i + 1]];
if (next && current < next) {
total -= current;
} else {
total += current;
}
}
return total;
};
π How It Works
- Map Roman Symbols: Use a dictionary to map Roman symbols to their values.
- Traverse the String: For each character:
- Add the value to the total if the current numeral is greater than or equal to the next.
- Subtract the value if the current numeral is smaller than the next (subtractive rule).
- Return the Total: After traversing the string, total holds the integer equivalent.
π Complexity Analysis
- > Time Complexity:
O(n)
, wheren
is the length of the string. We traverse the string once. - > Space Complexity:
O(1)
, as the mapping dictionary size is constant.
π Dry Run
Input: s = "MCMXCIV"
β¨ Pro Tips for Interviews
- Clarify constraints: Confirm that the Roman numeral input will always be valid (as per problem assumptions).
- Highlight efficiency: Emphasize
O(n)
time complexity and how the subtractive rule is handled efficiently. - Edge cases:
- Smallest numeral (
"I"
β1
). - Mixed additive and subtractive cases (
"XIV"
β14
).
- Smallest numeral (
π Learn More
Check out the full explanation and code walkthrough on my Dev.to post:
π Trapping Rain Water - JavaScript Solution
Whatβs your approach to solving this problem? Letβs discuss! π
Top comments (1)
Follow Me on GitHub π
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!