Roman To Integer (Leetcode Problem #13)

Java Solution for https://leetcode.com/problems/roman-to-integer/

Suraj Mishra
Javarevisited
Published in
3 min readSep 9, 2021

Youtube Video
If you prefer video format : https://youtu.be/BC-mHuUAaZA

Understanding Problem

input_x = "LVIII"
output_x = 58
L = 50; V=5; III=3
  • There some facts about roman numerals. They are usually written from largest to smallest. In above example L is larger than V.
  • There some instances mentioned below where subtraction is used.
  • I can be placed before (V & X); X can be placed before (L & C); C can be placed before (D & M).
  • So four is not written lie IIII , rather it is written as IV.

My Thought About Solution

  • I can convert roman numeral string to char array.
  • Since generally roman numerals are written largest to smallest usually except some cases where subtraction is needed, I can just check the case that if current char value is greater than next char value, if yes than i can just add the value of it to my sum.
  • But if i have case where current roman numeral value is less than next roman value then i have to subtract it. For example if roman numeral is “IV”, in that case if my current char is I then sum = sum- Value of (I) due to subtraction rule of roman numerals
  • Data structure: We need hashmap to store roman numerals and its corrosponding value
    Time-complexity: O(length(N)) where N is the input roman numeral
    Space-complexity: Constant Space since roman numerals are constant in time

Pseudocode

1: Convert Input roman numeral to char array
2: Create Map of each roman numeral char and its corrosponding value
3: Traverse input char array
4: for each char array calculate
a: if current roman numeral value is greater than next roman
numeral - value then add the value of current roman numeral
to the total sum

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Javarevisited
Javarevisited

Published in Javarevisited

A humble place to learn Java and Programming better.

Suraj Mishra
Suraj Mishra

Written by Suraj Mishra

Staff Software Engineer @PayPal ( All opinions are my own and not of my employer )

No responses yet

Write a response