06. Roman Number to Integer
β GFG solution to Roman Number to Integer problem: convert Roman numerals to decimal using greedy pattern matching technique for optimal performance. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given a string s in Roman number format, your task is to convert it to an integer. Various symbols and their values are given below:
Roman Numeral Values:
I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000
Special Cases (Subtraction Rules):
IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900
The goal is to parse the Roman numeral string and return its equivalent decimal integer value.
π Examples
Example 1
Input: s = "IX"
Output: 9
Explanation: IX is a Roman symbol which represents 10 β 1 = 9.Example 2
Example 3
π Constraints
$1 \le \text{roman number} \le 3999$
$s[i] \in [I, V, X, L, C, D, M]$
β
My Approach
The optimal approach uses a Greedy Pattern Matching technique that processes Roman numerals from largest to smallest values:
Greedy Pattern Matching Algorithm
Initialize Data Structures:
Create parallel arrays:
vals[]for decimal values andsyms[]for corresponding Roman patterns.Order them from largest to smallest value (M=1000 down to I=1).
Include subtraction cases (CM=900, CD=400, XC=90, XL=40, IX=9, IV=4).
Greedy Matching:
For each Roman pattern in descending order of value:
Check if current position in string matches the pattern.
If match found, add its value to result and advance position by pattern length.
Repeat until no more matches for current pattern.
Process All Patterns:
Continue with next smaller pattern until all 13 patterns are processed.
This ensures larger values are consumed first (greedy approach).
Return Result:
The accumulated sum represents the decimal equivalent.
Key Insight: By processing patterns in descending order, we naturally handle subtraction cases (like CM, CD) before their individual components, ensuring correct interpretation.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the Roman numeral string. Each character is processed at most once as we advance through the string systematically.
Expected Auxiliary Space Complexity: O(1), as we use fixed-size arrays for storing the 13 Roman patterns and their values, requiring constant extra space regardless of input size.
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Map-Based Single Pass Approach
π‘ Algorithm Steps:
Create a map for Roman numeral values for O(1) lookup.
Traverse string once from left to right.
Compare current and next character values to handle subtraction cases.
Add or subtract based on the comparison result.
π Complexity Analysis:
Time: β±οΈ O(n) - Single pass through string
Auxiliary Space: πΎ O(1) - Fixed size map
β
Why This Approach?
Clean and readable logic
Handles all Roman numeral rules naturally
Good for understanding Roman numeral principles
π 3οΈβ£ Reverse Traversal Approach
π‘ Algorithm Steps:
Start from the rightmost character and move left.
Keep track of the maximum value seen so far.
If current value is less than max, subtract it (handles IV, IX cases).
Otherwise add it to result and update maximum.
π Complexity Analysis:
Time: β±οΈ O(n) - Single reverse pass
Auxiliary Space: πΎ O(1) - Array lookup table
β
Why This Approach?
Elegant reverse logic eliminates lookahead
Simple comparison rule for subtraction cases
Efficient array-based character lookup
π 4οΈβ£ Switch-Case Optimized
π‘ Algorithm Steps:
Use switch statement for fastest character to value mapping.
Process string left to right with lookahead for subtraction cases.
Skip next character when subtraction pair is found.
Accumulate result with addition or subtraction.
π Complexity Analysis:
Time: β±οΈ O(n) - Linear traversal with constant lookups
Auxiliary Space: πΎ O(1) - No extra data structures
β
Why This Approach?
Switch statement provides fastest character mapping
Branch prediction friendly code structure
Minimal memory footprint
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π·οΈ Greedy Pattern Match
π’ O(n)
π’ O(1)
π Handles all cases directly
π More complex setup
π Map-Based
π’ O(n)
π’ O(1)
π Clean and intuitive
π Map lookup overhead
π Reverse Traversal
π’ O(n)
π’ O(1)
π― Elegant logic
π Less intuitive flow
π Switch-Case
π’ O(n)
π’ O(1)
β Fastest execution
π More verbose code
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Maximum performance needed
π₯ Switch-Case
β β β β β
π Code readability priority
π₯ Map-Based
β β β β β
π§ Pattern matching elegance
π₯ Greedy Pattern
β β β β β
π― Interview/Competitive
π Reverse Traversal
β β β β β
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated