Roman to Integer: LeetCode Java Solution

I'm a tech enthusiast who loves building backend systems that just work — clean, scalable, and efficient. I've worked with microservices, Spring Boot, Azure, and APIs, and I enjoy digging into root causes and making systems better. Whether it's writing clean code, reviewing it, or managing deployments with DevOps tools, I'm always up for the challenge. I like working in collaborative environments where I can learn, share, and grow alongside smart people.
👋 Introduction
Roman numerals were once the universal language of counting — from ancient Rome to modern programming puzzles. In this post, we’ll dive into LeetCode Problem #13: Roman to Integer, decode the logic, and implement a clean Java solution.
🧩 Problem Statement
Given a Roman numeral, convert it to an integer.
Roman numerals are represented by seven symbols:
| Symbol | Value |
| I | 1 |
| V | 5 |
| X | 10 |
| L | 50 |
| C | 100 |
| D | 500 |
| M | 1000 |
But there’s a twist:
Some numbers use subtractive notation:
IV= 4 → 5 - 1IX= 9 → 10 - 1XL= 40 → 50 - 10XC= 90 → 100 - 10CD= 400 → 500 - 100CM= 900 → 1000 - 100
🔍 Examples
Input: "III"
Output: 3
Input: "LVIII"
Output: 58
Explanation: L = 50, V = 5, III = 3
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4
🧠 Approach: Look Ahead and Subtract if Needed
🎯 Idea:
Start from the left of the Roman numeral.
If the current symbol is smaller than the next symbol, subtract its value.
Otherwise, add it.
🗺️ Strategy:
Use a
Map<Character, Integer>to store Roman symbol values.Traverse the string, comparing each character with the one after it.
Apply subtraction rule where applicable.
💻 Java Code
public class RomanToInteger {
public int romanToInt(String s) {
Map<Character, Integer> romanMap = new HashMap<>();
romanMap.put('I', 1);
romanMap.put('V', 5);
romanMap.put('X', 10);
romanMap.put('L', 50);
romanMap.put('C', 100);
romanMap.put('D', 500);
romanMap.put('M', 1000);
int result = 0;
int n = s.length();
for (int i = 0; i < n; i++) {
int current = romanMap.get(s.charAt(i));
// Check if there's a next character and it's larger
if (i + 1 < n && current < romanMap.get(s.charAt(i + 1))) {
result -= current; // Subtract if smaller than the next
} else {
result += current;
}
}
return result;
}
}
🧮 Time and Space Complexity
| Complexity | Value |
| ⏱️ Time | O(n) — one pass through the string |
| 🧠 Space | O(1) — fixed map size (7 symbols) |
✅ Summary
This problem is a great exercise in applying domain rules (Roman numeral logic) in code. Key takeaways:
Use a
Mapfor clean symbol-value lookups.Detect subtractive combinations by comparing adjacent values.
One pass and done — efficient and elegant!



