Member-only story
Coding Interview Prep: Roman to Integer — JavaScript Solution
Solution
/*
Time Complexity: O(n)
Space Complexity: O(n)
Runtime: 69 ms
*/
var romanToInt = function(s) {
const sym = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
let result = 0;
for (let i = 0; i < s.length; i++) {
console.log(s[i])
const cur = sym[s[i]];
const next = sym[s[i + 1]];
if (cur < next) {
result += next - cur;
i++;
} else {
result += cur;
}
}
return result;
};
Explanation
To create this problem, we need to create a hash table. The characters will correspond to the value of the character. The for loop will loop through each character of the parameter string. For each iteration, we will check if the current value is greater than the next one. If it is, then we add to the res variable. If the current value is less than the next value, then we subtract the next value with the current value. Then we will increase the iteration i by 1. Once the for loop has iterated through each element, the result number will be the output.
This solution has O(n) time complexity since there is 1 for loop that iterates through all elements in the array. The space complexity is O(n) because of the hasmap that has been created.