12. Integer to Roman

 

Converting Integers to Roman Numerals in JavaScript

Introduction

Roman numerals are an ancient system of writing numbers that dates back to the Roman Empire. They are still used today in various contexts, such as in clock faces, book chapters, and event names. Converting integers to Roman numerals is a common problem in computer science and often appears in coding interviews and competitive programming. In this blog post, we'll explore an efficient solution using JavaScript. We'll break down the approach, understand the underlying logic, and analyze the complexity of our solution.

Problem Statement

Given an integer, convert it to a Roman numeral. Roman numerals are represented by the symbols: I, V, X, L, C, D, and M.

Intuition

To convert an integer to a Roman numeral, we need to map the largest possible Roman numeral value to the integer and subtract that value repeatedly until we reach zero. By handling the values in descending order, we ensure that the resulting Roman numeral string is correct.

Approach

Our approach involves three main steps:

  1. Map Roman Numerals to Values:

    • Create a Map object symbolList that stores pairs of integers and their corresponding Roman numeral symbols in descending order.

  2. Initialize Result:

    • Initialize an empty string result which will store the final Roman numeral.

  3. Iterate Over Symbol List:

    • Iterate over each pair [val, sym] in the symbolList using a for...of loop.

    • For each pair, calculate how many times val can fit into num using Math.floor(num / val).

    • Append the Roman numeral symbol sym to result the calculated number of times using sym.repeat(count).

    • Update num by subtracting the total value added to result (count * val).

LeetCode Solution

Here's the complete JavaScript solution for the problem:

javascript
var intToRoman = function(num) {
    const symbolList = new Map([
        [1000, 'M'],
        [900, 'CM'],
        [500, 'D'],
        [400, 'CD'],
        [100, 'C'],
        [90, 'XC'],
        [50, 'L'],
        [40, 'XL'],
        [10, 'X'],
        [9, 'IX'],
        [5, 'V'],
        [4, 'IV'],
        [1, 'I']
    ]);
    let result = "";
    for([val, sym] of symbolList) {
        const count = Math.floor(num / val);
        result += sym.repeat(count);
        num -= count * val;
    }
    return result;
};

Example

Let's walk through an example to understand how the code works:

javascript
console.log(intToRoman(1994)); // Output: "MCMXCIV"

In this example, the integer 1994 is converted to the Roman numeral "MCMXCIV".

Complexity Analysis

Time Complexity: O(1)

  • The time complexity is O(1) because the number of iterations in the loop is fixed and does not depend on the input size. The maximum number of iterations is 13, corresponding to the 13 pairs in the symbolList.

Space Complexity: O(1)

  • The space complexity is O(1) because the space used by the result string and the symbolList map is constant and does not depend on the input size.

Conclusion

This solution efficiently converts integers to Roman numerals by leveraging a fixed mapping of values to symbols and iterating through them in descending order. This approach ensures that the solution is both time-efficient and space-efficient, making it suitable for a wide range of input sizes.

Feel free to try out this solution in your projects or coding challenges. If you have any questions or suggestions, feel free to leave a comment. Happy coding!

For a detailed explanation and to see the complete solution, check out my Integer to Roman - LeetCode .

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

LeetCode Problem: Implement pow(x, n) leetcode:- 50