Skip to main content
Leetcode Journey

Day 3: Roman to Integer – My Leetcode Journey

Brad Malgas

Brad Malgas

Author

22 July 20252 min read

Re-solved a problem from last year and improved performance from 43ms to 7ms. A good reminder of measurable progress.

Day 3: Roman to Integer – My Leetcode Journey cover image

Today’s problem was one I had solved before. You might say that’s cheating, but you clearly don’t know how bad my memory is. As usual, I read the problem and pulled out some key info:

  1. There are no numerals larger than M (1000).
  2. There are only 6 subtraction cases; the rest are additions.
  3. I can use a dictionary to store the conversion between characters and their numerical values.

My algorithm was straightforward:

  • Start with a total of 0.

  • Loop over the string:

    • If we are on I and the next character is V or X, subtract the current value from the total.
    • If we are on X and the next character is L or C, subtract the current value from the total.
    • If we are on C and the next character is D or M, subtract the current value from the total.
    • Otherwise, add the current value to the total.

To avoid an out-of-bounds error on the last character, I made the loop run until the second-to-last character. After the loop, I added the last character’s value and returned the result.

It took me 25 minutes 47 seconds to solve this one. The solution had a runtime of 7ms and used about 17.78MB. An obvious optimization would be to combine the checks into a single if statement, but that seemed messy to me, so I left it as is. For interest’s sake, my 2024 submission took 43ms, so I’ll count this as optimized.

My solution can be found on my GitHub: 13. Roman to Integer.py

Loading reactions…

Loading comments…