DSA

Roman to Int or vice versa

Covers: Roman to Int, Int to Roman. Optimal — Time O(N), Space O(1).

August 8, 2026

Practice Link Roman to Int, Int to Roman

Roman to Int#

Scan left to right comparing each symbol to the next. In Roman numerals, a smaller value placed before a larger one means subtraction (e.g., IV = 4). So if table[s[i]] < table[s[i+1]], subtract s[i]'s value; otherwise add it. Always add the last character unconditionally since there is no character to its right to compare against. A single pass over the string gives O(n) time.

cpp
class Solution {
public:
    int romanToInt(string s) {
        if(s.length()==0)
            return 0;
        
        unordered_map<char, int> table = {
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000}
        };
        int res =0;
        for(int i=0;i<s.length()-1;i++)
        {
            if(table[s[i]] < table[s[i+1]])
                res -= table[s[i]];
            else
                res += table[s[i]];
        }
        res += table[s.back()];
        return res;
    }
};

Time Complexity: O(N)

Space COmplexity: O(1)

Int to Roman#

Use a greedy approach with a lookup table of value-symbol pairs in descending order (including subtractive combinations like 900=CM, 400=CD, etc.). Repeatedly subtract the largest value that fits into num and append the corresponding symbol to the result. Because Roman numerals are represented with the largest values first, always taking the largest fitting value produces a valid representation. Iterate until num reaches 0.

cpp
class Solution {
public:
    string intToRoman(int num) {
        vector<int> values =    {1000, 900, 500, 400, 100, 90,  50,  40,  10, 9,   5,  4,  1};
        vector<string> symbols ={"M",  "CM","D", "CD","C","XC","L", "XL","X","IX","V","IV","I"};

        string result = "";
        for(int i=0;i<values.size();i++)
        {
            while(num >= values[i])
            {
                result += symbols[i];
                num -= values[i];
            }
        }
        return result;
    }
};