Roman to Integer: LeetCode Java Solution


๐ 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
Map
for clean symbol-value lookups.Detect subtractive combinations by comparing adjacent values.
One pass and done โ efficient and elegant!
Subscribe to my newsletter
Read articles from Aman Walke directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Aman Walke
Aman Walke
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.