Roman to Integer Conversion in DSA Javascript - Time & Space Complexity
We want to know how the time to convert a Roman numeral to an integer changes as the length of the Roman numeral grows.
How does the number of steps grow when the input string gets longer?
Analyze the time complexity of the following code snippet.
function romanToInt(s) {
const map = {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 = map[s[i]];
const next = map[s[i + 1]];
if (next && current < next) {
total -= current;
} else {
total += current;
}
}
return total;
}
This code converts a Roman numeral string to its integer value by checking each character and its next character.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop that goes through each character of the input string once.
- How many times: Exactly once for each character in the string (n times, where n is the string length).
As the Roman numeral string gets longer, the number of steps grows directly with the length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and additions/subtractions |
| 100 | About 100 checks and additions/subtractions |
| 1000 | About 1000 checks and additions/subtractions |
Pattern observation: The work grows evenly and directly with input size; doubling the input doubles the work.
Time Complexity: O(n)
This means the time to convert grows in a straight line with the length of the Roman numeral string.
[X] Wrong: "Because we check the next character inside the loop, the time complexity is O(n²)."
[OK] Correct: We only look one step ahead each time, so each character is visited once, not repeatedly.
Understanding how to analyze simple loops like this helps you explain your code clearly and shows you can reason about efficiency, a key skill in interviews.
"What if we changed the code to check pairs of characters at once instead of one by one? How would the time complexity change?"
Practice
Solution
Step 1: Understand Roman numeral rules
Roman numerals are added normally, but if a smaller numeral appears before a larger one, it is subtracted.Step 2: Apply addition and subtraction rules
For example, IV is 5 - 1 = 4, while VI is 5 + 1 = 6.Final Answer:
Add values of symbols, subtract if a smaller symbol is before a larger one -> Option BQuick Check:
Roman numeral rules = Add and subtract [OK]
- Always adding without subtraction
- Multiplying values incorrectly
- Ignoring order of symbols
romanMap?Solution
Step 1: Identify the data structure type
IfromanMapis a plain JavaScript object, access values using square brackets with the key as a string.Step 2: Choose correct syntax for object property access
UsingromanMap['V']correctly accesses the value for key 'V'.romanMap.get('V')is for Map objects, not plain objects.Final Answer:
romanMap['V'] -> Option AQuick Check:
Object property access = romanMap['V'] [OK]
- Using .get() on plain objects
- Using dot notation with string keys
- Calling object like a function
function romanToInt(s) {
const map = {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 = map[s[i]];
const next = map[s[i+1]] || 0;
if(current < next) {
total -= current;
} else {
total += current;
}
}
return total;
}
console.log(romanToInt('IX'));Solution
Step 1: Trace the loop for input 'IX'
For 'I' (1), next is 'X' (10), since 1 < 10, subtract 1 (total = -1). For 'X' (10), next is undefined (0), so add 10 (total = 9).Step 2: Calculate final total
Total after loop is 9, which is the integer value of 'IX'.Final Answer:
9 -> Option AQuick Check:
'IX' = 9 [OK]
- Adding all values without subtraction
- Ignoring next character check
- Off-by-one errors in loop
function romanToInt(s) {
const map = {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 = map[s[i]];
const next = map[s[i+1]] || 0;
if(current < next) {
total -= current;
} else {
total += current;
}
}
return total;
}Solution
Step 1: Analyze loop boundary
The loop runs from i = 0 to i <= s.length, which means it accesses s[s.length], an undefined index causing current to be undefined.Step 2: Correct loop condition
Changing loop condition to i < s.length prevents accessing out-of-bound index and avoids errors.Final Answer:
Loop condition should be i < s.length, not i <= s.length -> Option DQuick Check:
Loop boundary off-by-one error fixed [OK]
- Using <= instead of < in loops
- Wrong case for map keys
- Incorrect comparison operators
'MCMXCIV', what integer should the conversion function return?Solution
Step 1: Break down the Roman numeral 'MCMXCIV'
M = 1000, CM = 900 (1000 - 100), XC = 90 (100 - 10), IV = 4 (5 - 1).Step 2: Add all parts
1000 + 900 + 90 + 4 = 1994 total.Final Answer:
1994 -> Option CQuick Check:
'MCMXCIV' = 1994 [OK]
- Adding all numerals without subtraction
- Misreading subtractive pairs
- Confusing similar numerals
Ready to prove it?
Pass the test and this pattern moves unknown
