Start learning free

LESSON 310 OF 314 · MATH

Roman to Integer in Go: A Byte Map and One Pass

Practice O(n) Read the full explanation

You get a string s that holds a Roman numeral. Return the number it stands for.

Roman numerals use seven letters. Each letter has a value:

I = 1     X = 10     C = 100     M = 1000
V = 5     L = 50     D = 500

Usually the letters go from larger values to smaller ones. Then the number is the sum of their values.

Six pairs break that order. In each one, a smaller letter comes just before a larger one. That smaller letter is subtracted:

IV = 4     IX = 9
XL = 40    XC = 90
CD = 400   CM = 900

 

Example 1:

Input: s = "XXXI"
Output: 31
Explanation: No letter comes before a larger one.
So you add them all: 10 + 10 + 10 + 1 = 31.

Example 2:

Input: s = "XIV"
Output: 14
Explanation: X is 10.
Then comes the pair IV, which is 4.
In total, 10 + 4 = 14.

Example 3:

Input: s = "DCCCXLIX"
Output: 849
Explanation: D is 500, and CCC is 300.
XL is 40, and IX is 9.
In total, 500 + 300 + 40 + 9 = 849.

 

Constraints:

  • s has 1 to 15 letters.
  • Each letter is one of the seven above.
  • The numeral in s is always valid.
  • Its value is from 1 to 3,999.
Note:

Your solution should run in O(n) time, where n is the length of s.



Look at each letter together with the letter after it. When the next letter has a larger value, this letter is the first half of a pair like IV.

Subtract a letter's value when the next letter is larger. Otherwise, and for the last letter, add it. In XIV that gives 10 - 1 + 5 = 14.

Each letter takes one lookup in a map of 7 letters and one addition or subtraction: O(n) time.
The map always has 7 entries, so the extra space is O(1).
STEP 1 OF 7
    Ctrl + Enter to check

    GO · MATH

    Roman To Integer in Go, explained

    Problem overview

    The function romanToInt receives s, a valid Roman numeral of 1 to 15 letters, and returns its value, which is between 1 and 3,999. The seven letters are I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000.

    Usually the letters go from larger to smaller, and the value is their sum: XXXI is 10 + 10 + 10 + 1 = 31. Six pairs break that order, IV, IX, XL, XC, CD and CM, where a smaller letter stands just before a larger one and is subtracted. XIV is 10 + 4 = 14, and DCCCXLIX is 500 + 300 + 40 + 9 = 849.

    Approach: subtract a letter that comes before a larger one

    There is no need to find the six special pairs. Look at each letter together with the letter after it. If the next letter is worth more, the current one is the first half of a pair, so subtract its value. Otherwise add it. The last letter has no next letter and is always added.

    For XIV this reads: X is followed by I, which is smaller, so add 10. I is followed by V, which is larger, so subtract 1. V is last, so add 5. The sum is 10 - 1 + 5 = 14. The subtraction of the small letter and the later addition of the large one together give exactly the pair's value, here 5 - 1 = 4.

    One pass over the string with a lookup table of seven letters is enough, so the time is linear.

    Step by step

    1. Build the table. Declare values with a map literal and :=. Its type is map[byte]int, because indexing a string, s[i], gives a byte, so the keys are byte literals such as 'I'.
    2. Start total at 0. It sums the letters' signed values.
    3. Loop over the indexes with for i := 0; i < len(s); i++. The index is needed to reach the next letter, so a plain loop over the letters would not do.
    4. Look up the current letter: value := values[s[i]]. For XIV that gives 10, then 1, then 5.
    5. Subtract when a larger letter follows. The condition has two parts: i + 1 < len(s) and values[s[i + 1]] > value. The key line is total -= value.
    6. Otherwise add it with an else branch. The last letter always lands here.
    7. Return total after the loop.

    The order of the two tests in step 5 matters. Go's && stops at the first part that is false, so when i + 1 < len(s) fails, s[i + 1] is never read. Reading it would panic with an index out of range.

    The solution in Go

    func romanToInt(s string) int {
        values := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        total := 0
        for i := 0; i < len(s); i++ {
            value := values[s[i]]
            if i + 1 < len(s) && values[s[i + 1]] > value {
                total -= value
            } else {
                total += value
            }
        }
        return total
    }
    

    The Go details worth a closer look:

    • Bytes and runes. A Go string is a sequence of bytes. s[i] is a byte, which prints as a number: for "XIV", s[0] prints as 88, the code of 'X', while string(s[0]) gives "X". A range loop over a string yields runes instead. Using a rune as the key of this map[byte]int does not compile: cannot use c (variable of type rune) as byte value in map index. For a numeral made of ASCII letters the byte loop is simplest.
    • Missing keys. Reading a key that is not in a map gives the zero value, so values['Z'] is 0, not an error. The lesson guarantees valid input, so this never comes up, but it explains why bad input would quietly add nothing.
    • Map literal. map[byte]int{'I': 1, ...} builds and fills the map in one expression. A map is created once per call, which is fine for seven entries.
    • Integer type. total is an int, which holds far more than 3,999, so there is no overflow concern.

    Run on the examples, the function returns 31 for "XXXI", 14 for "XIV" and 849 for "DCCCXLIX". It also returns 1994 for "MCMXCIV", 3999 for "MMMCMXCIX" and 1 for "I".

    Complexity

    Each letter costs one or two map lookups and one addition or subtraction, so the time is O(n) for a string of length n. The map always holds seven entries, so the extra space is O(1).

    Edge cases and common mistakes

    • The last letter. It has no successor, so it must be added. Checking the bound first, as the condition does, handles this.
    • A single letter. "I" goes straight to the else branch and returns 1.
    • Several smaller letters before a larger one. A numeral like XIV or MCMXCIV mixes additions and subtractions. Each letter is judged only against its right neighbour, and that is enough for valid numerals.
    • Equal neighbours. In XXX, the next letter is equal, not larger, so the letter is added. Use a strict >.
    • Using range with the byte map. It gives runes and does not compile, as shown above. Index the string with s[i] instead.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free