Taro Logo

Integer to Roman

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+30
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.6K views
Topics:
ArraysStringsGreedy Algorithms

Seven different symbols represent Roman numerals with the following values:

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:

  • If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.
  • If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol, for example, 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM).
  • Only powers of 10 (I, X, C, M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form.

Given an integer, convert it to a Roman numeral.

Example 1:

Input: num = 3749

Output: "MMMDCCXLIX"

Explanation:

3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)
 700 = DCC as 500 (D) + 100 (C) + 100 (C)
  40 = XL as 10 (X) less of 50 (L)
   9 = IX as 1 (I) less of 10 (X)
Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places

Example 2:

Input: num = 58

Output: "LVIII"

Explanation:

50 = L
 8 = VIII

Example 3:

Input: num = 1994

Output: "MCMXCIV"

Explanation:

1000 = M
 900 = CM
  90 = XC
   4 = IV

Constraints:

  • 1 <= num <= 3999

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the valid range of input values for the integer `num`?
  2. Can the input integer be zero or negative?
  3. Are there any specific formatting or casing requirements for the resulting Roman numeral string?
  4. Is it guaranteed that the input will always fit within standard integer limits?
  5. Should I handle standard subtractive forms up to 3999, or do I need to support larger extensions like Vinculum bars for thousands above 3999?

Brute Force Solution

Approach

To solve this problem using a brute force strategy, you would exhaustively search through all possible combinations of Roman numeral symbols to see which ones add up to your target number. You would essentially try building the Roman numeral one piece at a time by testing every available symbol combination until you find the exact match.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire collection of Roman numeral symbols and their corresponding values.
  2. Try taking the largest symbol and see if it fits into your target number.
  3. If it does, subtract its value from your target number and write down that symbol.
  4. If it does not fit, try the next smaller symbol.
  5. Continue this process of trying different symbols one by one, constantly checking what is left of your target number.
  6. If you ever make a choice that leaves you with a remainder that cannot be formed by the remaining symbols, undo your last choice and try a different symbol combination.
  7. Keep testing and adjusting your choices until the remaining target number reaches zero, meaning you have successfully built the complete Roman numeral sequence.

Code Implementation

def int_to_roman(target_number):
    roman_symbols = [("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90), ("L", 50), ("XL", 40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1)]
    
    def backtrack(current_target, current_result):
        # We reach the base case when the target number is fully reduced to zero
        if current_target == 0:
            return current_result
            
        for symbol, value in roman_symbols:
            # Only attempt to subtract and recurse if the symbol fits within the current target
            if current_target >= value:
                result_from_recursion = backtrack(current_target - value, current_result + symbol)
                
                # If a valid path to zero is found, propagate the successful result upward
                if result_from_recursion:
                    return result_from_recursion
                    
        # Backtrack by returning empty if none of the symbol choices lead to a valid solution
        return ""
        
    return backtrack(target_number, "")

Big(O) Analysis

Time Complexity
O(1) – The input size n represents the integer value to be converted, but Roman numerals only support values up to 3999 in standard problems. Because the value of n is bounded by a strict constant maximum, the number of steps required to subtract values and build the string does not grow indefinitely. As the input is capped, the total operations remain bounded by a constant limit, which simplifies to O(1).
Space Complexity
O(1) – The auxiliary space is O(1) because the algorithm only uses a fixed number of variables to track the remainder and a constant-sized symbol mapping structure that does not grow with the input integer N. The output string of Roman numerals scales proportionally with the value of N, but since output space is traditionally excluded from auxiliary space, the extra memory remains bounded by a constant limit. Therefore, the total extra memory required remains constant regardless of how large the input number grows, simplifying to O(1) in Big O notation.

Optimal Solution

Approach

To convert any number into a Roman numeral, the optimal strategy mimics how humans naturally think about value by constantly subtracting the largest possible Roman symbol values until nothing is left. By pre-defining all standard symbol combinations and their special subtraction pairs in descending order, we can greedily build the Roman numeral from left to right.

Here's how the algorithm would work step-by-step:

  1. Start with your given number and a list of all Roman symbol values arranged strictly from largest to smallest, including the special subtraction pairs like nine hundred and four hundred.
  2. Compare your current number to the biggest symbol value on the list.
  3. If your number is big enough to hold that symbol value, write down that symbol and subtract its value from your current number.
  4. Repeat this subtraction process with that exact same symbol value as many times as it fits into your remaining number.
  5. Once the current symbol no longer fits, move down the list to the next smaller symbol value.
  6. Continue this process of comparing, writing, and subtracting until your number has been completely reduced to zero.
  7. Gather all the written symbols together in order to form your final Roman numeral answer.

Code Implementation

def int_to_roman(given_integer):
    roman_value_pairs = [
        (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
        (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
        (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
    ]

    accumulated_roman_numerals = []

    # Descending order ensures we use the largest symbols possible first.
    for symbol_value, roman_symbol in roman_value_pairs:

        # Keep subtracting the same value while it fits to maximize symbol usage.
        while given_integer >= symbol_value:
            accumulated_roman_numerals.append(roman_symbol)
            given_integer -= symbol_value

    # Combining all collected symbols forms the correct final Roman numeral string.
    return ''.join(accumulated_roman_numerals)

Big(O) Analysis

Time Complexity
O(1) – The input size is the integer n, but the cost is driven strictly by iterating through a fixed, pre-defined list of 13 Roman numeral symbol values and subtraction pairs. In the worst-case scenario, the algorithm loops through this static array of 13 elements a bounded number of times because the maximum valid input of 3999 can only subtract these symbols a limited number of times. As the input integer increases, the number of steps does not scale with n, but remains completely constant. This means the operations approximate a fixed upper bound of roughly 13 iterations, which simplifies to O(1) constant time complexity.
Space Complexity
O(1) – The algorithm utilizes a fixed-size, pre-defined lookup table containing all standard Roman symbol values and subtraction pairs, which requires constant extra space regardless of the input value. Additionally, a variable-length string or builder is used to gather the resulting symbols; however, because the maximum valid integer in this problem is 3999, the resulting string can never exceed 15 characters. Since both the lookup structures and the output buffer have hard upper bounds that do not scale with the magnitude of the input integer, the auxiliary memory remains entirely constant. Therefore, the overall space complexity simplifies to O(1).

Edge Cases

Minimum valid input of 1
How to Handle:
The greedy algorithm directly matches the value to I and terminates.
Maximum constraint input of 3999
How to Handle:
The predefined symbol list up to M allows correct translation without overflow or array out of bounds.
Numbers requiring subtractive notation like 4, 9, 40, or 90
How to Handle:
Including composite pairs like IV and IX in our descending lookup table ensures these are naturally picked by the greedy subtraction.
Numbers with zero in various place values such as 100
How to Handle:
The algorithm simply skips symbols whose values are greater than the remaining number, handling zeros implicitly.
Inputs outside the standard Roman numeral range such as 0 or negative numbers
How to Handle:
Constraint specifications guarantee standard inputs from 1 to 3999, but defensive checks can return an empty string for non-positive values.
Repeated identical highest digits like 3000
How to Handle:
The greedy subtraction loop applies the largest symbol M repeatedly until the remainder is smaller than 1000.
0/75 completed