LeetCode 12: Integer to Roman — Python Solution

Solve LeetCode 12: Integer to Roman in Python with a greedy token emission approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicArray / String
Reusable patterngreedy token emission
ComplexityO(1) time and O(1) extra space for the bounded Roman range

What the problem is testing

Iterate Roman tokens from largest to smallest, including subtractive forms, and emit each token as many times as it fits.

Algorithm

  1. Iterate Roman tokens from largest to smallest, including subtractive forms, and emit each token as many times as it fits.
  2. Maintain this invariant: After each token, the output encodes the consumed value and the remainder is smaller than that token.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def intToRoman(self, num):
        tokens = [(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")]
        output = []
        for value, symbol in tokens:
            count, num = divmod(num, value)
            output.append(symbol * count)
        return "".join(output)

Why this is correct

The proof follows the maintained state: After each token, the output encodes the consumed value and the remainder is smaller than that token. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(1) time and O(1) extra space for the bounded Roman range. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Subtractive values such as 4, 9, 40, and 900 must precede their component symbols.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 13. Roman to Integer · Next: 58. Length of Last Word