Tensorum
YouTubeশেখা শুরু করুন
LeetCode 12 · Sorting + Simple Greedy

Integer to Roman

LeetCode 12 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Greedy over values including subtractive pairs.

মাঝারিHash TableMathString
LeetCode-এ খুলুন ↗

আমি Integer to Roman (LeetCode 12) এভাবে সমাধান করেছি — Sorting + Simple Greedy প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।

নিচের বিবরণ ইংরেজিতে।

Intuition

Roman numerals are greedy: always write the largest symbol that still fits. Including the six subtractive pairs (CM, CD, XC, XL, IX, IV) in the table makes the greedy rule produce the correct form.

Approach

  1. 1

    Table of 13 values from 1000 down to 1.

  2. 2

    While num > 0, append each symbol as many times as it fits.

  3. 3

    Subtract its value each time.

আমি কীভাবে সমাধান করেছি

Greedy tablePythonO(1) time
class Solution:
    def intToRoman(self, num: int) -> str:
        nums = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
        symbols = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
        ans = ""
        while num>0:
            for index,cur_num in enumerate(nums):
                while cur_num<=num:
                    ans+=symbols[index]
                    num=num-cur_num
                    if cur_num>num:
                        break;
        return ans
স্টেপ-থ্রু লোড হচ্ছে…

Integer to Roman — সাধারণ প্রশ্ন

Integer to Roman-এর পেছনে intuition কী?

Roman numerals are greedy: always write the largest symbol that still fits. Including the six subtractive pairs (CM, CD, XC, XL, IX, IV) in the table makes the greedy rule produce the correct form.

Integer to Roman (LeetCode 12) কীভাবে সমাধান করবেন?

1. Table of 13 values from 1000 down to 1. 2. While num > 0, append each symbol as many times as it fits. 3. Subtract its value each time.

Integer to Roman-এর time আর space complexity কত?

Time: O(1)। Space: O(1)। (Accepted approach: Greedy table।)

Integer to Roman-এ সাধারণ ভুলগুলো কী?

Without CM, XC, IV, etc. you'd produce 'VIIII'.