Day 3: Roman to Integer – My Leetcode Journey

Brad Malgas
Author
Re-solved a problem from last year and improved performance from 43ms to 7ms. A good reminder of measurable progress.
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:
- There are no numerals larger than M (1000).
- There are only 6 subtraction cases; the rest are additions.
- 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
Iand the next character isVorX, subtract the current value from the total. - If we are on
Xand the next character isLorC, subtract the current value from the total. - If we are on
Cand the next character isDorM, subtract the current value from the total. - Otherwise, add the current value to the total.
- If we are on
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…