LeetCode 12: Integer to Roman is a Medium array / string problem. This Python walkthrough develops a greedy token emission solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Array / String |
| Reusable pattern | greedy token emission |
| Complexity | O(1) time and O(1) extra space for the bounded Roman range |
Recognizing the pattern
Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.
For this problem specifically, iterate Roman tokens from largest to smallest, including subtractive forms, and emit each token as many times as it fits. The invariant worth writing beside the code is: After each token, the output encodes the consumed value and the remainder is smaller than that token.
Step-by-step algorithm
- Identify the input state consumed by
intToRoman(num)and initialize the data required by the greedy token emission pattern. - Iterate Roman tokens from largest to smallest, including subtractive forms, and emit each token as many times as it fits.
- After each update, verify the page’s central invariant: After each token, the output encodes the consumed value and the remainder is smaller than that token.
- Finish only after the boundary behavior is covered: Subtractive values such as 4, 9, 40, and 900 must precede their component symbols.
Python solution
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)Reading the implementation
The main entry point is intToRoman(num). The named working state includes tokens, output, count; those variables make the greedy token emission state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, iterate Roman tokens from largest to smallest, including subtractive forms, and emit each token as many times as it fits.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Iterate Roman tokens from largest to smallest, including subtractive forms, and emit each token as many times as it fits. Each update records the current item without invalidating earlier decisions; consequently, after each token, the output encodes the consumed value and the remainder is smaller than that token.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(1) time and O(1) extra space for the bounded Roman range. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().intToRoman(1994) == "MCMXCIV"Common mistakes and edge cases
- Problem-specific boundary: Subtractive values such as 4, 9, 40, and 900 must precede their component symbols.
- Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
- Invariant check: after every update, confirm that after each token, the output encodes the consumed value and the remainder is smaller than that token.
Interview review checklist
- Explain why greedy token emission matches the structure of this input.
- State the invariant in one sentence before tracing code: After each token, the output encodes the consumed value and the remainder is smaller than that token.
- Derive O(1) time and O(1) extra space for the bounded Roman range from how many times each element or state is visited.
- Test the boundary explicitly: Subtractive values such as 4, 9, 40, and 900 must precede their component symbols.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 13. Roman to Integer · Next: 58. Length of Last Word