Roman to Integer Conversion in DSA Java - Time & Space Complexity
We want to know how the time to convert Roman numerals to integers grows as the input gets longer.
How does the number of steps change when the Roman numeral string gets bigger?
Analyze the time complexity of the following code snippet.
public int romanToInt(String s) {
int result = 0;
for (int i = 0; i < s.length(); i++) {
int value = valueOfRoman(s.charAt(i));
if (i + 1 < s.length() && value < valueOfRoman(s.charAt(i + 1))) {
result -= value;
} else {
result += value;
}
}
return result;
}
private int valueOfRoman(char c) {
switch(c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
This code converts a Roman numeral string to its integer value by checking each character and deciding whether to add or subtract its value.
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, so as many times as the string length.
As the Roman numeral string gets longer, the number of steps grows directly with its 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 in a straight line with input size; doubling the input doubles the work.
Time Complexity: O(n)
This means the time to convert grows directly with the length of the Roman numeral string.
[X] Wrong: "Because of the subtraction rule, the code might need to look ahead multiple characters, making it slower than linear."
[OK] Correct: The code only looks one character ahead at a time, so it still processes each character once, keeping the time linear.
Understanding this time complexity helps you explain how your solution scales and shows you can analyze simple loops well, a key skill in many coding problems.
"What if the code used recursion to process the string instead of a loop? How would the time complexity change?"
Practice
IX when converted to an integer?Solution
Step 1: Understand Roman numeral rules for subtraction
In Roman numerals, when a smaller numeral appears before a larger one, it is subtracted. Here, I (1) is before X (10), so 1 is subtracted from 10.Step 2: Calculate the integer value
10 - 1 = 9.Final Answer:
9 -> Option CQuick Check:
IX = 9 [OK]
- Adding values instead of subtracting
- Confusing IX with XI
- Ignoring subtraction rule
Solution
Step 1: Check correct Map initialization syntax in Java
Java requires using a concrete class like HashMap to create a Map instance. Then, use put() method to add key-value pairs.Step 2: Verify each option
Map map = new HashMap<>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); correctly uses new HashMap<>(), then map.put() calls. B uses Map.of with string keys ("I", etc.) causing type mismatch for Map<Character, Integer>. Options C and D use invalid syntax.Final Answer:
Map map = new HashMap<>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); -> Option DQuick Check:
Use HashMap and put() for map initialization [OK]
- Using invalid Map constructor
- Using map.add() instead of map.put()
- Trying to assign values with brackets
String s = "MCMXCIV";
int result = 0;
Map map = Map.of('I',1,'V',5,'X',10,'L',50,'C',100,'D',500,'M',1000);
for (int i = 0; i < s.length(); i++) {
int value = map.get(s.charAt(i));
if (i + 1 < s.length() && value < map.get(s.charAt(i + 1))) {
result -= value;
} else {
result += value;
}
}
System.out.println(result);Solution
Step 1: Understand the Roman numeral string and map values
The string "MCMXCIV" represents a Roman numeral. Map assigns values: M=1000, C=100, X=10, I=1, V=5.Step 2: Trace the loop and calculate result
Loop through each character:
- M(1000), next C(100): 1000 > 100, add 1000
- C(100), next M(1000): 100 < 1000, subtract 100
- M(1000), next X(10): 1000 > 10, add 1000
- X(10), next C(100): 10 < 100, subtract 10
- C(100), next I(1): 100 > 1, add 100
- I(1), next V(5): 1 < 5, subtract 1
- V(5), no next, add 5
Sum = 1000 - 100 + 1000 - 10 + 100 - 1 + 5 = 1994.Final Answer:
1994 -> Option BQuick Check:
MCMXCIV = 1994 [OK]
- Adding all values without subtraction
- Incorrectly subtracting when not needed
- Misreading character order
public int romanToInt(String s) {
Map map = Map.of('I',1,'V',5,'X',10,'L',50,'C',100,'D',500,'M',1000);
int result = 0;
for (int i = 0; i < s.length(); i++) {
int value = map.get(s.charAt(i));
if (i + 1 < s.length() && value > map.get(s.charAt(i + 1))) {
result -= value;
} else {
result += value;
}
}
return result;
}Solution
Step 1: Analyze the if condition logic
The code subtracts value when current value is greater than next. But Roman numerals subtract when current is less than next.Step 2: Identify the correct comparison operator
The condition should be value < map.get(next char) to subtract, not value > next value.Final Answer:
The comparison operator should be '<' instead of '>' in the if condition. -> Option AQuick Check:
Subtract when current < next [OK]
- Using wrong comparison operator
- Ignoring subtraction rule
- Assuming map initialization error
["XL", "IX", "MMXX"] to their integer values using Java. Which approach correctly handles this with minimal code duplication?Solution
Step 1: Identify the need for reusable code
Converting Roman numerals requires the same logic for each string. Writing a helper method avoids repeating code.Step 2: Use a loop to process the list
Loop through the list and call the helper method for each Roman numeral string to get its integer value.Final Answer:
Write a separate method to convert one Roman numeral to integer, then loop over the list calling this method for each element. -> Option AQuick Check:
Use helper method + loop for clean code [OK]
- Repeating conversion code for each string
- Ignoring code reuse principles
- Using incorrect logic for all elements
Ready to prove it?
Pass the test and this pattern moves unknown
