LeetCode: Roman to Integer in Java I tried solve this easy leetcode challenge in java. Challenge link

Here is my solution

class Solution {
  public int romanToInt(String s) {
    Map&lt;String, Integer&gt; data 
        = new HashMap&lt;String, Integer&gt;() {
        {
            put("I", 1);
            put("V", 5);
            put("X", 10);
            put("L", 50);
            put("C", 100);
            put("D", 500);
            put("M", 1000);
            put("IV", 4);
            put("IX", 9);
            put("XL", 40);
            put("XC", 90);
            put("CD", 400);
            put("CM", 900);
        }
    };
    String[] edge = {"IV", "IX", "XL", "XC", "CD", "CM"};    
      int sum = 0;  
      for (String val : edge) { 
          if(s.isBlank()) {
              break;
          } else if(s.contains(val)) {
             sum += data.get(val);
             int index = s.indexOf(val); 
             s = s.substring(0, index) + s.substring(index + 2);
          }
      }
      s = s.trim();
      for (char c: s.toCharArray()) {
          sum += data.get("" + c);
      }
      return sum;  
      }
}


I am learning to compute the complexity:
Here is my interpretation
Looks like it is O(6) constant ~ O(1) * O(len(string)) ~ O(n) => O(n)
Correct me if it is not O(n)

Any suggestions on my approach to problem and code where I can reduce time and space complexity.
Your variable names are bad, s, data, all of these could be better, input, romanNumerals and so on.

Your formatting is a little bit off, consider using an autoformatter.

Also your method will spectacularly fail when handed invalid input.



put("I", 1);


Be aware of Autoboxing.



for (String val : edge) { 
    if(s.isBlank()) {


Have the if outside the loop, so that you don't even need to start the loop just to bail out immediately.



sum += data.get("" + c);


I'm absolutely not a friend of such casts. Most of the time, they mask what you actually wanted and depend on implementation details, especially with numbers.



Otherwise it seems to work. What you could do is split the initial Map into two, romanNumerals and compoundRomanNumerals, that would simplify the overall logic and would remove the duplication you have with the edge array.

If you can help it, try to avoid string operations, they will always consume a lot of memory, for example:

String c = a + b;


Will result in:


Allocate c with enough memory to hold a and b
Copy a into c
Copy b into c


So if a and/or b is large, and I mean large, your memory usage will spike.

What you could do instead, is to copy the String into a StringBuilder, as that one will internally work on an array and will not create immutable instances with every change.

And you should handle error cases, null as input, Hello World! as input, such stuff. Would be a great exercise for writing unittests.