DEV Community

Sofia Jonsson
Sofia Jonsson

Posted on

Roman To Integer

Intro

This week I decided to do some whiteboard practice and came across a pretty neat solution in Ruby that I wanted to share. I had previously completed this question in JavaScript but decided to go back and attempt the LeetCode questions in a different language.

For this specific blog post I am focusing on the classic whiteboard question of converting Roman letters to an integer:

Problem

Alt Text

As stated above, there are 7 Roman numerals to keep track of and for most cases, they are usually written largest to smallest from left to right. However, for any instance where the numbers 4 and 9 are shown we need to adjust our output to reflect that subtraction.

For this example, our input will be "XLIV", and our Output will be "44"

JavaScript Solution

First, I'll show you how I solved for JavaScript:
Alt Text
To break it down further, I put some Console.logs in my Repl.it to see the outputs from the algorithm and how it produced the specific solution of 44.

I set Roman numerals and decimals equal to specific values in separate arrays so that I would not have to subtract once I came across a number with a 4 or 9 and could then loop through it.

As you can see, the algorithm went through the problem 2 times before arriving at the solution:
Alt Text

Ruby Solution

Next, I solved for Ruby:
Alt Text

Once again, I put some "puts" statements in my Repl.it to see how the algorithm arrived at 44. This solution was initially much longer as I thought I needed to incorporate more Roman Numerals into my hash_map_. Ruby has a super useful function for enumerables called each_cons. This then "Iterates the given block for each array of consecutive elements." I put the "puts" statements in there to show how each time it loops through, it looks to the if statement and produces an output for the appreciating and depreciating sums as displayed in the Repl.it as :sum1 and :sum2.

This time around, the algorithm went through the Roman letters 3 times before arriving at the solution:
Alt Text

Time and Space Complexity

The time and space complexity between these two answers were displayed in my submission:
Alt Text
As we can see, the JavaScript solution was significantly more costly than the Ruby solution.

Conclusion

There are so many different ways to solve these LeetCode questions and this is simply an example of two different ways to do it. It's easy to overthink your answer as you're going through the process of trying to solve the problem, but it's good to struggle for a bit and see what you can extract from memory. As you're practicing it's also important to be mindful of how much time you spend trying to solve a problem so that you don't burn yourself out on something so small.

Hope this was useful, good luck practicing these questions!

Oldest comments (0)