Roman to Integer - Leetcode 13 - Python

Поделиться
HTML-код
  • Опубликовано: 11 дек 2024

Комментарии • 121

  • @zexisun1243
    @zexisun1243 2 года назад +52

    I love how the negative numbers is applied here(when small numbers are being put before the largers), it is very inspiring

    • @haru5214
      @haru5214 Год назад +2

      Hey I love your positivity and way of thinking ❤

  • @Phi_AI
    @Phi_AI Год назад +6

    Great solution, NeetCode. Your videos help a lot.
    Here is another solution: trick is to always add roman values,
    but if previous roman value is smaller than next one,
    subtract it twice. (because we already added it on the previous step). here is the code:
    roman = {}
    roman["I"] = 1
    roman["V"] = 5
    roman["X"] = 10
    roman["L"] = 50
    roman["C"] = 100
    roman["D"] = 500
    roman["M"] = 1000
    int_sum = roman[s[0]]
    for i in range(1,len(s)):
    if roman[s[i-1]] < roman[s[i]]:
    int_sum -= 2*roman[s[i-1]]
    int_sum += roman[s[i]]
    for example, "XC" which is 90 will be computed as
    step 1: int_sum = roman[s[0]] (10)
    step 2: since roman[s[1]] > roman[s[0]], int_sum = -2*roman[s[0]] + int_sum + roman[s[1]] (- 2*10 + 10 + 100)

  • @abuchikingsley124
    @abuchikingsley124 Год назад +6

    Did this yesterday. My solution was too complex, but faster. This is way easier to grasp.

  • @abhishekr700
    @abhishekr700 2 года назад +7

    Nobody highlights this so clearly that there can only be 1 symbol on the left for substraction case, you just made it clear !

  • @Historyiswatching
    @Historyiswatching 2 года назад +86

    This is easy?! Oh noooooooo I'm screwed

    • @arnaldoramirez4279
      @arnaldoramirez4279 2 года назад +13

      im felling you my brother 🤣

    • @one_step_sideways
      @one_step_sideways 2 года назад +3

      Just learn your language and data structures more. And it takes time to become confident when doing interview questions. How are you doing so far btw?

    • @turell-tate
      @turell-tate 2 года назад +3

      update us on your progress 😂

    • @abuchikingsley124
      @abuchikingsley124 Год назад

      😂

    • @o__bean__o
      @o__bean__o 6 месяцев назад

      My code only passed in Case 1 and Cast 2 😂 case 3 😵

  • @DarklordMcsweetTeaSipper
    @DarklordMcsweetTeaSipper Год назад +3

    I never thought I would be able to understand how this problem worked, thanks so much.

  • @riyatiwari7178
    @riyatiwari7178 2 года назад +20

    You're amazing, thank you for the lucid explanation, breaking down how to reach the problem. 😊

  • @xReisk
    @xReisk 2 года назад +9

    Bro I just wanted to take a look how others solved this and Im so happy my solution its close to yours, literally one/two lines differently. Happy to see that I was able to come with a simple solution like you, good minds think alike 😁

    • @xhenex7622
      @xhenex7622 2 года назад +1

      crange

    • @xReisk
      @xReisk 2 года назад +1

      @@xhenex7622 u ok mr pro?

  • @jideabdqudus
    @jideabdqudus 3 года назад +8

    I watch this channel while eating. Keep it going mate :)

  • @zerosandones7547
    @zerosandones7547 2 года назад +9

    You really know how to clear the confusion. THANK YOU!

  • @cometomatt
    @cometomatt Год назад +1

    this is the best explanation of this problem. clean and simple.

  • @alf8988
    @alf8988 3 года назад +3

    If you keep a prev variable you can simply add the value of the numeral each iteration and substract previous twice if it is smaller than the current numeral

    • @GoziePO
      @GoziePO 2 года назад +4

      I tried that, but I think this method is a bit cleaner/more straight forward.

  • @adityavardhanjain
    @adityavardhanjain 4 месяца назад +1

    I understood the logic of the Roman numerals but didn't really understand the execution. Thanks for the vid.

  • @joonghokim2449
    @joonghokim2449 Месяц назад

    Another way to solve this is to go through the string from the end and in reverse and keeping track of the previous number. If the current number is smaller than the previous, you subtract from the result, else you can just add to the result. I find it a little easier to implement since you are not looking ahead at the next value, so there is no need to check if the next value exists within the bounds.

  • @koearnn3219
    @koearnn3219 5 месяцев назад

    to understand better you have to understand the outputs of each instruction, check the outputs of
    str="XVIII"
    for i in range(len(str)):
    #print(i) #print first
    #print(str[i]) #2nd
    str = "XVIII"
    for i in range(len(str)):
    print(f"i: {i}, c: {str[i]}")
    and you will get it sooner, basically is the explanation of comparing 2 chars and compare the value with the map and check that is >1 letter, cant be 0 that's why the line 11

  • @alifeoflaurels
    @alifeoflaurels 3 года назад +10

    hey, i understand this concept but what about the very last number in the index? how does the code account for that since there's no subsequent number to compare it with? been stuck in leetcode for a while

    • @sharkPause1
      @sharkPause1 3 года назад +13

      That's what the else statement is for
      the if statement runs when all their conditions are true
      if not then run the else statement
      since we're at the last character, the i+1 condition returns false because i+1 is bigger than the length of the string, so we run the else statement
      hope that clears things up

    • @alifeoflaurels
      @alifeoflaurels 3 года назад +1

      @@sharkPause1 thanks it really helps!

    • @bleachie
      @bleachie 2 года назад +1

      @@sharkPause1 except that would actually raise an indexError: index out of bounds. I know because I ran into this error, and my solution was to check up to len(s)-1 and then anded and if statement check and handle the end of the string

    • @sirmidor
      @sirmidor 2 года назад

      @@bleachie No, that would not happen if you use the exact code in the video. This is because conditional expressions made with the boolean keywords not/and/or 'short-circuit' in Python. If you have a combined conditional expression like 'i + 1 < len(s) AND [anything else here]', if the first part of the expression evaluates to False, the second part will not be executed. This is why the code works: When i = len(s) - 1 (the final value that range(len(s) will yield), the first condition ('i + 1 < len(s)') is not True and therefore the second part does not execute, avoiding an IndexError.
      You can test this with a simple example: Dividing by 0 in Python always raises a ZeroDivisionError if executed, but the following code will not raise it:
      '1 > 2 and 5 // 0'
      Because 1 > 2 is False, the second part, which would throw an error, is never executed. This is why the order of your conditional expressions matters. If you would run '5 // 0 and 1 > 2', it will always raise an error.

  • @abhineetsingh6720
    @abhineetsingh6720 2 года назад +2

    concise, no bs. very good

  • @a4rdev
    @a4rdev 2 года назад +3

    I feel so dumb, I can't figure out how to solve these on my own so I just look up the answer and then it makes sense. The only way I'll pass an interview is by memorization at this point.

    • @one_step_sideways
      @one_step_sideways 2 года назад +3

      No, it's just that you didn't learn or get accustomed to some of the complex data structures like hashmaps/dictionaries in Python. I knew I needed to use some kind of dictionary for this one (i mean, it's literally explicitly hinted at in the question with the keys and values) and that was indeed the case. So all you need to do is get accustomed to data structures like knowing when to use which and the rest of your logic would be a simple "if-else" statement. It's just a matter of taking some more time to learn Python or other language that you use.

    • @wokeclub1844
      @wokeclub1844 2 года назад

      @@one_step_sideways Thanks for the reassurance man.

  • @pekarna
    @pekarna 2 года назад

    Small adjustment: We do not need to do the lookahead. Instead, we can keep the last value added, and if it is smaller than the current, we can substract it twice. Imho that's faster than looking into each character twice, looking into a hashmap twice, and check the current position against the end.
    var int = 0
    var lastVal = 0
    for (c in s) {
    val curVal = conv[c]!!
    int += curVal
    if (lastVal < curVal)
    int -= lastVal shl 1
    lastVal = curVal
    }

    • @GoldAMG
      @GoldAMG 2 года назад

      This won't work if there are duplicate smaller values before a larger value.

    • @叶文琴-x7s
      @叶文琴-x7s 2 года назад

      @@GoldAMG there can only be one

    • @abuchikingsley124
      @abuchikingsley124 Год назад

      Yeah. Implemented something similar. Repeated symbols and special cases like IX, XC etc were computed in a single loop and i is moved 2 or 3 places forward.

  • @geekydanish5990
    @geekydanish5990 2 года назад +9

    this is more intuitive i feel
    class Solution:
    def romanToInt(self, s: str) -> int:
    romans = {'M': 1000, 'D': 500 , 'C': 100, 'L': 50, 'X': 10,'V': 5,'I': 1}
    prev,running_total = 0,0
    for i in range(len(s)-1,-1,-1):
    curr = romans[s[i]]
    if prev > curr:
    running_total -= curr
    else:
    running_total += curr
    prev = curr
    return running_total

  • @sepia2008
    @sepia2008 3 месяца назад

    Lol, I did it kinda the same. Basically I had a dictionary but then i converted the string given to a list and then created a new list of the values of that given string so instead of XIII i had [10 1 1 1] and then did the addition for this particular list :) proud i made it by myself

  • @LordPython-xi3yw
    @LordPython-xi3yw 8 месяцев назад

    damn the way this question was explained in the leetcode was far more complex than the solution

  • @ShaikSharmila-tq6bc
    @ShaikSharmila-tq6bc 10 месяцев назад +1

    I am not getting output for the folllowing string i.e
    MCMXCIV
    If i use your method then the answer is 1990
    But the answer is 1994
    How?????
    Please reply

  • @wokeclub1844
    @wokeclub1844 2 года назад

    Funny how I stumble upon this video exactly a year after it was posted.

  • @chaitanyakhot3842
    @chaitanyakhot3842 9 месяцев назад

    I had a similar solution to yours but I iterated the loop backwards. Here's my solution:
    class Solution:
    def romanToInt(self, s: str) -> int:
    roman = s.strip("")
    convert = {"I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000}
    num = convert[roman[len(roman) - 1]]
    for letter in range(len(roman) - 2, -1, -1):
    if convert[roman[letter]] < convert[roman[letter + 1]]:
    num -=convert[roman[letter]]
    else:
    num += convert[roman[letter]]
    return num

  • @Carmadon100
    @Carmadon100 2 года назад

    your videos are amazing. Hope I can pass the screening!

  • @premraja55
    @premraja55 3 года назад +2

    Great explanation!

  • @suraj-ej6oq
    @suraj-ej6oq 3 года назад +1

    You are awesome👍👏😊 please continue like this, this was really helpful for us

  • @ninadpanchal7086
    @ninadpanchal7086 8 месяцев назад

    we making out of rome with this one!!

  • @deeptimayeemaharana2448
    @deeptimayeemaharana2448 2 года назад +1

    i dont understand if we swap the if-else sequence then we get errors, can someone explain?>

    • @muhammadtaimoor876
      @muhammadtaimoor876 5 месяцев назад

      Can be because of short circuiting. (if an AND sees a False early, it won't check the next expression, it will just return False)

  • @milanpatel6240
    @milanpatel6240 2 года назад

    You are too good man

  • @brahimelhoube9532
    @brahimelhoube9532 3 года назад

    Great channel 🎉

  • @siddhantsehgal9900
    @siddhantsehgal9900 3 года назад +1

    Can you go over this one? (1878. Get Biggest Three Rhombus Sums in a Grid)

  • @picture_of_a_swan
    @picture_of_a_swan 2 года назад

    Thank you for this explanation! I didn't even think to use hashmap for some reason, so my code was originally stupidly long (I used a switch case to assign the roman numbers🤦‍♂)

    • @jigyarthjoshi6002
      @jigyarthjoshi6002 Год назад +2

      hey same i did. But the switch case is better because it can also find if the roman number is valid or not unlike this code. My solution is this ->
      class Solution {
      public:
      int romanToInt(string s) {
      int count = 0, n = s.size();
      for(int i = 0; i < n; i++){
      switch(s[i]){
      case 'M':
      count += 1000;
      break;
      case 'D':
      count += 500;
      break;
      case 'C':
      if(s[i+1]== 'M') {
      count += 900;
      i++;
      }else if(s[i+1]== 'D'){
      count+=400;
      i++;
      }else count += 100;
      break;
      case 'L':
      count+= 50;
      break;
      case 'X':
      if(s[i+1]== 'L') {
      count += 40;
      i++;
      }else if(s[i+1]== 'C'){
      count+=90;
      i++;
      }else count += 10;
      break;
      case 'V':
      count+=5;
      break;
      case 'I':
      if(s[i+1]== 'X') {
      count += 9;
      i++;
      }else if(s[i+1]== 'V'){
      count+=4;
      i++;
      }else count += 1;
      break;
      }
      }
      return count;
      }
      };

  • @Joelvarghese6
    @Joelvarghese6 2 года назад +1

    The code I wrote was 40 lines, you solved it in 17 lines...

  • @DusKed
    @DusKed 10 часов назад

    Thank you!

  • @tommyw5332
    @tommyw5332 2 года назад

    I did it recursively for the funs.

  • @deshawnbattle7510
    @deshawnbattle7510 2 года назад

    Great video!

  • @Punibaba1
    @Punibaba1 3 года назад

    You should consider doing Integer to Roman.

  • @kingsleyatuba
    @kingsleyatuba 2 года назад

    Can someone please tell me why this doesnt work for line 11:
    if values[s[i]] < values[s[i+1]] and i+1 < len(s)
    Since it's an 'and' operator, should it matter which one comes first?

    • @Nick-zw7gg
      @Nick-zw7gg 2 года назад

      I found this interesting too and I don't know why.

    • @longmai6888
      @longmai6888 2 года назад +2

      Since it's an if statement using 'and' operator, you need Both conditions to be TRUE in order for line 12 to be executed. And, it shouldn't matter which statement comes first since you would need to satisfy both. I hope that explains it!

    • @shrijeet.gaikwad
      @shrijeet.gaikwad Год назад

      No

    • @nicolassilvadossantos9688
      @nicolassilvadossantos9688 9 месяцев назад

      You need to validate whether there is i+1 first, or the first statement will throw an error accessing a value that doesn't exist.

  • @atlasatlantis8447
    @atlasatlantis8447 2 года назад

    As a beginner, this is what I tried. I am wondering, is there a way to do it my way? With indexes in if statements?
    Roman = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
    I = str(1)
    V = str(5)
    X = str(10)
    L = str(50)
    C = str(100)
    D = str(500)
    M = str(1000)
    if D[ ] < M[ ]:
    D = str(-500)
    else:
    D = str(500)
    print(M,D)
    print(D,M)

  • @komasdfg
    @komasdfg 6 месяцев назад

    oh man, the front is always bigger than the back. Why did my brain not notice that. Thanks.

  • @Avuvos
    @Avuvos 3 года назад +2

    great video as per usual!
    can you do 542. 01 Matrix, please? :)

  • @jindaldreams
    @jindaldreams Год назад

    Thanks Neetcode for awesome explanations. Where can I find the code snippet to your solutions ?

  • @alishahbaz6062
    @alishahbaz6062 2 года назад

    Great explanation! the time complexity will also be O(1) because the largest possible numberal will have 15 letters in it, and then we will only have to iterate 15 times. So O(15) can be considered O(1)

    • @anshgupta9880
      @anshgupta9880 2 года назад +2

      It will be O(n)

    • @xtunasil0
      @xtunasil0 2 года назад

      + the way he wrote the code would prevent that: range(len(s))

  • @izrafaturrahman9174
    @izrafaturrahman9174 3 года назад +1

    Great video, however I think the problem link in the description leads to a different problem.

    • @NeetCode
      @NeetCode  3 года назад +3

      Sorry bout that, should be fixed.

    • @izrafaturrahman9174
      @izrafaturrahman9174 3 года назад +1

      @@NeetCode No problem, keep up the good work!

  • @Morimove
    @Morimove Год назад

    Please provide cpp and java solution also.
    it is really helpful

  • @saurabhbarasiya4721
    @saurabhbarasiya4721 2 года назад

    thanks for sharing this

  • @kingsoonkit9234
    @kingsoonkit9234 2 года назад

    Me thinking that my 140+ lines of crap code was super smart, then i saw this video :'D

  • @ayomikunogunjuyigbe1286
    @ayomikunogunjuyigbe1286 3 года назад +3

    Great video, really helpful!
    I am still confused about something, why are we maintaining (res=0)?

    • @CharounsonSaintilus
      @CharounsonSaintilus 3 года назад +5

      He's just initializing the result he'll eventually return to zero. Notice that result is being added to or subtracted from, so we need to initialize before we can do that.

  • @OwenWu-f9t
    @OwenWu-f9t 7 месяцев назад

    so this question assumes that we can't have LD? because D has a larger value than L, but then you don't subtract 50 from 500.

  • @semilshah8252
    @semilshah8252 2 года назад

    if i+1 < len(s) and roman[s[i]] < roman[s[i+1]]:
    from above line i didnt understand why i+1 < len(s) is written
    can somebody explain??

    • @maratheshrutidattatray2045
      @maratheshrutidattatray2045 2 года назад

      i + 1 < len(s) helps the iteration to stop when the len of s is reached. lets say len(s)== 4 you want your loop to go 4 times but not 4 + 1 as its beyond the bounds.. I hope I made it clear! So as fas as i + 1 < len (s ) the loop is valid.

    • @kingsleyatuba
      @kingsleyatuba 2 года назад

      @@maratheshrutidattatray2045 Can you please tell me why this doesnt work for line 11:
      if values[s[i]] < values[s[i+1]] and i+1 < len(s)
      Since it's an 'and' operator, should it matter which one comes first?

  • @amrholo4445
    @amrholo4445 2 года назад

    Thanks a lot sir

  • @fuyeekee
    @fuyeekee 3 года назад

    if I try the example of IM gets me the 999, is that correct?

    • @NeetCode
      @NeetCode  3 года назад +1

      yeah, i think so

  • @mr.carguy6271
    @mr.carguy6271 Год назад

    what is inbounce said by neetcode ?can someone explain me?

  • @atlasatlantis8447
    @atlasatlantis8447 2 года назад

    The biggest problem I am having with this, is there is no question! The problem dose not ask me a question. What the hell dose the problem want? Do they want us to write a program that converts Roman numbers to inters? I assume this, but the problem dose not even ask you a question.

  • @joaovitorsoares9119
    @joaovitorsoares9119 8 месяцев назад

    but is 999 CMXCIX?
    can we do this IM?

  • @ombothre2350
    @ombothre2350 5 месяцев назад

    1:57 Us

  • @Eltopshottah
    @Eltopshottah 2 года назад

    Who’s comes up with this I need to have a chat with them 😂

  • @SoCalCycling
    @SoCalCycling 2 года назад

    c++ 15ms 6.1mb

  • @andrewchen3247
    @andrewchen3247 2 года назад

    I have a quick question.
    Since you are only adding and subtracting in the for loop and incrementing by 1 each time, wouldn’t that cause the program to recount pairs?
    For example, wouldn’t IVI be counted as 4 + 5 + 1 instead of 4 + 1 because the loop is checking each letter, regardless of if it has already appeared in a pair and has been counted already?

    • @idqnnez1338
      @idqnnez1338 2 года назад

      I understand how you think, but this is how it would be: -1 + 5 + 1
      Since the program doesn't know that IV is for, it knows that a "I" before a "V" is "-1".

  • @aboalabds
    @aboalabds 2 года назад

    IIIX will return wrong result need to add another elif
    class Solution:
    def romanToInt(self, s):
    roman = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
    res = 0
    for i in range(len(s)):
    if (i+1 < len(s) and roman[s[i]] < roman[s[i+1]]):
    res -= roman[s[i]]
    elif (i+1 < len(s) and roman[s[i]] == roman[s[i+1]]):
    res -= roman[s[i]]
    else:
    res += roman[s[i]]
    return res

    • @shinduratmoro2282
      @shinduratmoro2282 2 года назад

      yea but isn't IIIX is invalid? you can't put multiple lesser value behind greater value. if you wish to have 7 as a result, the roman should be VII instead of IIIX.

  • @JackMari
    @JackMari 2 года назад

    BTW "IM" is invalid, 999 = "CMXCIX"

  • @gouravkumarshaw5467
    @gouravkumarshaw5467 2 года назад

    Great!!

  • @iloveyourodman7023
    @iloveyourodman7023 2 года назад

    im so confused man, WHAT is the problem. like WHAT is the question? i don't see what they're asking us to do

  • @bisanghoul3632
    @bisanghoul3632 2 года назад

    Doesn’t the hashmap in this case increase the space complexity? i inow there are only 5 items in it, but still why the extra space when u can use a switch for example?

  • @jvfr-
    @jvfr- 2 года назад

    this is hard

  • @lakshayrohilla873
    @lakshayrohilla873 2 года назад

    This solution wont work for "II"

    • @NeetCode
      @NeetCode  2 года назад +1

      What will it return?

    • @oladipotimothy6007
      @oladipotimothy6007 2 года назад

      Watch out for case sensitive romans. Solution works!

  • @lukaszplachecki8723
    @lukaszplachecki8723 4 месяца назад

    🎉

  • @krateskim4169
    @krateskim4169 2 года назад

    nice

  • @sreeru
    @sreeru 8 месяцев назад

    Easy for who? Newton?

  • @js8597
    @js8597 3 года назад +1

    im trying this on my own and cant figure out why my solution doesnt work correctly. More interested in what is wrong with my logic than this person's solution.
    class Solution(object):
    def romanToInt(s):
    romans = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
    total = []
    result = 0
    for l in s:
    total.append(romans[l])

    for num in total:

    number_totheright = total[total.index(num)+1]
    try:
    if num < number_totheright:
    result -= num
    else:
    result += num
    # last number wont have a 'number_totheright'
    except IndexError:
    result += num
    print(result)
    Solution.romanToInt('CMXC')

  • @BurhanCerit
    @BurhanCerit 3 года назад

    nice..

  • @SiarheiAkhramenia
    @SiarheiAkhramenia 4 месяца назад

    There is no such thing as IM in Roman numbers. Just an inaccurate example.

  • @atlasatlantis8447
    @atlasatlantis8447 2 года назад

    This video is poor quality for learning. How about showing us how to run the code? As a beginner, I want to learn how to actually use the code.
    Running what you have, dose nothing.

  • @bluemoon7890
    @bluemoon7890 2 года назад

    "I am getting this error, someone plz help"
    TypeError: None is not valid value for the expected return type integer
    raise TypeError(str(ret) + " is not valid value for the expected return type integer");
    Line 37 in _driver (Solution.py)
    _driver()
    Line 44 in (Solution.py)
    During handling of the above exception, another exception occurred:
    TypeError: '

  • @srigkt
    @srigkt 2 года назад

    "III"
    "LVIII"
    "MCMXCIV"
    "MCV"
    "CMXCVIII" - results for the last two roman letters are incorrect as per leetcode. here is the code i put in for the same. Can u please help explain why?
    Input:
    "III"
    "LVIII"
    "MCMXCIV"
    "MCV"
    "CMXCVIII"
    Output:
    3
    58
    1994
    905
    798
    Expected:
    3
    58
    1994
    1105
    998
    #################
    class Solution:
    def romanToInt(self, s: str) -> int:
    roman={"I":"1","V":"5","X":"10","L":"50","C":"100","D":"500","M":"1000"}
    res=0
    for i in range(len(s)):
    if i+1

    • @tarunmuppuri1106
      @tarunmuppuri1106 2 года назад

      class Solution:
      def romanToInt(self, s: str) -> int:
      HashMap = {"I":1,"V":5,"L":50,"X":10,"C":100,"M":1000,"D":500}
      ans=0
      for i in range(len(s)):
      if i+1

    • @tarunmuppuri1106
      @tarunmuppuri1106 2 года назад

      In hashmap u should not give numbers in string.While compariing it takes ascii values which leads to wrong interpretution

    • @srigkt
      @srigkt 2 года назад

      @@tarunmuppuri1106 it solved thank u

  • @zara4257
    @zara4257 Год назад

    why does everyone keep saying it's easy? 🥲🥲

    • @sunithakumari333
      @sunithakumari333 Год назад

      Becoz it's easy if u know school math related to numbers and their different notations 😄