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

TanishiTanishi
2 min read

๐Ÿ—“๏ธ Date: July 29, 2025

๐Ÿ“Œ Challenge:

๐Ÿ”ข Problem: Roman to Integer โ€“ LeetCode #13 (Easy)
๐ŸŽฏ Topic: Strings, Hash Map, Maths

๐Ÿ’ป Platform: Leetcode


๐Ÿ”— Table of Contents


โœ… 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:

MetricValue
Problems Solved1
Topics CoveredHashMap, String Parsing
Tools UsedC++
Next FocusStack-based problems
Day5 / 30

๐Ÿ—‚๏ธ Tags:

#leetcode #43DaysChallenge #string #hashmap #dsa #cpp #codingjourney

0
Subscribe to my newsletter

Read articles from Tanishi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tanishi
Tanishi