Integer to Roman
LeetCode 12 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Greedy over values including subtractive pairs.
मैंने 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
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.
मैंने कैसे हल किया
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'.