๐ Day 5 โ Teacher's Day Challenge | Roman to Integer | Hash Map + Subtraction Rule


๐๏ธ Date: July 29, 2025
๐ Challenge:
๐ข Problem: Roman to Integer โ LeetCode #13 (Easy)
๐ฏ Topic: Strings, Hash Map, Maths
๐ป Platform: Leetcode
๐ Table of Contents
Daily Summary
โ Problem Statement (Summary):
Convert a Roman numeral string to its corresponding integer.
Roman symbols and values:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Subtraction cases:
I before V or X โ 4, 9
X before L or C โ 40, 90
C before D or M โ 400, 900
๐งพ Example:
"III" โ 3
"LVIII" โ 58
"MCMXCIV" โ 1994
๐ง What I Learned Today:
Use a hash map for fast Roman symbol lookup.
Key logic: if current symbol value is less than the next, subtract it. Otherwise, add it.
This approach simplifies subtraction rules elegantly in a single loop.
๐งช Code (C++):
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> roman = {{'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 curr = roman[s[i]];
int next = (i + 1 < s.length()) ? roman[s[i + 1]] : 0;
if (curr < next) {
result -= curr;
} else {
result += curr;
}
}
return result;
}
};
๐ Time Complexity: O(n)
๐ฆ Space Complexity: O(1)
๐ธ LeetCode Submission Screenshot:
โ Key Takeaways:
Subtractive notation is the only tricky part (like
IV
,IX
,CM
).HashMap gives O(1) lookup for Roman values.
Always check the next character during traversal.
๐ Daily Summary:
Metric | Value |
Problems Solved | 1 |
Topics Covered | HashMap, String Parsing |
Tools Used | C++ |
Next Focus | Stack-based problems |
Day | 5 / 30 |
๐๏ธ Tags:
#leetcode #43DaysChallenge #string #hashmap #dsa #cpp #codingjourney
Subscribe to my newsletter
Read articles from Tanishi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
