#12
Integer to Roman
MediumHash TableMathStringHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Hash Map)★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using a hash map (or a list of tuples) allows us to efficiently map the integer values to their corresponding Roman numeral symbols. This approach is more efficient than brute force as it directly checks and subtracts the largest possible values in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Create a list of tuples containing Roman numeral symbols and their corresponding integer values, sorted from largest to smallest.
- 2Step 2: Initialize an empty string to build the Roman numeral result.
- 3Step 3: Use a loop to iterate through the list, subtracting the value from the number and appending the corresponding symbol to the result until the number is reduced to zero.
solution.py27 lines
1# Full working Python code with comments
2
3def int_to_roman(num):
4 roman_numerals = [
5 (1000, 'M'),
6 (900, 'CM'),
7 (500, 'D'),
8 (400, 'CD'),
9 (100, 'C'),
10 (90, 'XC'),
11 (50, 'L'),
12 (40, 'XL'),
13 (10, 'X'),
14 (9, 'IX'),
15 (5, 'V'),
16 (4, 'IV'),
17 (1, 'I')
18 ]
19 result = ''
20 for value, symbol in roman_numerals:
21 while num >= value:
22 result += symbol
23 num -= value
24 return result
25
26# Example usage
27print(int_to_roman(1994)) # Output: MCMXCIVℹ
Complexity note: The time complexity is O(n) because we iterate through the list of Roman numeral values at most once for each numeral. The space complexity is O(1) since we only use a fixed amount of space for the result string.
- 1Recognizing the patterns in Roman numeral representation, especially the subtractive combinations (like IV, IX) helps streamline the conversion process.
- 2Understanding that we can efficiently use a sorted list of numeral values allows for a more systematic approach to building the final Roman numeral string.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.