#12

Integer to Roman

Medium Greedy table

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Convert an integer from 1 to 3999 into a Roman numeral.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: write a number in Roman numerals.

Why this works: include the subtractive pairs (CM, XC, IV…) in the value table, then greedily take the biggest piece that fits.

Example: 58

50 → L, 8 left5 → V, 3 leftIII → "LVIII"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Leaving out the subtractive pairs, which produces IIII instead of IV.

Solve on LeetCode ↗
Complexity
  • Time: O(1) — the output is at most 15 characters.
  • Space: O(1).
Topic: Strings
🎬 Episodes 16–20: video coming soon