Largest Number - Leetcode 179 - Python

Поділитися
Вставка
  • Опубліковано 9 лис 2024

КОМЕНТАРІ • 85

  • @nikkil7428
    @nikkil7428 Рік тому +17

    You are the best one yet. Your videos had been helping me so much, from struggling doing medium, to now conquering medium leetcode. Your positive energy also giving me such a good vibe to work on supposed to be boring and painful leetcode questions. ❤❤❤ Thank you.

  • @aswinbarath
    @aswinbarath 7 місяців тому +10

    I struggled a more than 1 hour on this problem by doing it myself without the knowledge of Custom comparator concept. Thank you so much for this solution bro!

  • @rhosymedra6628
    @rhosymedra6628 2 роки тому +8

    great explanation! tried this on my own, got stuck, and came here to listen to your explanation.

  • @fer-ic1wh
    @fer-ic1wh 2 роки тому +5

    for those who don't understand the cmp function. paste source code here
    def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
    __slots__ = ['obj']
    def __init__(self, obj):
    self.obj = obj
    def __lt__(self, other):
    return mycmp(self.obj, other.obj) < 0
    def __gt__(self, other):
    return mycmp(self.obj, other.obj) > 0
    def __eq__(self, other):
    return mycmp(self.obj, other.obj) == 0
    def __le__(self, other):
    return mycmp(self.obj, other.obj) = 0
    __hash__ = None
    return K

  • @stephenbouldin8163
    @stephenbouldin8163 2 роки тому +16

    As someone new to python, and coding in general, I learn something new in each of these videos. However, it would be more helpful if you explained the functions within the class a little more.

  • @rakoonberry7879
    @rakoonberry7879 2 роки тому +28

    I'm not sure if your str(int(..)) solution at the end is the best way to go about it. The problem says that the number may be large (i.e. overflow) so we are asked to return a string. A loop would probably be a better albeit less elegant answer.

    • @jessesinger4790
      @jessesinger4790 7 місяців тому +1

      Can just check first value of string too, concatenatedString[0] == '0' ? "0" : concatenatedString

    • @lenovox1carbon664
      @lenovox1carbon664 Місяць тому +3

      Python never overflows

    • @thepriestofvaranasi
      @thepriestofvaranasi Місяць тому

      Pretty sure you can't overflow int in Python.

  • @AlexSav
    @AlexSav 2 роки тому +13

    0:25 It may be very large, so return string instead of an integer
    10:35 - Just convert to an integer and then back to string
    Genius!

    • @jfcherng
      @jfcherng 2 роки тому +8

      lol... worked since Python has auto big number handling.
      return ''.join(nums).lstrip('0') or '0'

  • @redfinance3403
    @redfinance3403 7 місяців тому +1

    My solution was pretty ugly and consisted of making the number into separate digits within a map of maps of maps ... and then sorting each map in descending order based on the key. Then recursively iterating over the digits and eventually adding them in order to the answer. This comparator idea is very smart and its amazing how the idea didn't come to me earlier given the fact that my code is basically selecting the best possible order to add them in. Once again, amazing video!

  • @OneMoreLight1
    @OneMoreLight1 2 роки тому +20

    nums = list(map(str,nums))
    this will convert every int list element into str and store in nums . Python ❤️💕

  • @AustinWeeks
    @AustinWeeks Місяць тому

    I spent like 45 minutes writing this convoluted sorting algorithm that looped through each digit to compare the values, got stuck, then came here. Now I feel stupid knowing the solution takes like 3 lines of code 😂

  • @jimmycheong7970
    @jimmycheong7970 2 роки тому +1

    I ended up writing a recursive comparator function which took me ages to figure out properly! Only I had submitted a successful solution did I find out you can just add the nums strings as strings in different orders. 🤦🏻‍♂️. Thanks for the video as always!

  • @FACS01
    @FACS01 2 роки тому +3

    Careful that converting str to int for handling the 000 case could produce overflow in large numbers

    • @NeetCode
      @NeetCode  2 роки тому +2

      That's definitely true, python makes it work but in other languages it probably won't work.

    • @nandhakiran6523
      @nandhakiran6523 2 роки тому +8

      We can avoid that, just check if the sorted arrays first element is "0". if so, that means everything after it will also be "0" so we can just return "0" right there :)
      And if that is not good enough, we can sum the initial array, if it is 0, return "0". But that decreases the efficiency of the code.

    • @HelloJaewon
      @HelloJaewon 2 роки тому

      @@nandhakiran6523 Great! It's clear and does not dependent on programming language.

    • @sharksinvestment9864
      @sharksinvestment9864 Рік тому

      Nums=list(map(str,nums))

  • @pammugaadu
    @pammugaadu 2 роки тому +2

    Thank you very much for your valuable time. I really appreciate.
    If anyone is looking for Java code:
    public static String getLargestNumber(int[] input) {
    String output[] = Arrays.stream(input).mapToObj(String::valueOf).toArray(String[]::new);
    Arrays.sort(output, (n1, n2) -> {
    return (n2 + n1).compareTo(n1 + n2);
    });
    String result = Arrays.stream(output).collect(Collectors.joining());
    if (result.matches("^[0]*$")) {
    return "0";
    }
    return result;
    }

  • @AlexN2022
    @AlexN2022 Місяць тому

    Yea, this works in languages like Python. But go into C++ even and two large enough ints concatenated together will overflow even a long int. So you will really be down to by-position comparison.

    • @thepriestofvaranasi
      @thepriestofvaranasi Місяць тому

      You can put a check, if the first element of your sorted array is 0, the rest all would obviously be zero coz the number would logically be the biggest possible after the sort. So in that case, you can just return "0".

    • @AlexN2022
      @AlexN2022 Місяць тому

      @@thepriestofvaranasi you were probably replying to some other comment?

  • @gskpsrikar1858
    @gskpsrikar1858 2 роки тому

    Max length of the array is 100. So write simple sort algo in O(n^2) using the str comparator logic. Simple !

  • @el_chivo99
    @el_chivo99 2 роки тому +3

    great solution. never knew about cmp_to_key until now!

  • @oneplusgeek7510
    @oneplusgeek7510 2 роки тому +2

    Thanks!!

  • @aprily5016
    @aprily5016 Рік тому

    The sound feels like ASMR, which makes me personally feel disturbing. Content is clear

  • @miguelangelrodriguez8999
    @miguelangelrodriguez8999 5 місяців тому

    Thank you

  • @Cloud-577
    @Cloud-577 2 роки тому

    Do we have to write out own sorting function in an interview?

  • @HolyCowSoft
    @HolyCowSoft 2 роки тому +1

    oh great and clear tip! thx

  • @rohanchess8332
    @rohanchess8332 Рік тому

    Wait, how can you compare strings like integers, it compares the ascii value right, so shouldn't we use int(n1+n2) > int(n2+n1) ?

  • @hueydo3522
    @hueydo3522 8 місяців тому +1

    why if n1 is the bigger significant digit, we would want to return -1?

  • @刘智宇-v1t
    @刘智宇-v1t Місяць тому +1

    Thank you very much

  • @shubhamsingla8182
    @shubhamsingla8182 2 роки тому

    Please do 708. Insert into a Sorted Circular Linked List

  • @santoshrathod9868
    @santoshrathod9868 2 роки тому

    You are a legend.

  • @anirbanhossen6170
    @anirbanhossen6170 2 місяці тому

    class Solution:
    def largestNumber(self, arr: List[int]) -> str:
    for i in range(len(arr)):
    arr[i]=str(arr[i])
    arr=sorted(arr,key=lambda x:x*10,reverse=True)
    ans="".join(arr)
    return str(int(ans))#[0,0,0] should return 0

  • @weaponkid1121
    @weaponkid1121 2 роки тому

    What drawing program do you use??

  • @linggesarulsamy
    @linggesarulsamy 2 роки тому +1

    I wrote the function in JavaScript:
    1) Arr_To_Single_String = Array.join("");
    Convert the Interger Array to a Single String:
    [10, 2] => "102"
    2) Arr = Arr_To_Single_String.split("");
    Split the String to each character individually in Array;
    "102" => ["1", "0", "2"]
    3) Sorted = Arr.sort().reverse();
    Sort the Array in descending order
    ["1", "0", "2"] => ["2", "0", "1"] => "210"
    function sortString(Array) {
    let Arr_To_Single_String = Array.join("");
    let Arr = Arr_To_Single_String.split("");
    let Sorted = Arr.sort().reverse();
    return Sorted.join("");
    }
    // Question 1
    let Q1 = [10, 2];
    console.log(`sortString(${Q1}) = ${sortString(Q1)}`); // Output: "210"
    // Question 2
    let Q2 = [3, 30, 34, 5, 9];
    console.log(`sortString(${Q2}) = ${sortString(Q2)}`); // Output: "9543330"
    // Question
    let Q3 = [10, 2, 5000, 321];
    console.log(`sortString(${Q3}) = ${sortString(Q3)}`); // Output: "5322110000"

    • @jimmycheong7970
      @jimmycheong7970 2 роки тому

      Actually you are supposed to preserve the order of the numbers so technically the answer you have for question 2 is incorrect 😕

    • @KARTHIKEYANR-b1n
      @KARTHIKEYANR-b1n 2 місяці тому

      Thanks 👍

  • @GriffinBaker
    @GriffinBaker 4 місяці тому

    nlogn or knlogn where k is the avg. length of the strings were comparing?

  • @nikhil199029
    @nikhil199029 2 роки тому +1

    If we compare 9 and 930 then 930 has a higher value so this code should return 9309 instead of 9930? Not sure what am I missing.

    • @dakshbhayana237
      @dakshbhayana237 2 роки тому +1

      it doesn't compare numbers individually , it compares after concatenating them.

  • @Cloud-577
    @Cloud-577 2 роки тому

    I had the same idea but struggled to code it up :( how do I improve?

  • @akshatsingh6036
    @akshatsingh6036 Місяць тому

    But the question states that the number could be very large hence should be returned as an string. Why didn't you used lstrip ?

  • @neilgaliaskarov5341
    @neilgaliaskarov5341 2 роки тому

    Can you please explain us Accounts merge problem from leer code? I just don’t understand other explainers…

  • @Dezdichado1000
    @Dezdichado1000 2 роки тому

    can this not be done by a recursion?

  • @mickeymacke1780
    @mickeymacke1780 2 роки тому

    Can you do 1721. Swapping Nodes in a Linked List?

  • @navamshuram
    @navamshuram 2 роки тому +1

    def comp(a,b):
    if (a+b)>(b+a):
    return -1
    else:
    return 1
    #
    arr.sort(key = functools.cmp_to_key(comp))
    ans="".join(arr)
    return ans

    • @KARTHIKEYANR-b1n
      @KARTHIKEYANR-b1n 2 місяці тому

      Thanks for the help bro,saved my time 😊

  • @symbol767
    @symbol767 2 роки тому

    Wow this is a genius solution wtf

  • @rsankaranarayanan5254
    @rsankaranarayanan5254 12 днів тому

    Did anyone try all the combinations ?
    i did not get the greedy approach intuitively

  • @its_me_tabs
    @its_me_tabs Рік тому

    Whats the time complexity?

  • @niharikkatyagi4089
    @niharikkatyagi4089 Рік тому

    I'm not sure why, but this is returning a NULL value in each case when I try to run it. Is there any solution to this??

  • @jugsma6676
    @jugsma6676 2 роки тому +1

    I always solve my way before watching the solution, and this is my solution,
    def max_number(nums):
    res_lst = permute(nums)
    max_str_numb = -sys.maxsize
    for i in range(len(res_lst)):
    appended_str = ''.join([str(r) for r in res_lst[i]])
    max_str_numb = max_str_numb if max_str_numb > int(appended_str) else int(appended_str)
    return str(max_str_numb)
    def permute(nums):
    if len(nums) == 1:
    return [nums]
    res = []
    for i in range(len(nums)):
    head = nums[i]
    remainder = nums[:i] + nums[i+1:]
    for p in permute(remainder):
    buffer = [head] + p
    res.append(buffer)
    return res

  • @tanaypatel8412
    @tanaypatel8412 Рік тому +1

    did anyone else tried extracting just the first character and arranging as such and got stuck.

  • @amarnathmishra8697
    @amarnathmishra8697 2 роки тому

    Damn You are good

  • @saurabhverma7366
    @saurabhverma7366 2 роки тому +1

    555

  • @eamytb
    @eamytb Місяць тому

    Custom comparator in Python sucks

  • @donabiswas6266
    @donabiswas6266 Місяць тому

    My core logic was correct but execution was wrong

  • @numberonep5404
    @numberonep5404 2 роки тому

    I love it

  • @lakshyasaharan5348
    @lakshyasaharan5348 2 роки тому +3

    First

  • @guruprasadv7972
    @guruprasadv7972 2 роки тому +1

    Sixth

  • @brogrammer8783
    @brogrammer8783 2 роки тому +1

    Fourth

  • @monicawang8447
    @monicawang8447 2 роки тому +4

    Hey can anyone explain why we return -1 when n1 + n2 > n2 + n1? I'm confused about how returning -1 or 1 works here..Thanks!

    • @iaingavinsoutherland4369
      @iaingavinsoutherland4369 2 роки тому +3

      Hey, my guess is as good as any but I was playing around with it. We're trying to compare elements, e.g. if we have a='30' and b='3' (in python notation), we are trying to figure out if a+b ('303') is larger than b+a ('330'). The cmp_to_key function is part of the functools module, and tells the sorting to use our comparison method. So if we want to decide whether to put '30' or '3' first, we look at whether a+b or b+a is bigger.
      In order to tell the key which is better, in almost a boolean sense, we say positive means change/don't change order, and negative means don't change/change order. So if we get in a='30' and b='3', (note that in the key function, the first value is later, so we would have a list that had [......, 3, 30, .......] in there, if a+b > b+a (303 > 330, not true in this case), we would pass a -1 (red flag), and the key function would switch order to have [...., 30, 3, .....]. In real life, that case wouldn't be true, and the key function would receive a 1 (green flag) so that it wouldn't have to switch the two.
      Bit long, but it's an odd question. Can't imagine answering this in an interview. Also note that you could return any positive/negative (e.g. 420/-69), but you can't return a 0 or it gets screwy. The delineator is positive vs negative as switch position after comparison vs don't switch position after comparison.

    • @SkyeTian
      @SkyeTian 2 роки тому +1

      1. This key is eventually helping sorted() to arrange elements in ascending order; 2. It returns a negative value indicating the first argument is lesser than the second argument or a positive value indicating the first argument is greater than the second argument. So if n1 + n2 > n2 + n1 we want to put n1 first so we must tell it that n1 is the smaller one thus return -1

  • @shrio272
    @shrio272 2 роки тому +1

    Second

  • @awukugodfred6610
    @awukugodfred6610 2 роки тому +1

    Third