DDSA Solutions

12. Integer to Roman

Time: O(1)
Space: O(1)
Advertisement

Intuition

Roman numerals use a fixed set of symbols (I=1, V=5, X=10, L=50, C=100, D=500, M=1000) plus six subtractive combinations (IV=4, IX=9, XL=40, XC=90, CD=400, CM=900). Greedily subtract the largest symbol value that fits, emitting its string each time. Since the symbol list is finite and ordered, a simple loop works.

Algorithm

  1. 1Build parallel arrays: values = [1000,900,500,400,100,90,50,40,10,9,5,4,1], symbols = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"].
  2. 2Iterate through each (value, symbol) pair.
  3. 3While num >= value: append symbol to result, subtract value from num.
  4. 4Return result.

Example Walkthrough

Input: num = 1994

  1. 1.1994 >= 1000 -> append "M", num=994.
  2. 2.994 >= 900 -> append "CM", num=94.
  3. 3.94 >= 90 -> append "XC", num=4.
  4. 4.4 >= 4 -> append "IV", num=0.

Output: "MCMXCIV"

Common Pitfalls

  • Include the subtractive cases (4, 9, 40, 90, 400, 900) in the value table - do not try to detect them dynamically.
12.cs
C#
// Approach: Greedy with sorted value/symbol pairs. Repeatedly subtract the
// largest value that fits and append its corresponding symbol.
// Time: O(1) Space: O(1)

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

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < values.Length; i++)
        {
            if (num == 0)
                break;

            while (num >= values[i])
            {
                num -= values[i];
                sb.Append(symbols[i]);
            }
        }

        return sb.ToString();
    }
}
Advertisement
Was this solution helpful?