Roman to Integer Conversion in DSA C# - Time & Space Complexity
We want to know how the time to convert a Roman numeral to an integer changes as the input gets longer.
How does the number of steps grow when the Roman numeral string grows?
Analyze the time complexity of the following code snippet.
public int RomanToInt(string s) {
int total = 0;
for (int i = 0; i < s.Length; i++) {
int value = GetValue(s[i]);
if (i + 1 < s.Length && value < GetValue(s[i + 1])) {
total -= value;
} else {
total += value;
}
}
return total;
}
private int GetValue(char c) {
return c switch {
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
_ => 0
};
}
This code converts a Roman numeral string to its integer value by checking each character and deciding 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 (n times, where n is 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 evenly and directly with the input size.
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 of the subtraction checks, the code does extra loops or nested checks making it slower than linear."
[OK] Correct: The subtraction check is done inside the same single loop, so it does not add extra loops or multiply the work.
Understanding this linear time complexity helps you explain how your solution scales and why it is efficient for converting Roman numerals.
"What if we used recursion to process each character instead of a loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand Roman numeral rules
Roman numerals add values unless a smaller symbol is before a larger one, then subtract.Step 2: Apply rule to conversion
When converting, add values normally but subtract when a smaller symbol precedes a larger one.Final Answer:
Add values of symbols, subtract if a smaller symbol is before a larger one -> Option CQuick Check:
Roman numeral conversion rule = Add values of symbols, subtract if a smaller symbol is before a larger one [OK]
- Multiplying values instead of adding/subtracting
- Ignoring subtraction rule
- Adding all values without checking order
Solution
Step 1: Identify correct dictionary types
Roman numerals are characters mapped to integer values, so Dictionary is correct.Step 2: Check initialization syntax
Initialization with curly braces and pairs like {'I', 1} is correct syntax in C#.Final Answer:
var map = new Dictionary { {'I', 1}, {'V', 5} }; -> Option AQuick Check:
Dictionary with correct pairs = var map = new Dictionary { {'I', 1}, {'V', 5} }; [OK]
- Swapping key and value types
- Using string keys instead of char
- Incorrect initialization syntax
string s = "IX";
var map = new Dictionary { {'I', 1}, {'V', 5}, {'X', 10} };
int result = 0;
for (int i = 0; i < s.Length; i++) {
if (i + 1 < s.Length && map[s[i]] < map[s[i + 1]]) {
result -= map[s[i]];
} else {
result += map[s[i]];
}
}
Console.WriteLine(result);Solution
Step 1: Analyze loop and conditions
For 'IX', at i=0: 'I' < 'X' so subtract 1; at i=1: add 10.Step 2: Calculate result
result = -1 + 10 = 9.Final Answer:
9 -> Option AQuick Check:
IX = 9 [OK]
- Adding all values without subtraction
- Off-by-one errors in loop
- Incorrect dictionary values
var map = new Dictionary { {'I', 1}, {'V', 5}, {'X', 10} };
int result = 0;
for (int i = 0; i < s.Length - 1; i++) {
if (map[s[i]] < map[s[i + 1]]) {
result -= map[s[i]];
} else {
result += map[s[i]];
}
}
result += map[s[s.Length - 1]];
Console.WriteLine(result);Solution
Step 1: Check variable declarations
The variable 's' is used but not declared or initialized, causing a compile error.Step 2: Verify loop and dictionary usage
Loop and dictionary usage are correct; only 's' is missing.Final Answer:
Missing initialization of string s -> Option BQuick Check:
Undefined variable s causes error = Missing initialization of string s [OK]
- Forgetting to declare input string
- Incorrect loop range causing index errors
- Wrong dictionary key types
"MCMXCIV", what integer does the following C# code output?string s = "MCMXCIV";
var map = new Dictionary {
{'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++) {
if (i + 1 < s.Length && map[s[i]] < map[s[i + 1]]) {
result -= map[s[i]];
} else {
result += map[s[i]];
}
}
Console.WriteLine(result);Solution
Step 1: Break down the Roman numeral "MCMXCIV"
M=1000, CM=900, XC=90, IV=4; sum = 1000 + 900 + 90 + 4.Step 2: Calculate total value using code logic
Code subtracts smaller before larger and adds others: 1000 - 100 + 1000 - 10 + 100 - 1 + 5 = 1994.Final Answer:
1994 -> Option DQuick Check:
MCMXCIV = 1994 [OK]
- Adding all values without subtraction
- Misreading compound numerals like CM or XC
- Incorrect dictionary values
Ready to prove it?
Pass the test and this pattern moves unknown
