Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Roman Numeral Conversion Method

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Roman Numeral Conversion Method. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Global Healthcare Exchange systems may receive compact Roman numeral identifiers from legacy healthcare documents. Implement a parser that converts a Roman numeral to its integer value only when the numeral follows canonical Roman numeral rules.

Return the decoded integer for a valid numeral. Return -1 for an invalid numeral.

Formal Specification

Implement roman_to_integer(s), where s is a non-empty uppercase string containing only the characters I, V, X, L, C, D, and M. Valid values range from 1 through 3999 and must use canonical notation:

  • I, X, and C may precede only their valid subtractive partners: IV, IX, XL, XC, CD, or CM.
  • V, L, and D may not repeat.
  • No symbol may repeat more than three times consecutively.
  • Symbols must appear in descending place-value order, except for valid subtractive pairs.

The function returns an integer for valid input and -1 otherwise. Aim for a single left-to-right parse and explain how canonical validation prevents malformed strings from being accepted.

Constraints

  • 1 <= len(s) <= 15
  • s contains only uppercase Roman numeral letters
  • Valid values are between 1 and 3999
  • Return -1 for any non-canonical representation

Function Signature

def roman_to_integer(s):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output